nodejs实现OAuth2.0授权服务认证(3)
这里的${query}即为客户端登录重定向携带的完整query,然后是/oauth2/authorize路由的写法:
app.all('/oauth2/authorize', app.oAuth2Server.authorize());// 获取授权码
这里调用app.oAuth2Server.authorize()时,插件会自动执行重定向操作,首先是重定向到客户端指定地址,客户端拿到code和state后,再去授权层获取token:
async redirect(){
// 服务端重定向过来的
console.log(this.ctx.query)
const result = await this.ctx.curl('http://127.0.0.1:7001/users/token', {
dataType: 'json',
// contentType: 'application/x-www-form-urlencoded', // 默认格式
method: 'POST',
timeout: 3000,
data: {
grant_type: 'authorization_code',
code: this.ctx.query.code,
state: this.ctx.query.state,
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
}
});
this.ctx.body = result.data;
}
获取到token后正常返回:

2、password grant模式测试
首先使用username、password获取access_token:

用户名或密码错误时返回:

使用token获取授权资源正常返回:

以上内容完整源码参考:https://github.com/caiya/eggjs-oAuth2-server
总结
- OAuth实际使用时要上https,包括客户端和授权服务端
- 授权服务可以使用私钥签名,客户端使用公钥验证,从而保证数据安全性
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。
