Quantcast
Channel: Node.js – SitePoint
Viewing all articles
Browse latest Browse all 225

Using JSON Web Tokens with Node.js

$
0
0

Front end frameworks and libraries such as Ember, Angular, and Backbone are part of a trend towards richer, more sophisticated web application clients. As a consequence of this, server-side components are unburdened from many of their traditional responsibilities, in essence becoming more like API's. This API approach allows a greater decoupling of the traditional "front end" and "back end" parts of an application. One set of developers can build the back end independently from the front end engineers, with the additional benefit that testing becomes simpler. This approach also makes it much easier to build, say, a mobile application that shares the same back end as your web application. One of the challenges when providing an API is authentication. In traditional web applications, the server responds to a successful authentication request by doing two things. First, it creates a session using some storage mechanism. Each session has its own identifier - usually a long, semi-random string - which is used to retreive information about the session on future requests. Secondly, that information is sent to the client by way of headers instructing it to set a cookie. The browser automatically attaches the session ID cookie to all subsequent requests, allowing the server to identify the user by retrieving the appropriate session from storage. This is how traditional web applications get around the fact that HTTP is stateless. APIs should be designed to be truly stateless. This means no login or logout methods and no sessions. API designers can't rely on cookies either, as there is no guarantee that requests will be made via a web browser. Clearly, we need an alternative mechanism. This article looks at one possible mechanism designed to tackle the problem - JSON Web Tokens, or JWTs (pronounced jots). The examples in this article uses Node's Express framework on the back end, and Backbone on the client.

Background

Let's briefly look at a few common approaches to securing APIs. One is to use HTTP Basic Authentication. Defined in the official HTTP specification, this essentially involves setting a header on the server response which indicates authentication is required. The client must respond by attaching their credentials, including their password, to every subsequent request. If the credentials match, the user information is made available to the server application as as variable. The second approach is very similar, but using the application's own authentication mechanism. This usually involves checking the supplied credentials against those in storage. As with HTTP Basic Authentication, this requires that the user's credentials are supplied with each and every call. The third approach is OAuth (or OAuth2). Designed to a large extent for authenticating against third-party services, it can be rather challenging to implement, at least on the server-side. A fourth approach is using tokens. That's what we're going to look at in this article. We'll look at an implementation that utilizes JavaScript on both the front and back ends.

The Token Approach

Instead of supplying credentials such as a username and password with every request, we can allow the client to exchange valid credentials for a token. This token gives the client access to resources on the server. Tokens are generally much longer and more obfuscated than a password. For example, the JWTs we're going to be dealing with are on the order of ~150 characters. Once the token is obtained, it must be sent with every API call. However, this is still more secure than sending a username and password with every request, even over HTTPS. Think of the token like a security pass. You identify yourself at the front desk of a restricted building on arrival (supply your username and password), and if you can be successfully identified you're issued a security pass. As you move around the building (attempt to access resources by making calls to the API) you are required to show your pass, rather than go through the initial identification process all over again.

About JWTs

JWTs are a draft specification, although in essence they are really just a more concrete implementation of an authentication and authorization mechanism that is already commonplace; that of exchanging tokens. A JWT is split into three parts, separated by periods. JWTs are URL-safe, meaning they can be used in query string parameters. The first part of a JWT is an encoded string representation of a simple JavaScript object which describes the token along with the hashing algorithm used. The example below illustrates a JWT using HMAC SHA-256. [js] { "typ" : "JWT", "alg" : "HS256" } [/js] After encoding, the object becomes this string: [code] eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9 [/code] The second part of the JWT forms the core of the token. It too represents a JavaScript object, which contains a few pieces of information. Some of these fields are required, and some are optional. An example, taken from the draft specification, is shown below. [js] { "iss": "joe", "exp": 1300819380, "http://example.com/is_root": true } [/js] This is called a JWT Claims Set. For the purposes of this article, we're going to ignore the third parameter, but you can read more in the specification. The iss property is short for issuer, and specifies the person or entity making the request. Typically, this would be the user accessing the API. The exp field, short for expires, is used to limit the lifetime of the token. Once encoded, the JSON token looks like this: [code] eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ [/code] The third, and final, part of the JWT is a signature generated based on the header (part one) and the body (part two). The signature for our example JWT is shown below. [code] dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk [/code] The resulting complete JWT looks like this: [code] eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk [/code] There are a number of additional, optional properties supported in the specification. Among them are iat representing the time at which the token was issued, nbf (Not Before) to indicate the token should not be accepted before a certain time, and aud (audience) to indicate the recipients the token is intended for.

Continue reading %Using JSON Web Tokens with Node.js%


Viewing all articles
Browse latest Browse all 225

Latest Images

Trending Articles



Latest Images