発生している問題
ログイン実行時のレスポンスはCompleted 200だが、localStorageに必要な情報が保存されない為かログインできていない。
ターミナル
Started POST "/api/v1/auth/sign_in" for 172.22.0.1 at 2022-06-21 17:14:07 +0900
Processing by Api::V1::Auth::SessionsController#create as HTML
Parameters: {"agent_companies_id"=>"123456789", "email"=>"test@mail.com", "password"=>"[FILTERED]", "session"=>{"agent_companies_id"=>"123456789", "email"=>"test@mail.com", "password"=>"[FILTERED]"}}
Unpermitted parameter: :session
Unpermitted parameter: :session
Agent Load (1.8ms) SELECT `agents`.* FROM `agents` WHERE (BINARY email = 'test@mail.com' AND provider= 'email') ORDER BY `agents`.`id` ASC LIMIT 1
↳ app/controllers/api/V1/auth/sessions_controller.rb:15:in `create'
Unpermitted parameter: :session
Unpermitted parameter: :session
(1.9ms) BEGIN
↳ app/controllers/api/V1/auth/sessions_controller.rb:58:in `create_and_assign_token'
Agent Load (2.7ms) SELECT `agents`.* FROM `agents` WHERE `agents`.`id` = 575837166 LIMIT 1 FOR UPDATE
↳ app/controllers/api/V1/auth/sessions_controller.rb:58:in `create_and_assign_token'
Agent Update (2.3ms) UPDATE `agents` SET `agents`.`tokens` = '{\"1ahWgABsGT8wmtDKBzSkTA\":{\"token\":\"$2a$10$G025CGmb2L24XpgIVt/C1OQjtZ01.9YkshriSyxw8VS90SLUI4g1a\",\"expiry\":1656998919},\"4mkvq_WbnGVPjyWw2JE2mw\":{\"token\":\"$2a$10$BIAo.WnSJR0zlBmdzjSB4eq1NDv2qY5eW29hh1iwoxpumT5uMNwHa\",\"expiry\":1656999196},\"DzRvzfWbWEPS-5sfRHNaJQ\":{\"token\":\"$2a$10$1Ca.ZEv5kzo.IB8Q1Kba2uN8FbLT.S5Um2JkpMFt2n3kFa2rOPwli\",\"expiry\":1656999440},\"TM2w3UM1E5PLVTj1C6qjJQ\":{\"token\":\"$2a$10$I5MDUqTnJ71WLSmbur3Ad.orKDb9FtU6fgRt1zjtUFZn2iBNIxqNG\",\"expiry\":1656999504},\"5qBIOHN9ASriY1jNiGMPsw\":{\"token\":\"$2a$10$aPRKzTL313YhAlMHXgJxFeQwU3xt2/1oQnuOKwY2DtJ3AURpAPsum\",\"expiry\":1657007037},\"gch-ykxWGHJEuoP4yrh5EQ\":{\"token\":\"$2a$10$owf9Vl.IOIqeVcVqVjH0WOZug16cGET1tP2nJ/EzAGRLAUfO6ZSdC\",\"expiry\":1657007377},\"PehEXLadm3kL502DTf9Uwg\":{\"token\":\"$2a$10$2z3YqEbuMQUQrPpWl.2ZlOE6qmJcSDKl09yUtapEzfOY1w8wFMjcy\",\"expiry\":1657007472},\"Zq-YlRGmWcm4THTI6ks2_w\":{\"token\":\"$2a$10$K3CQEMN9BU45OdnLJNpT7eLJ14LCUPtPWQAH.p3OuB1tLBTu0b0oq\",\"expiry\":1657007529},\"0i9B70CyxtGWhotpB4PnUw\":{\"token\":\"$2a$10$tBdx7iBLMyFskLnQCKE3NePcUBie8hMiNCZrWpSMOwSeCsc2zXwJ2\",\"expiry\":1657008649},\"8arJED_D8FczCG6_zCxdPw\":{\"token\":\"$2a$10$j5ylYGQD7i6hVpUYchXoNOfNYlituypEpyE5a22kBFRUnB2OJrr7m\",\"expiry\":1657008848}}', `agents`.`updated_at` = '2022-06-21 08:14:08.049640' WHERE `agents`.`id` = 575837166
↳ app/controllers/api/V1/auth/sessions_controller.rb:60:in `block in create_and_assign_token'
(6.5ms) COMMIT
↳ app/controllers/api/V1/auth/sessions_controller.rb:58:in `create_and_assign_token'
Agent Load (2.6ms) SELECT `agents`.* FROM `agents` WHERE `agents`.`id` = 575837166 LIMIT 1
Completed 200 OK in 676ms (Views: 0.5ms | ActiveRecord: 17.8ms | Allocations: 8324)
該当のソースコード
signin.vue
<template>
<div>
<h2>ログイン</h2>
<form>
<div>
<label>企業ID</label>
<input
v-model="agent.agent_companies_id"
type="text"
placeholder="企業ID"
/>
</div>
<div>
<label>ユーザーID</label>
<input v-model="agent.email" type="text" placeholder="ユーザーID" />
</div>
<div>
<label>パスワード</label>
<input
v-model="agent.password"
type="password"
placeholder="パスワード"
/>
</div>
<div>
<button type="submit" @click="login">
ログイン
</button>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
agent: {
agent_companies_id: '',
email: '',
password: ''
},
error: null
}
},
methods: {
async login() {
await this.$auth
.loginWith('local', {
data: {
agent_companies_id: this.agent.agent_companies_id,
email: this.agent.email,
password: this.agent.password
}
})
.then((data) => {
console.log(data) // eslint-disable-line no-console
this.$router.push('/')
})
this.$router.push('/').then((error) => {
this.error = error.response.data.errors
console.log(this.error) // eslint-disable-line no-console
})
}
}
}
</script>
application_controller.rb
class ApplicationController < ActionController::API
include DeviseTokenAuth::Concerns::SetUserByToken
skip_before_action :verify_authenticity_token, raise: false
before_action :configure_permitted_parameters, if: :devise_controller?
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:agent_companies_id, :last_name, :first_name, :last_name_syllabic_characters, :first_name_syllabic_characters, :email, :password]) #新規登録時に許可するパラメーターの指定
devise_parameter_sanitizer.permit(:sign_in, keys: [:agent_companies_id, :email, :password]) #ログイン時に許可するパラメーターの指定
end
end
sessions_controller
class Api::V1::Auth::SessionsController < DeviseTokenAuth::SessionsController
before_action :cookie_destroy
def cookie_destroy
request.session_options[:skip] = true
end
private
def resource_params
params.permit(:agent_companies_id, :email, :password)
end
end
nuxt.config.js
export default {
server: {
port: 3000,
host: '0.0.0.0' // デフォルト: localhost,
},
mode: 'universal',
head: {
title: process.env.npm_package_name || '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
hid: 'description',
name: 'description',
content: process.env.npm_package_description || ''
}
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]
},
loading: { color: '#fff' },
css: [],
plugins: ['~/plugins/axios.js'],
buildModules: ['@nuxtjs/eslint-module', '@nuxtjs/stylelint-module'],
modules: ['@nuxtjs/axios', '@nuxtjs/auth'],
axios: {
baseURL: 'http://localhost:5000',
proxy: true
},
auth: {
redirect: {
login: '/auth/sign_in', // middleware:authを設定したURLにアクセスがあった場合の、リダイレクト先。
logout: '/', // ログアウト後のリダイレクト先
callback: false,
home: '/' /// ログイン後のリダイレクト先。
},
strategies: {
local: {
endpoints: {
// ログイン処理に関する設定
login: {
url: 'http://localhost:5000/api/v1/auth/sign_in',
method: 'post',
propertyName: 'access_token'
},
// ログアウト処理に関する設定
logout: {
url: 'http://localhost:5000/api/v1/auth/sign_out',
method: 'delete'
},
// ログイン時にユーザー情報を保存するか。
user: {
url: 'http://localhost:5000/api/v1/agents',
method: 'get',
propertyName: 'agent'
}
// user: false
}
}
}
},
build: {
standalone: true,
extend(config, ctx) {}
}
}
axios.js
export default function({ $axios }) {
$axios.onRequest((config) => {
config.headers.client = window.localStorage.getItem('client')
config.headers['access-token'] = window.localStorage.getItem('access-token')
config.headers.uid = window.localStorage.getItem('uid')
config.headers['token-type'] = window.localStorage.getItem('token-type')
})
$axios.onResponse((response) => {
if (response.headers.client) {
localStorage.setItem('access-token', response.headers['access-token'])
localStorage.setItem('client', response.headers.client)
localStorage.setItem('uid', response.headers.uid)
localStorage.setItem('token-type', response.headers['token-type'])
}
})
}
試したこと
localStorageのデータを削除してログイン実行したが、保存されなかった
axios.jsの内容を書き換えて、実行
export default ({ $axios, store }) => {
$axios.onRequest((config) => {
config.headers = store.getters.auth
})
$axios.onResponse((response) => {
if (response.headers['access-token']) {
const authHeaders = {
'access-token': response.headers['access-token'],
client: response.headers.client,
expiry: response.headers.expiry,
uid: response.headers.uid
}
store.commit('setAuth', authHeaders)
}
})
$axios.onError((error) => {
return Promise.reject(error.response)
})
}
補足情報(FW/ツールのバージョンなど)
rails 6.0.3
nuxt 2.15.0
auth 4.9.1
axios 5.3.6
どなたかご教示いただければ幸いです🙇♂️