第三方登陆是如今常见的登陆方式,免注册且安全方便快捷。javascript
本篇文章将以Github为例,介绍如何在本身的站点添加第三方登陆模块。html
OAuth(开放受权)是一个开放标准,容许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用。
更多关于OAuth2.0的信息请访问 OAuth 2.0 — OAuthvue
实际使用只须要知道:java
详细的认证过程请访问官方文档 Authorization options for OAuth Apps,这里我对通常的web app请求认证的过程作一下总结。ios
用户点击登陆按钮跳转至Github提供的受权界面,并提供参数:客户端ID(稍后会介绍到),回调页面等。git
GET https://github.com/login/oauth/authorize
github
参数:web
名称 | 类型 | 描述 |
---|---|---|
client_id |
string |
必需。GitHub的客户端ID 。 |
redirect_uri |
string |
回调地址,默认返回申请时设置的回调地址。 |
scope |
string |
以空格分隔的受权列表。eg:user repo 不提供则默认返回这两种。 |
state |
string |
客户端提供的一串随机字符。它用于防止跨站请求伪造攻击。 |
allow_signup |
string |
若是用户未注册Github,是否提供注册相关的信息,默认是true 。 |
客户端以POST的方式访问GIthub提供的地址,提供参数code等。ajax
POST https://github.com/login/oauth/access_token
vue-cli
参数:
名称 | 类型 | 描述 |
---|---|---|
client_id |
string |
必需。GitHub的客户端ID 。 |
client_secret |
string |
必需。Github提供的一串随机字符串。 |
code |
string |
必需。上一步收到的code |
redirect_uri |
string |
以前提供redirect_uri |
state |
string |
以前提供的state |
Github返回数据, 包含accesstoken。根据不一样的Accept标头返回不一样格式,推荐json。
Accept: application/json {"access_token":"e72e16c7e42f292c6912e7710c838347ae178b4a", "scope":"repo,gist", "token_type":"bearer"}
客户端以GET的方式访问Github提供的地址,在参数中加入或在head中加入accesstoken。
GET https://api.github.com/user?access_token=...
curl -H "Authorization: token OAUTH-TOKEN" https://api.github.com/user
大部分的第三方登陆都参考了Github的认证方法。
不用多说,Vue.js。这里我主要总结一下第三方登陆组件的设计流程。
以博客系统为例,可分为三类:
组件的职能可归纳为如下几点:
code
和正确state
出现。若是出现开始身份认证。更全面的,出于方便考虑以及Auth2.0的特性,accesstoken
能够存放至cookie以实现必定时间内免登录且不用担忧密码泄露。响应的在用户认证成功和登出时须要对cookie进行设置和清除操做。
那么开始最主要组件auth
的编写
首先进行准备工做,访问Github -> settings -> Developer settings 填写相关信息建立 Oauth App。
注意: 此处设置的 Authorization callback URL
即为客户端的回调页面。客户端申请携带的参数与这个地址不一样会报相应的错误。
获得client信息后就能够在auth
组件内设置字段了。
" @/components/GithubAuth.vue " data () { return { client_id: 'your client ID', client_secret: 'your client secret', scope: 'read:user', // Grants access to read a user's profile data. state: 'your state', getCodeURL: 'https://github.com/login/oauth/authorize', getAccessTokenURL: '/github/login/oauth/access_token', getUserURl: 'https://api.github.com/user', redirectURL: null, code: null, accessToken: null, signState: false } }
模板中加入登陆按钮, 保存以前的地址至cookie以便登陆后回调,跳转至受权页面。
<a v-if="!signState" href="#" v-on:click="saveURL">登陆</a>
saveURL: function () { if (Query.parse(location.search).state !== this.state) { this.$cookie.set('redirectURL', location.href, 1) location.href = this.getCodeURL } }
A Vue.js plugin for manipulating cookies. --- vue-cookieParse and stringify URL. ---query strings
组件建立后,检查地址栏是否存在有效code
。若是存在则进行相应处理,获取有效accesstoken
存入cookie,页面回调至登陆以前保存的地址。 若是不存在则检查cookie内是否存在accesstoken
获取用户信息。
注意: 须要计算获得的属性务必在computed
下定义。
computed: { formatCodeURL: function () { return this.getCodeURL + ('?' + Query.stringify({ client_id: this.client_id, scope: this.scope, state: this.state })) } }
created: function () { this.getCode() // when code in url if (this.code) this.getAccessToken() else { // if no code in top, get accessToken from cookie this.accessToken = this.$cookie.get('accessToken') if (this.accessToken) this.getUser() } }
获取地址栏携带的code
参数的处理:getCode()
getCode: function () { this.getCodeURL += ('?' + Query.stringify({ client_id: this.client_id, scope: this.scope, state: this.state })) let parse = Query.parse(location.search) if (parse.state === this.state) { this.code = parse.code } }
利用code
获取accesstoken
的处理: getAccessToken()
getAccessToken: function () { this.axios.post(this.getAccessTokenURL, { client_id: this.client_id, client_secret: this.client_secret, code: this.code, state: this.state }).then((response) => { this.accessToken = response.data.access_token if (this.accessToken) { // save to cookie 30 days this.$cookie.set('accessToken', this.accessToken, 30) this.redirectURL = this.$cookie.get('redirectURL') if (this.redirectURL) { location.href = this.redirectURL } } }) }
A small wrapper for integrating axios to Vuejs. --- vue-axios
要说的是,由于axios是基于promise的异步操做,因此使用时应当特别注意。页面跳转放在回调函数里是为了防止promise还未返回时页面就发生跳转。
重要 :包括ajax
,fetch
在内的向后台提交资源的操做都存在跨域问题。浏览器同源政策及其规避方法(阮一峰)。 这里利用了代理的方法,使用vue-cli时可经过配置文件临时设置代理规避跨域问题。在生产环境下须要配置服务器代理至其余域名。
" $/config/index.js " proxyTable: { '/github': { target: 'https://github.com', changeOrigin: true, pathRewrite: { '^/github': '/' } }
/github
会在请求发起时被解析为target
。设置完成后中断热重载从新编译,从新编译,从新编译。
利用accesstoken
获取用户信息的处理:getUser()
getUser: function () { this.axios.get(this.getUserURl + '?access_token=' + this.accessToken) .then((response) => { let data = response.data this.signState = true // call parent login event this.$emit('loginEvent', { login: data.login, avatar: data.avatar_url, name: data.name }) }) // invaild accessToken .catch((error) => { console.log(error) this.$cookie.delete('accessToken') }) }
请求用户信息成功后触发了loginEvent
事件,并以当前用户信息做为参数传递出去。
用户登出的处理: logout()
<a v-else v-on:click="logout" href="#">注销</a>
logout: function () { this.$cookie.delete('accessToken') this.signState = false this.$emit('logoutEvent') }
清理cookie,触发用户登出事件。
引入auth组件并注册为子组件。
import GithubAuth from '@/components/GithubAuth' Vue.component('auth', GithubAuth)
设置子组件触发事件后的处理函数
<auth v-on:loginEvent="login"v-on:logoutEvent="logout"></auth>
methods: { login: function (user) { this.user = user }, logout: function () { this.user = null } }
初始化一个空的user字段后等待auth
唤起事件,改变user字段的值。
data () { return { user: null } }
由于Vue.js是响应式的,props
中设置user字段,初始化时传入便可。
<router-view v-bind:user="user"></router-view>
props: ['user']
以上仅是我我的总结出的一些方法,若有更好的解决方法或是错误的地方请指出,感激涕零!