最近,我们不得不使用不记名令牌实现基于 Sails 的 API 的保护,这就是我们所做的(用 测试0.9.x
):
1)将护照作为自定义中间件连接config/passport.js
(或者可以是config/express.js
,取决于您的口味):
/**
* Passport configuration
*/
var passport = require('passport');
module.exports.express = {
customMiddleware: function(app)
{
app.use(passport.initialize());
app.use(passport.session());
}
};
2) 使用以下策略保护必要的控制器/操作config/policies.js
:
module.exports.policies = {
// Default policy for all controllers and actions
'*': 'authenticated'
};
3) 创建检查承载的策略api/policies/authenticated.js
:
/**
* Allow any authenticated user.
*/
var passport = require('passport');
module.exports = function (req, res, done) {
passport.authenticate('bearer', {session: false}, function(err, user, info) {
if (err) return done(err);
if (user) return done();
return res.send(403, {message: "You are not permitted to perform this action."});
})(req, res);
};
services/passport.js
4)在(或您认为更适合您的特定应用程序的其他任何地方)定义护照的承载策略:
var passport = require('passport'),
BearerStrategy = require('passport-http-bearer').Strategy;
/**
* BearerStrategy
*
* This strategy is used to authenticate either users or clients based on an access token
* (aka a bearer token). If a user, they must have previously authorized a client
* application, which is issued an access token to make requests on behalf of
* the authorizing user.
*/
passport.use('bearer', new BearerStrategy(
function(accessToken, done) {
Tokens.findOne({token: accessToken}, function(err, token) {
if (err) return done(err);
if (!token) return done(null, false);
if (token.userId != null) {
Users.find(token.userId, function(err, user) {
if (err) return done(err);
if (!user) return done(null, false);
// to keep this example simple, restricted scopes are not implemented,
// and this is just for illustrative purposes
var info = { scope: '*' }
done(null, user, info);
});
}
else {
//The request came from a client only since userId is null
//therefore the client is passed back instead of a user
Clients.find({clientId: token.clientId}, function(err, client) {
if (err) return done(err);
if (!client) return done(null, false);
// to keep this example simple, restricted scopes are not implemented,
// and this is just for illustrative purposes
var info = { scope: '*' }
done(null, client, info);
});
}
});
}
));
这样,您就可以通过将您的不记名放在Authorization
标头中来访问 API:Bearer 8j4s36...
。
在此示例中,使用单独的服务器来请求/发出令牌,但您也可以在同一个应用程序中执行此操作(然后您必须仅将策略应用于选定的控制器)。