项目的配置文件放置于路径:src/config/config.jsjavascript
具体配置:php
var config={ //请求受权地址 userAuthorizationUri:"https://github.com/login/oauth/authorize", //accessToken请求地址 accessTokenUri : "https://github.com/login/oauth/access_token", //用户信息请求地址 userInfoUri:"https://api.github.com/user", //登出请求地址 logoutUri:"https://github.com/logout", //项目地址 localuri :"http://localhost:9999", //回调地址 redirect_uri : "http://localhost:9999/login", //案例资源服务器地址 resUri:"http://localhost:8080", //客户端相关标识,请从认证服务器申请 clientId: "", client_secret:"", //申请的权限范围 scope:"user", //可选参数,客户端的当前状态,能够指定任意值,用于校验,这次案例不作相关认证 state:"", //一些固定的请求参数 response_type:"token", grant_type : "authorization_code", code:"", } export default config;
登陆,配置客户端信息并重定向到认证地址,等待用户受权。vue
文件地址:src/util/loginUtils.js
login:function (vue) { vue.$config.code = RndNum(4); var authorUrl = vue.$config.userAuthorizationUri; authorUrl = authorUrl + ('?' + vue.$querystring.stringify({ client_id:vue.$config.clientId, response_type:vue.$config.response_type, scope:vue.$config.scope, state:vue.$config.state, redirect_uri:vue.$config.redirect_uri, })) window.location.href = authorUrl; } 其中几个参数的含义: response_type:表示受权类型,必选项,此处的值固定为"code" client_id:表示客户端的ID,必选项 redirect_uri:表示重定向URI,可选项 scope:表示申请的权限范围,可选项 state:表示客户端的当前状态,能够指定任意值,认证服务器会原封不动地返回这个值。
这一步的目的是取得用户的受权并获得受权码,受权码将用于取得Access_Token。
若是配置了参数中的redirect_uri,取得受权码以后认证服务器将会重定向到该地址。java
2.用户完成受权,取得受权码,咱们将携带受权码和配置相关信息向认证服务器申请Access_Tokengit
文件地址:src/components/ssologin.vue
mounted:function () { this.code = this.$route.query.code; this.state = this.$route.query.state; this.getToken(); } 回调取得两个参数的做用: code:表示受权码,必选项。该码的有效期应该很短,一般设为10分钟,客户端只能使用该码一次,不然会被受权服务器拒绝。该码与客户端ID和重定向URI,是一一对应关系。 state:若是客户端的请求中包含这个参数,认证服务器的回应也必须如出一辙包含这个参数。 getToken:function(){ this.$token.getTokenFromService(this,this.code,(response)=>{ this.$token.savetoken(response.data); this.$router.push('/user'); },function (error) { alert(error); }); }
这里获取了Access_Token做为身份凭证,须要咱们保存起来,能够保存在cookie中,也能够选择其余方式,在后续访问资源服务器调用资源的时候须要携带Access_Token访问。
文件地址:src/util/token.js
getTokenFromService:function (vue,code,callback,error) { vue.$ajax.post(vue.$config.accessTokenUri,{ client_id:vue.$config.clientId, client_secret:vue.$config.client_secret, code:code, redirect_uri:vue.$config.redirect_uri, grant_type:vue.$config.grant_type },{ headers:{"Accept":"application/json"} }) .then(callback) .catch(error); } 相关几个参数的含义: grant_type:表示使用的受权模式,必选项,此处的值固定为"authorization_code"。 code:表示上一步得到的受权码,必选项。 redirect_uri:表示重定向URI,必选项,且必须与A步骤中的该参数值保持一致。 client_id:表示客户端ID,必选项。
获取用户的身份信息是将认证服务器做为资源服务器看待,携带身份凭证Access_Token请求资源,资源服务器将经过认证服务器检测身份凭证的有效性做出相应回复。对于前段咱们的作法以下:github
原文地址:https://www.jianshu.com/p/5cf2b7a45b75getUserInfo:function () { var tokenInfo = this.$token.loadToken(); this.$ajax({ url:this.$config.userInfoUri+"?"+"access_token="+tokenInfo.access_token, headers:{"Accept":"application/json"} }) .then((response) =>{ this.user = response.data; console.log(this.user); }) .catch((error) =>{ this.$root.push("/logout") }); }