0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nuxt 2 with GithubAPI認証

0
Posted at

概要

Nuxt2でGithubAPI認証からユーザー情報を取得する方法

前提条件

  • GithubでClientIDとClientSecretが発行済であること

手順

1. 環境変数とCORS設定

nuxt.config.js
publicRuntimeConfig: {
  // 事前に.envの作成が必要です。
  GITHUB_CLIENT_ID: process.env.GITHUB_CLIENT_ID,
  GITHUB_CLIENT_SECRET: process.env.GITHUB_CLIENT_SECRET
},

axios: {
  proxy: true
},

proxy: {
  '/github/': {
    target: 'https://github.com',
    pathRewrite: {'^/github/': '/'},
  },
  '/github-api/': {
    target: 'https://api.github.com',
    pathRewrite: {'^/github-api/': '/'},
  }
}

2. Githubのアクセストークンを保存するストアを作成

store/index.js
export const state = () => ({
  accessToken: null
})

export const mutations = {
  setAccessToken(state, accessToken) {
    state.accessToken = accessToken
  }
}

export const actions = {
  setAccessToken({ commit }, accessToken) {
    commit('setAccessToken', accessToken)
  }
}

3. Githubの認証画面へ遷移する画面を作成

pages/index.vue
<template>
  <div>
    <!-- Vuetify.jsを使用しています -->
    <v-btn
      v-text="'Github'"
      @click="goTo"
    />
  </div>
</template>

<script>
export default {
  methods: {
    goTo() {
      window.location.href =`https://github.com/login/oauth/authorize?scope=user&client_id=${this.$config.GITHUB_CLIENT_ID}`
    }
  }
}
</script>

4. 認証画面からのリダイレクト先の画面を作成

pages/callback.vue
<template>
  <div>
    コールバック画面
  </div>
</template>

<script>
export default {
  asyncData({ query }) {
    return {
      code: query.code
    }
  },
  data: () => ({
    code: ''
  }),
  async mounted() {
    await this.github()
  },
  methods: {
    github() {
      const data = await this.$axios.$post('/github/login/oauth/access_token', {
        client_id: this.$config.GITHUB_CLIENT_ID,
        client_secret: this.$config.GITHUB_CLIENT_SECRET,
        code: this.code
      }, {
        headers: {
          'Accept': 'application/json'
        }
      }).catch((error) => { return error.response })
      
      this.$store.dispatch('setAccessToken', data.access_token)

      return this.$router.push('/home')
    }
  }
}
</script>

5. ホーム画面を作成

pages/home.vue
<template>
  <div>
    ホーム画面
  </div>
</template>

<script>
export default {
  async mounted() {
    await this.init()
  },
  methods: {
    async init() {
      const res = await this.$axios.$get('/github-api/user', {
        headers: {
          'Authorization': `token ${this.$store.state.accessToken}`,
          'Accept': 'application/vnd.github.v3+json'
        }
      }).catch((error) => { return error.response })

      // Githubのユーザー情報を出力
      console.log(res)
    }
  }
}
</script>

完了!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?