sails-permissions
sails-permissions copied to clipboard
JWT Support?
Thanks for this awesome work!
Is there any possibility to use JWT Token instead of Cookies?
+1 Also need Bearer authentication
+1
+1 8)
I was able to put together JWT support with a bit of a workaround here:
- Disable config/policies/sessionAuth.js:
module.exports = function(req, res, next) {
return next();
};
- Add a tokenAuth.js policy:
/**
* tokenAuth
*
* @module Policies
* @description Policy that verifies a given JWT token.
* If successful, associated user object is stored in req.user for future use.
* @docs http://sailsjs.org/#!documentation/policies
* @see http://github.com/auth0/express-jwt
*
*/
var jwt = require('express-jwt');
module.exports = jwt({secret: sails.config.session.secret});
- Override the callback function in AuthController.js to sign the JWT and include it on login:
/**
* Create a authentication callback endpoint (Overrides sails-auth)
*
* @param {Object} req request object
* @param {Object} res response object
*/
callback: function (req, res) {
// since we disabled sessions, we must also override req.flash
req.flash = function(type, message) {
var err = new Error(message);
err.code = 400;
return err;
};
sails.services.passport.callback(req, res, function (err, user) {
if (err || !user) {
return res.forbidden(err);
}
req.login(user, function (err) {
if (err) {
return res.forbidden(err);
}
var token = require('jsonwebtoken').sign(
user,
sails.config.session.secret,
{ expiresIn: sails.config.session.jwtExpiry + "h" }
);
// Upon successful login, optionally redirect the user if there is a
// `next` query param
if (req.query.next) {
res.status(302).set('Location', req.query.next);
}
sails.log.info('user', resp.user, 'authenticated successfully at', new Date());
return res.json( {
user: user,
token: {
payload: token,
expires: sails.config.session.jwtExpiry
}
});
});
});
}
@khchan
- Override the callback function in AuthController.js ...
So we have to create AuthController.js? (sails generate controller auth
?)
yes you will have to include your own auth controller that overrides just that method.
@khchan
- Disable config/policies/sessionAuth.js: ...
Can we just remove sessionAuth
from config/policies.js:
module.exports.policies = {
'*': [
'basicAuth',
'passport',
// 'sessionAuth',
'ModelPolicy',
'AuditPolicy',
'OwnerPolicy',
'PermissionPolicy',
'RolePolicy',
'CriteriaPolicy'
],
...
- Add a tokenAuth.js policy:
Where we include this policy to our app?
Thanks
@Keramet I don't think you can just remove sessionAuth. he said you're just overriding 1 method in the auth controller. I imagine you still need the rest.
@westlakem If I want to use JWT, why I need session (and therefore - sessionAuth)? All necessary info will include in token. Am I rigth?
@Keramet if it works that way, you can remove it from the policy list. This is more of a workaround than an actual fix.
+1 for this feature
++
It’s been over 2 years now... any support for this coming?