authentication angular nodejs with JWT

Why use it?

Here are some advantages of choosing JWT:

  • Standard: JWT is becoming a standard, and there a multiple libraries for a lot of languages (Ruby, Java, Python, Node, Backbone). So the integration with your language or technology should be pretty easy.
  • Cross-domain / CORS: Since the information is transmitted using an HTTP header, you are able to make AJAX requests to any server or domain.
  • Protection from CSRF: The token must be included in every request made to the server, and will be validated by the server. The token is linked to the user’s current session.
  • Server side Scalability: The token is self-contained(i.e. contains all the user info), so there’s no need to keep a session store. The rest of the state lives in the client’s local storage.
    The token might be generated anywhere, so you are not tied to any specific authentication scheme, decoupling this process from your application.

Warning: since the information is transmitted in an HTTP header and its size is limited, the token size could be an issue.

Basic steps

1. when user login successfully, return client the signed token. Sign module is the jsonwebtoken

2. store the token in the browser in angular.

3. Have a interceptor send the bearer + token to server with each request.

4. nodejs’ get/put/post..ect would add jwt(secret) in the config for urls needs to be protected so that the middleware could ‘verify’ the token from the client. Verify module is the express-jwt

About the verify

  1. When client calls /authenticate, server first validates user credentials against database to make this user authenticated. And this “expensive” operation performed only once for whole token life. Then, server prepares JSON object, holding useful user info, and encrypts it to get JWT token.
  2. This token sent only once to client, stored in a browser, and then sent back to server on every client request to /api.
  3. During processing client /api request, server must “verify” token for validity (JWT does it for you). But this does not mean to check user credentials against database again. Only just decrypting token to get JSON object back, HMAC-SHA256 verification – quite fast.
  4. Having JSON object with useful user info (claims), server can allow or not this specific user to access requested resource under /api route.

During token verification, no database check of user credentials is needed, because server have to trust received and verified (successfully decrypted) token. No server sessions storage is required to identify user.

You can think of JWT tokens like a simple session info, stored on client in an encrypted form. But if you need to cache more data in a user session info, I think, you still need some sort of sessions storage on a server, rendering JWT idea to almost useless compared to traditional Session ID in cookies.

HERE is another article explaining token-based auth and jwt.

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.

1
2
3
4
{
  "typ" : "JWT",
  "alg" : "HS256"
}

After encoding, the object becomes this string:

1
eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9

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.

1
2
3
4
5
{
  "iss": "joe",
  "exp": 1300819380,
}

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:

1
eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ

The third, and final, part of the JWT is a signature generated based on the header (part one) and the body (part two) along with our serectKey hashed by the algorithm specified in the header(here is ‘HS256’). The signature for our example JWT is shown below.

1
dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk

The resulting complete JWT looks like this:

1
eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s