您的位置:首页 > Web前端 > Node.js

Node OAuth2 server 初步尝试和验证

2014-06-24 20:53 429 查看
由于在身份验证过程中不允许在客户端存储敏感性信息,如用户账号和密码,同时为了更容易地在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_id
vart_client_id = 'papers3';
//client_secret
vart_client_secret = '123';
//clientCredentials  以client_id:client_secret形式组合并转换成Base64-encoded
varclientCredentials = (t_client_id + ':'+t_client_secret).toString('base64');
//用户名
vart_username = 'alex@example.com';
//密码
vart_password = 'test';

console.log(clientCredentials);

//发送Post请求获取Token
request.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);
});
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Node Token OAuth2 服务器
相关文章推荐