OAuth 2.0 (由 RFC 6749 正式指定) 提供的授权框架,它允许用户授权访问第三方应用程序。授权时,该应用程序发出的令牌作为身份验证凭据来使用。这有两个主要的安全优势:
这些好处是确保Web应用程序的安全性,使的OAuth2.0的API认证的主要标准尤为重要。
当使用OAuth2.0保护的API端点,也有必须执行三个不同的步骤:
OAuth2orize, a sibling project to Passport, provides a toolkit for implementing OAuth 2.0 authorization servers.
授权是一个复杂的过程,涉及请求的应用程序和用户,以及提示权限用户,从而确保足够的细节使做出明智的决定。
此外,它是由实现者确定哪些限制可以放在有关访问范围的应用,以及随后实施这些限制。
作为一个工具包,OAuth2orize并不试图做出执行决定。本指南不涉及这些问题,但强烈建议服务部署的OAuth2.0有涉及到安全方面的考虑一个完整的认识。
OAuth 2.0 provides a framework, in which an arbitrarily extensible set of token types can be issued. In practice, only specific token types have gained widespread use.
Bearer tokens are the most widely issued type of token in OAuth 2.0. So much so, in fact, that many implementations assume that bearer tokens are the only type of token issued.
Bearer tokens can be authenticated using the passport-http-bearer module.
$ npm install passport-http-bearer
passport.use(new BearerStrategy(
function(token, done) {
User.findOne({ token: token }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
return done(null, user, { scope: 'read' });
});
}
));
The verify callback for bearer tokens accepts the token
as an argument. When invoking done
, optionalinfo
can be passed, which will be set by Passport at req.authInfo
. This is typically used to convey the scope of the token, and can be used when making access control checks.
app.get('/api/me',
passport.authenticate('bearer', { session: false }),
function(req, res) {
res.json(req.user);
});
Specify passport.authenticate()
with the bearer
strategy to protect API endpoints. Sessions are not typically needed by APIs, so they can be disabled.