JWT Token strategy for frontend and backend JWT Token strategy for frontend and backend node.js node.js

JWT Token strategy for frontend and backend


If we're talking about not only working but also secure stateless authentication you will need to consider proper strategy with both access and refresh tokens.

  1. Access token is a token which provides an access to a protected resource.Expiration here might be installed approximately in ~1 hour (depends on your considerations).

  2. Refresh token is a special token which should be used to generate additional access token in case it was expired or user session has been updated. Obviously you need to make it long lived (in comparison with access token) and secure as much as possible.Expiration here might be installed approximately in ~10 days or even more (also depends on your considerations).

FYI: Since refresh tokens are long lived, to make them really secure you might want to store them in your database (refresh token requests are performed rarely). In this way, let's say, even if your refresh token was hacked somehow and someone regenerated access/refresh tokens, of course you will loose permissions, but then you still can login to the system, since you know login/pass (in case you will use them later) or just by signing in via any social network.


Where to store these tokens?

There are basically 2 common places:

  1. HTML5 Web Storage (localStorage/sessionStorage)

Good to go, but in the same time risky enough. Storage is accessible via javascript code on the same domain. That means in case you've got XSS, your tokens might be hacked. So by choosing this method you must take care and encode/escape all untrusted data. And even if you did it, I'm pretty sure you use some bunch of 3rd-party client-side modules and there is no guarantee any of them has some malicious code.

Also Web Storage does not enforce any secure standards during transfer. So you need to be sure JWT is sent over HTTPS and never HTTP.

  1. Cookies

With specific HttpOnly option cookies are not accessible via javascript and are immune to XSS. You can also set the Secure cookie flag to guarantee the cookie is only sent over HTTPS.However, cookies are vulnerable to a different type of attack: cross-site request forgery (CSRF).In this case CSRF could be prevented by using some kind of synchronized token patterns. There is good implementation in AngularJS, in Security Considerations section.

An article you might want to follow.

To illustrate how it works in general:

enter image description here


Few words about JWT itself:

To make it clear there is really cool JWT Debugger from Auth0 guys.There are 2 (sometimes 3) common claims types: public, private (and reserved).

An example of JWT body (payload, can be whatever you want):

{       name: "Dave Doe",  isAdmin: true,  providerToken: '...' // should be verified then separately}

More information about JWT structure you will find here.


To answer the two specific questions that you posed:

What would be the flow when a user signs in with an OAuth provider for the first time? Should emberjs send all the details to the backend on every sign in so that backend can add new users to the db?

Whenever a user either signs up or logs in via oauth and your client receives a new access token back, I would upsert (update or insert) it into your users table (or collection) along with any new or updated information that you retrieved about the user from the oauth provider API. I suggest storing it directly on each users record to ensure the access token and associated profile information changes atomically. In general, I'd usually compose this into some sort of middleware that automatically performs these steps when a new token is present.

What should be part of my JWT body? I was thinking uid and provider supplied access token. One issue I can think of here is that provider specific access token can change. User can revoke the token from provider's site and signs up again with emberjs.

The JWT body generally consists of the users claims. I personally see little benefit to storing the provider access token in the body of a JWT token since it would have few benefits to your client app (unless you are doing a lot of direct API calls from your client to their API, I prefer to do those calls server-side and send my app client back a normalized set of claims that adhere to my own interface). By writing your own claims interface, you will not have to work around the various differences present from multiple providers from your client app. An example of this would be coalescing Twitter and Facebook specific fields that are named differently in their APIs to common fields that you store on your user profile table, then embedding your local profile fields as claims in your JWT body to be interpreted by your client app. There is an added benefit to this that you will not be persisting any data that could leak in the future in an unencrypted JWT token.

Whether or not you are storing the oauth provider supplied access token within the JWT token body, you will need to grant a new JWT token every time the profile data changes (you can put in a mechanism to bypass issuing new JWT tokens if no profile updates occurred and the previous token is still good).

In addition to whatever profile fields you store as claims in the JWT token body, I would always define the standard JWT token body fields of:

{    iss: "https://YOUR_NAMESPACE",    sub: "{connection}|{user_id}",    aud: "YOUR_CLIENT_ID",    exp: 1372674336,    iat: 1372638336}


For any OAuth workflow you should definitely use the passportjs library. You should also read the full documentation. It is easy to understand but I made the mistake of not reading the the whole thing the first time and struggled. It contains OAuth Authentication with over 300 Providers and Issuing Tokens.

Nevertheless, if you want to do it manually or want a basic understanding, here is the flow that I'd use:

  1. Frontend has a login page listing Sign-in with Google/Facebook etc where OAuth is implemented.

  2. Successful OAuth results in a uid, login, access_token etc. (JSON object)

  3. You POST the JSON object to your /login/ route in your Node.js application. (Yes, you send the whole response regardless if it's a new or existing user. Sending extra data here is better than doing two requests)

  4. The backend application reads the uid and the access_token. Ensure that the access_token is valid by following (https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#checktoken) or asking for user data from the provider using the access token. (This will fail for invalid access token since OAuth access tokens are generated on a per app/developer basis) Now, search your backend DB.

  5. If the uid exists in the database, you update the user's access_token and expiresIn in the DB. (The access_token allows you to get more information from Facebook for that particular user and it provides access for a few hours usually.)

  6. Else, you create a new user with uid, login etc info.

  7. After updating the access_token or creating a new user, you send JWT token containing the uid. (Encode the jwt with a secret, this would ensure that it was sent by you and have not been tampered with. Checkout https://github.com/auth0/express-jwt)

  8. On the frontend after the user has received the jwt from /login, save it to sessionStorage by sessionStorage.setItem('jwt', token);

  9. On the frontend, also add the following:

if ($window.sessionStorage.token) { xhr.setRequestHeader("Authorization", $window.sessionStorage.token); }

This would ensure that if there is a jwt token, it is sent with every request.

  1. On your Node.js app.js file, add

app.use(jwt({ secret: 'shhhhhhared-secret'}).unless({path: ['/login']}));

This would validate that jwt for anything in your path, ensuring that the user is logged-in, otherwise not allow access and redirect to the login page. The exception case here is /login since that's where you give both your new or unauthenticated users a JWT.

You can find more information on the Github URL on how to get the token and to find out which user's request you are currently serving.