Vue.js 2.0:打造最强OAuth2.0第三方登录组件,安全又便捷!

本篇文章将以Github为例,介绍如何在自己的站点添加第三方登录模块。

OAuth2.0

OAuth(开放授权)是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用。

更多关于OAuth2.0的信息请访问  OAuth 2.0 — OAuth

实际使用只需要知道:

  1. 提供方储存了用户的信息,ID,Name,Email等。
  2. 客户端通过提供方指定的页面发起请求,获取token。
  3. 客户端通过token获得用户信息。

Github

详细的认证过程请访问官方文档 Authorization options for OAuth Apps,这里我对一般的web app请求认证的过程做一下总结。

GIthub的具体认证流程:

  1. 用户点击登录按钮跳转至Github提供的授权界面,并提供参数:客户端ID(稍后会介绍到),回调页面等。

    GET https://github.com/login/oauth/authorize

    「参数」

    名称 类型 描述
    client_id string 「必需」。GitHub的客户端ID 。
    redirect_uri string 回调地址,默认返回申请时设置的回调地址。
    scope string 以空格分隔的授权列表。eg:user repo  不提供则默认返回这两种。
    state string 客户端提供的一串随机字符。它用于防止跨站请求伪造攻击。
    allow_signup string 如果用户未注册Github,是否提供注册相关的信息,默认是true
  2. 通过验证后页面跳转至之前提供的回调页面,url中包含相关参数:code和state。

  3. 客户端以POST的方式访问GIthub提供的地址,提供参数code等。

    POST https://github.com/login/oauth/access_token

    「参数」

    名称 类型 描述
    client_id string 「必需」。GitHub的客户端ID 。
    client_secret string 「必需」。Github提供的一串随机字符串。
    code string 「必需」。上一步收到的code
    redirect_uri string 之前提供redirect_uri
    state string 之前提供的state
  4. Github返回数据, 包含accesstoken。根据不同的Accept标头返回不同格式,推荐json。

    Accept: application/json
    {"access_token":"e72e16c7e42f292c6912e7710c838347ae178b4a""scope":"repo,gist""token_type":"bearer"}

5.客户端以GET的方式访问Github提供的地址,在参数中加入或在head中加入accesstoken。

GET https://api.github.com/user?access_token=...
curl -H "Authorization: token OAUTH-TOKEN" https://api.github.com/user

6.Github返回用户的json数据。

大部分的第三方登录都参考了Github的认证方法。

Vue.js

不用多说,Vue.js。这里我主要总结一下第三方登录组件的设计流程。

组件

以博客系统为例,可分为三类:

  1. 主页,所有组件的parent。
  2. 身份认证组件,需解耦,至少要唤起登录和登出事件。
  3. 其他需要身份认证的组件。

身份认证组件(auth)

组件的职能可概括为以下几点:

  1. 未登陆状态时显示登陆按钮,登陆状态时显示注销按钮。
  2. 点击登录按钮时,页面发生跳转。
  3. 监视地址栏有无code和正确state出现。如果出现开始身份认证。
  4. 认证成功唤起登录事件并将用户信息传递出去。
  5. 用户点击登出唤起登出事件。

更全面的,出于方便考虑以及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',
      redirectURLnull,
      codenull,
      accessTokennull,
      signStatefalse
    }
  }

模板中加入登录按钮, 保存之前的地址至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-cookie

Parse and stringify URL.   —query strings

组件创建后,检查地址栏是否存在有效code。如果存在则进行相应处理,获取有效accesstoken存入cookie,页面回调至登录之前保存的地址。如果不存在则检查cookie内是否存在accesstoken 获取用户信息。

「注意:」 需要计算得到的属性务必在computed下定义。

computed: {
    formatCodeURLfunction ({
      return this.getCodeURL + ('?' + Query.stringify({
        client_idthis.client_id,
        scopethis.scope,
        statethis.state
      }))
    }
  }
 createdfunction ({
    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_idthis.client_id,
        scopethis.scope,
        statethis.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_idthis.client_id,
        client_secretthis.client_secret,
        codethis.code,
        statethis.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还未返回时页面就发生跳转。

「重要」 :包括ajaxfetch在内的向后台提交资源的操作都存在跨域问题。浏览器同源政策及其规避方法(阮一峰)。这里利用了代理的方法,使用vue-cli时可通过配置文件临时设置代理规避跨域问题。在生产环境下需要配置服务器代理至其他域名。

" $/config/index.js "
proxyTable: {
      '/github': {
        target'https://github.com',
        changeOrigintrue,
        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,触发用户登出事件。

主页(app)

引入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 {
      usernull
    }
  }

其他组件

因为Vue.js是响应式的,props中设置user字段,初始化时传入即可。

<router-view v-bind:user="user"></router-view>
props: ['user']

原文始发于微信公众号(尘缘如梦):Vue.js 2.0:打造最强OAuth2.0第三方登录组件,安全又便捷!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/166249.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!