我正在开发一个带有移动客户端的应用程序,我想将Oauth2orize部署为Oauth服务器,一种使用资源所有者密码方式进行身份验证的方法。但我无法理解该如何流动。我寻找了很多的例子,但找不到一个在哪里使用。
向客户端提供令牌的流程应该是什么?
发布于 2015-08-25 14:18:06
这件事来得有点晚,但我认为这篇文章能帮到别人。我只是花了一周时间来实现这一点,因为oauth2orize将所有oauth流混合到示例中的一个文件中,因此很难确定要使用哪一个来获得所需的结果。
要开始回答您的问题,您需要询问有关资源所有者密码授予的问题,如所述的这里。这将使您可以在oauth2定义的步骤上先发制人,将用户名(或电子邮件)和密码交换为令牌,并可选择交换刷新令牌。
步骤1:客户端使用用户名和密码向授权服务器请求令牌
步骤2:如果客户端具有有效的凭据,授权服务器将向客户端发出令牌。
因此,您开始以application/x form-urlencoded格式向身份验证资源发送包含用户名、密码和grant_type参数的请求,也可以选择使用作用域。Oauth2orize提供了server.token()函数,它生成一个中间件来解析这个请求。
app.post('/token', server.token(), server.errorHandler());但是在这个阶段之前,您应该创建并配置服务器。我通常使用不同的文件并使用module.exports将中间件传递回应用程序。
authorization.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);这是你如何做这件事的一个基本例子。此外,应该在此端点上启用某种类型的保护。您可以使用客户端凭据验证与护照-OAuth2-客户端密码模块。这样,client函数中的oauth2orize.exchange.password变量将包含有关试图访问资源的客户端的信息,从而为授权服务器启用额外的安全检查。
https://stackoverflow.com/questions/17391065
复制相似问题