我正在开发一个带有移动客户端的应用程序,我想为其部署 Oauth2orize 作为 Oauth 服务器,并使用资源所有者密码方式进行身份验证。但我无法理解流程应该如何。我搜索了很多示例,但找不到此用途的示例。
向客户提供令牌的流程应该是什么?
我正在开发一个带有移动客户端的应用程序,我想为其部署 Oauth2orize 作为 Oauth 服务器,并使用资源所有者密码方式进行身份验证。但我无法理解流程应该如何。我搜索了很多示例,但找不到此用途的示例。
向客户提供令牌的流程应该是什么?
这有点晚了,但我认为这篇文章可以帮助其他人。我只花了一周时间尝试实现这一点,因为 oauth2orize 将所有 oauth 流混合在样本中的一个文件中,因此很难确定使用哪个流来获得所需的结果。
要开始回答您提出的有关资源所有者密码授权的问题,请参阅此处。这应该让您在 oauth2 定义的步骤上抢先一步,将用户名(或电子邮件)和密码交换为令牌和可选的刷新令牌。
第 1 步:客户端使用用户名和密码向授权服务器请求令牌
第 2 步:如果客户端具有有效凭据,授权服务器会向客户端颁发令牌
因此,您开始以 application/x-www-form-urlencoded 格式向身份验证资源发送请求,其中包含用户名、密码和 grant_type 参数,您也可以选择使用范围。Oauth2orize 提供了server.token()
生成中间件来解析这个请求的函数。
app.post('/token', server.token(), server.errorHandler());
但在此阶段之前,您应该已创建并配置了服务器。我通常使用不同的文件并使用 module.exports 将中间件传回应用程序。
授权.js 文件
// Create the server
var server = oauth2orize.createServer();
// Setup the server to exchange a password for a token
server.exchange(oauth2orize.exchange.password(function (client, username, password, scope, done) {
// Find the user in the database with the requested username or email
db.users.find({ username: username }).then(function (user) {
// If there is a match and the passwords are equal
if (user && cryptolib.compare(password, user.password)) {
// Generate a token
var token = util.generatetoken();
// Save it to whatever persistency you are using
tokens.save(token, user.id);
// Return the token
return done(null, /* No error*/
token, /* The generated token*/
null, /* The generated refresh token, none in this case */
null /* Additional properties to be merged with the token and send in the response */
);
} else {
// Call `done` callback with false to signal that authentication failed
return done(null, false);
}
}).catch(function (err) {
// Signal that there was an error processing the request
return done(err, null);
})
};
// Middlewares to export
module.exports.token = [
server.token(),
server.errorHandler()
];
稍后在您的应用程序中,您编写类似这样的内容
var auth = require('./authorization');
app.post('/token', auth.token);
这是您如何执行此操作的基本示例。此外,您应该在此端点上启用某种保护。您可以将客户端凭据验证与 passport-oauth2-client-password 模块一起使用。这样,函数client
中的变量oauth2orize.exchange.password
将包含有关尝试访问资源的客户端的信息,从而为您的授权服务器启用额外的安全检查。