NodeJS OAuth2.0 principles

我们两清 提交于 2019-12-24 04:51:43

问题


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:

  • https://www.npmjs.org/package/node-oauth2-server
  • https://github.com/domenic/restify-oauth2

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.


回答1:


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.



来源:https://stackoverflow.com/questions/23240339/nodejs-oauth2-0-principles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!