aokabin / nuxt-rails-practice

0 stars 0 forks source link

nuxt側で、jwtを取得して保存するフローを作りたい #7

Open aokabin opened 4 years ago

aokabin commented 4 years ago

nuxtでjwtを取得して保存したい

CORSの設定をしたから、GETするときはJWTを使わなくてもいい?ちょっとわからないけど

aokabin commented 4 years ago

とりあえず、jwtを取得して保存するスキームを作る

アプリアクセス→railsにredirect→loginさせる →loginしたらnuxtにredirect→key取得

みたいにしようと思ったけど、なんかCORSの設定足りてないっぽい?

Access to XMLHttpRequest at 'http://localhost:3001/check' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

これかな?

aokabin commented 4 years ago

これの下のCookieを使用する場合、の方っぽい

aokabin commented 4 years ago

nuxt.configにこれ書いた

  router: {
    middleware: ['auth']
  },
aokabin commented 4 years ago

取得できたぞー

こんなのをlibにおいて

import axios from 'axios'

export const getRequest = (url, config) => {
  return axios.get(url, config)
}

export const getAuthKey = function(parameters = {}) {
  const config = parameters.$config
  return getRequest('http://localhost:3001/check', config)
}

middlewareから呼び出す

import { getAuthKey } from '~/lib/backend-client'

export default async function({ store, redirect, env, route }) {
  if (process.client) {
    let authKey = store.getters['auth/getKey']
    if (authKey == null) {
      let resp
      try {
        resp = await getAuthKey({
          $config: {
            withCredentials: true
          }
        })
      } catch (err) {
        redirect('http://localhost:3001/login')
      }

      if (resp.status !== 200) {
        redirect('http://localhost:3001/login')
      }

      authKey = resp.data.auth_token
      console.log(authKey)
      store.commit('auth/setKey', { authKey })
    }
  }
}

storeはこんな感じ

export const state = {
  key: null
}

export const mutations = {
  setKey: (state, key) => {
    state.key = key
  }
}

export const getters = {
  key: (state) => {
    return state.key
  }
}