2013-06-30 43 views
2

我正在开发一个应用程序,其中我想将Oauth2orize作为Oauth服务器部署到使用资源所有者密码方式进行认证的移动客户端。但我无法理解流量应该如何。我搜索了很多例子,但是找不到使用它的地方。在Oauth2orize模块中使用资源所有者密码

该流程应该给客户端一个令牌?

+0

同样在这里,我有点了解oauth2orize的用法 – Luc

回答

4

这有点晚了,但我认为这篇文章可以帮助别人。我只花了一个星期的时间试图实现这个功能,因为oauth2orize将样本中的所有oauth流混合到一个文件中,因此很难弄清楚使用哪一个来获得所需的结果。

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

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

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

因此,您开始以application/x-www-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); 

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

相关问题