在微服务大行其道的今天,各系统根据其业务划分,又独立出了好几个模块,Spring Cloud就像一个插排一样,想看电视,把电视机电源插上;没有网,把路由器电源插上,而电视机和路由器都是一个个服务。
那么这么多的服务,如何验证登录和权限?
1、架构图
这个图的设想是,搭建一个认证服务器,每个系统下的微服务模块都可以作为客户端去认证服务器那边要求认证。这就有点像现在的第三方登录,认证服务器管理的资源就是用户信息。
2、时序图
用户认证的过程如上图所示,最终得到一个access_token(包含refresh_token),这个时序图和微信开放平台的时序图是一致的,也是目前比较流行的认证方式。
3、前端可以将token储存在localStorage实现统一登录,当然安全方面的因素还是要考虑去完善的
created () {
// http://www.avanty.com:8766/oauth/authorize?response_type=code&client_id=my-client-1&redirect_uri=https://www.baidu.com GET 获取code再获取token
// http://www.avanty.com:8766/oauth/authorize?response_type=token&client_id=my-client-1&redirect_uri=https://www.baidu.com GET 直接获取token
// http://www.avanty.com:8766/oauth/token?grant_type=refresh_token&client_id=my-client-1&client_secret=12345678&refresh_token=d3ddd902-fb2c-41ac-aa2a-fd5b73ea9e48 POST PARAM 刷新token
//获取URL后面拼接的code
var code = this.getQueryString("code")
//实际可以储存服务端返回的包含access_token和refresh_token的对象
var token = localStorage.getItem("access_token")
if (!code && !token) {
location.href = "http://www.avanty.com:8766/oauth/authorize?response_type=code&client_id=my-client-1&redirect_uri=http://www.avanty.com:8080";
}
if (code) {
this.$axios.post('http://www.avanty.com:8766/oauth/token?grant_type=authorization_code&client_id=my-client-1&client_secret=12345678&redirect_uri=http://www.avanty.com:8080&code=' + code)
.then(function (res) {
console.log(res)
//储存返回结果
})
.catch(function (e) {
location.href = "http://www.avanty.com:8766/oauth/authorize?response_type=code&client_id=my-client-1&redirect_uri=http://www.avanty.com:8080";
});
}
},
methods: {
getQueryString (name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i")
var l = decodeURI(window.location.search)
var r = l.substr(1).match(reg)
if (r != null) return unescape(r[2])
return null
}
}
至此,整个架构设想在流程方面可以算是走通了。