ppoliani
ppoliani

Reputation: 4906

NodeJS OAuth2.0 principles

Recently I was working on a nodeJS project and I was thinking how to go about and implement the security module of my mobile application. I had a previous experience from OAuth 2.0 protocol which I used in C# projects in the past.

In .NET there are two nice open source project

  1. https://github.com/thinktecture/Thinktecture.IdentityServer.v3
  2. https://github.com/thinktecture/Thinktecture.AuthorizationServer

The former is an Identity Provider supporting federated authentication and the later is an OAuth 2.0 provider.

So I decided to employ the same security infrastructure for my nodeJS app. But as far as I know, there is nothing equivalent to those projects.

I found some really nice project, which are not yet complete but are a good start:

In addition, I came across a nice article that suggests a nice way to deal with authentication in nodeJS. https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/ and a similar answer to a questtion on stackoverflow. Auth between a website and self-owned API

From what I understood, expressJwt guards our api's and basically will validate the access token sent by the user. But I'd like to go a step further, and associate a token with app specific scopes, in a similar way that one would do with the OAuth2.0 protocol. So for example, I would like to assign a write, read etc. scopes and have expressJwt check if the user's token has the required scopes to access as specific API endpoint.

I would be grateful if you could provide me with some suggestions about how to deal with this topic.

Upvotes: 2

Views: 1440

Answers (1)

José F. Romaniello
José F. Romaniello

Reputation: 14156

First, you need to generate a token with such claims. This could be in an API or some other place:

var jwt = require('jsonwebtoken');

var claims = {
  name: user.name
  can_write: true,
  can_post_timeline: false
};

var token = jwt.sign(claims, 'my-super-secret');

Then, to validate you will do something like this:

var jwt = require('express-jwt');

app.use(jwt({secret: 'my-super-secret'}));

function require_time_line_access (req, res, next) {
  if (!req.user.can_post_timeline) return res.send(401);
  next();
}

app.post('/timeline', 
  require_time_line_access,
  function(req, res) {
    //do timeline stuff
  });

express-jwt validates the signature of the token, expiration and few other things. If everything is okay it puts the decoded token in req.user, and if is not okay it returns 401.

require_time_line_access is a middleware that ensure the user has this claim, if it doesnt it returns 401. You can put this middleware in every endpoint that needs this claim.

Upvotes: 2

Related Questions