Vue實現
1. 對接環境配置
項目的配置文件放置於路徑:src/config/config.js
具體配置:
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;
2. 用戶登錄並獲取Access_Token
-
登錄,配置客戶端信息並重定向到認證地址,等待用戶授權。
文件地址: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,取得授權碼之后認證服務器將會重定向到該地址。
2.用戶完成授權,取得授權碼,我們將攜帶授權碼和配置相關信息向認證服務器申請Access_Token
文件地址: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); }); }
文件地址: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作為身份憑證,需要我們保存起來,可以保存在cookie中,也可以選擇其他方式,在后續訪問資源服務器調用資源的時候需要攜帶Access_Token訪問。
3. 獲取身份信息
獲取用戶的身份信息是將認證服務器作為資源服務器看待,攜帶身份憑證Access_Token請求資源,資源服務器將通過認證服務器檢測身份憑證的有效性作出相應回復。對於前段我們的做法如下:
getUserInfo: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") }); }
原文地址:https://www.jianshu.com/p/5cf2b7a45b75