在Oauth2orize模块中使用资源所有者密码

时间:2013-06-30 13:55:02

标签: node.js passport.js

我正在开发一个带有移动客户端的应用程序,我想将Oauth2orize部署为Oauth服务器,并使用资源所有者密码方式进行身份验证。但我无法理解流程应该如何。我搜索了很多例子,但找不到这个例子。

流程应该为客户提供一个令牌?

1 个答案:

答案 0 :(得分:4)

这有点晚了,但我认为这篇文章可以帮助其他人。我只花了一个星期试图实现这个,因为oauth2orize将所有oauth流混合在样本中的一个文件中,因此很难找出用于获得所需结果的那个。

要开始回答您的问题,请按照here所述询问资源所有者密码授予。这应该让您在oauth2定义的步骤上领先一步,以便为令牌和可选的刷新令牌交换用户名(或电子邮件)和密码。

步骤1:客户端使用用户名和密码向授权服务器请求令牌

步骤2:如果客户端具有有效凭据,授权服务器会向客户端发出令牌

因此,您开始以包含用户名,密码和grant_type参数的application / x-www-form-urlencoded格式向身份验证资源发送请求,您也可以选择使用范围。 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);

这是您如何做的基本示例。此外,您应该在此端点上启用某种保护。您可以使用passport-oauth2-client-password模块进行客户端凭据验证。这样,client函数中的oauth2orize.exchange.password变量将包含有关尝试访问资源的客户端的信息,从而为您的授权服务器进行额外的安全检查。