项目作者: saviogl

项目描述 :
Sails hook提供jwt认证方案,例如策略,路由,控制器,服务。
高级语言: JavaScript
项目地址: git://github.com/saviogl/sails-hook-jwt-auth.git
创建时间: 2015-04-24T16:36:52Z
项目社区:https://github.com/saviogl/sails-hook-jwt-auth

开源协议:

下载


sails-hook-jwt-auth

Hook that provides jwt authentication sails-compatible scheme, such as policies, routes, controllers, services.

Installation

Within a Sails App structure:

  1. npm install --save sails-hook-jwt-auth

Service

This module globally expose a service which integrates with the jsonwebtoken (https://github.com/auth0/node-jsonwebtoken) and provide the interface to apply the jwt specification (http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html).

  1. var jwt = require('jsonwebtoken');
  2. module.exports.issueToken = function(payload, options) {
  3. var token = jwt.sign(payload, process.env.TOKEN_SECRET || sails.config.jwt.token_secret, options);
  4. return token;
  5. };
  6. module.exports.verifyToken = function(token, callback) {
  7. return jwt.verify(token, process.env.TOKEN_SECRET || sails.config.jwt.token_secret, {}, callback);
  8. };

Policy

The authToken.js policy is just like any other Sails policy and can be applied as such. It’s responsible for parsing the token from the incoming request and validating it’s state.

  1. module.exports = function(req, res, next) {
  2. var token;
  3. if ( req.headers && req.headers.authorization ) {
  4. var parts = req.headers.authorization.split(' ');
  5. if ( parts.length == 2 ) {
  6. var scheme = parts[0],
  7. credentials = parts[1];
  8. if ( /^Bearer$/i.test(scheme) ) {
  9. token = credentials;
  10. }
  11. } else {
  12. return res.json( 401, { err: { status: 'danger', message: res.i18n('auth.policy.wrongFormat') }});
  13. }
  14. } else if ( req.param('token') ) {
  15. token = req.param('token');
  16. // We delete the token from param to not mess with blueprints
  17. delete req.query.token;
  18. } else {
  19. return res.json( 401, { err: { status: 'danger', message: res.i18n('auth.policy.noAuthorizationHeaderFound') }});
  20. }
  21. TokenAuth.verifyToken(token, function(err, decodedToken) {
  22. if ( err ) return res.json( 401, { err: { status: 'danger', message: res.i18n('auth.policy.invalidToken'), detail: err }});
  23. req.token = decodedToken.sub;
  24. next();
  25. });
  26. };

Use it as you would use any other sails policy to enable jwt authentication restriction to your Controllers/Actions:

  1. module.exports.policies = {
  2. ...
  3. 'UserController': ['authToken'],
  4. ...
  5. };

Model

This hook sets up a basic User model with some defaults attributes required to implement the jwt authentication
scheme.

  1. var bcrypt = require('bcrypt');
  2. module.exports = {
  3. attributes: {
  4. email: {
  5. type: 'email',
  6. required: true,
  7. unique: true
  8. },
  9. password: {
  10. type: 'string',
  11. required: true,
  12. },
  13. active: {
  14. type: 'boolean',
  15. defaultsTo: true
  16. },
  17. isPasswordValid: function (password, cb) {
  18. bcrypt.compare(password, this.password, cb);
  19. }
  20. }
  21. };

The User model can be extended with any property you want by defining it in your own Sails project.

Routes

These are the routes provided by this hook:

  1. module.exports.routes = {
  2. 'post /login' : 'AuthController.login',
  3. 'post /signup' : 'AuthController.signup',
  4. 'get /activate/:token' : 'AuthController.activate'
  5. };

/login

The POST request to this route /login must be sent with these body parameters:

  1. {
  2. email: 'email@test.com',
  3. password: 'test123'
  4. }

The POST response:

  1. {
  2. user: user,
  3. token: jwt_token
  4. }

Make sure that you provide the acquired token in every request made to the protected endpoints, as query parameter token or as an HTTP request Authorization header Bearer TOKEN_VALUE.

/signup

The POST request to this route /signup must be sent with these body parameters:

  1. {
  2. email: 'email@test.com',
  3. password: 'test123',
  4. confirmPassword: 'test123',
  5. }

The POST response:

If account activation feature is disabled, the reponse will be the same as the POST /login. If it’s enabled you will set the response as you want in the sendAccountActivationEmail function.

/activate/:token

Account Activation

This feature is off by default and to enable it you must override the requireAccountActivation configuration and implement the function sendAccountActivationEmail:

  1. module.exports.jwt = {
  2. requireAccountActivation: true,
  3. sendAccountActivationEmail: function (res, user, link){
  4. sails.log.info('An email must be sent to this email: ', user.email, ' with this activation link: ', link);
  5. return res.json(200, { success: 'Email has been sent to user!' });
  6. }
  7. }