Node OAuth2 server 初步尝试和验证

来源:互联网 发布:windows局域网共享文件 编辑:程序博客网 时间:2024/06/05 11:47

由于在身份验证过程中不允许在客户端存储敏感性信息,如用户账号和密码,同时为了更容易地在Cocoa和.NET上进行OAuth2验证,有人尝试使用Node来实现一个OAuth2验证服务器。针对这个问题,笔者决定进行初步尝试和验证。

相关介绍文档和Github地址:

http://blog.papersapp.com/oauth-server-in-node-js/

https://github.com/thomseddon/node-oauth2-server/


使用方法:

1.      访问https://github.com/mekentosj/oauth2-example,下载OAuth2服务器示例代码。

2.      调用node seed.js创建一个用户账户。

3.  在工程目录下,运行npm start开启OAuth2服务器,在浏览器上访问http://localhost:3000/ 便可以看到用户登录界面。这里可以使用示例中给出的用户名(alex@example.com)和密码(test)进行登录。

源代码:seed.js

varapp = require('./app');varmodels = require('./models');models.User.create({   //email即为用户名   email: 'alex@example.com',    //经过哈希的密码   哈希前值为test   hashed_password:'$2a$10$aZB36UooZpL.fAgbQVN/j.pfZVVvkHxEnj7vfkVSqwBOBZbB/IAAK'},function() {  models.OAuthClientsModel.create({    //客户端id    clientId: 'papers3',    //客户端secret    clientSecret: '123',    redirectUri: '/oauth/redirect'  }, function() {    process.exit();  });});


从服务器获取Token信息

1. 下载这份getToken.js代码。

2. 打开Terminal,输入命令node getToken.js从服务器获得Token。

3. 在Terminal上可以看到返回的Token信息。具体信息为

{

  "token_type":"bearer",

  "access_token":"ff5b3b0d3ba171f3bb534abc6edbe45ca9555b63",

  "expires_in": 3600,

  "refresh_token":"1b3bd985f9cbc932d11883b69c589a6399b7fda1"

}

 

源代码:getToken.js

varrequest = require('request'); //client_idvart_client_id = 'papers3';//client_secretvart_client_secret = '123';//clientCredentials  以client_id:client_secret形式组合并转换成Base64-encodedvarclientCredentials = (t_client_id + ':'+t_client_secret).toString('base64');//用户名vart_username = 'alex@example.com';//密码vart_password = 'test'; console.log(clientCredentials); //发送Post请求获取Tokenrequest.post({   url: 'http://' + clientCredentials +'@localhost:3000/oauth/token',  form: {    grant_type: 'password',    username: t_username,    password: t_password,    client_id: t_client_id,    client_secret: t_client_secret  },},function(err, res, body) {  console.log(body);  //获得Token  var accessToken =JSON.parse(body).access_token;   request.get({    url: 'http://localhost:3000/secret',    headers: { Authorization: 'Bearer ' +accessToken }  }, function(err, res, body) {    console.log(body);   });});


0 0
原创粉丝点击