axiosでトークン取得を修正する

This commit is contained in:
Mouriya
2024-08-08 16:45:44 +09:00
parent 5889874720
commit d9b3f57191
2 changed files with 21 additions and 25 deletions

View File

@@ -2,14 +2,14 @@ import { defineStore } from 'pinia';
import { api } from 'boot/axios';
import { router } from 'src/router';
import { IDomainInfo } from '../types/ActionTypes';
import { jwtDecode } from "jwt-decode";
import { jwtDecode } from 'jwt-decode';
export interface IUserState {
token?: string;
returnUrl: string;
currentDomain: IDomainInfo;
LeftDrawer: boolean;
userId?:string;
userId?: string;
}
export const useAuthStore = defineStore('auth', {
@@ -18,7 +18,7 @@ export const useAuthStore = defineStore('auth', {
returnUrl: '',
LeftDrawer: false,
currentDomain: {} as IDomainInfo,
userId:''
userId: '',
}),
getters: {
toggleLeftDrawer(): boolean {
@@ -37,10 +37,10 @@ export const useAuthStore = defineStore('auth', {
const result = await api.post(`api/token`, params);
console.info(result);
this.token = result.data.access_token;
this.userId=jwtDecode(result.data.access_token).sub
this.userId = jwtDecode(result.data.access_token).sub;
api.defaults.headers['Authorization'] = 'Bearer ' + this.token;
this.currentDomain = await this.getCurrentDomain();
this.router.push(this.returnUrl || '/');
router.push(this.returnUrl || '/');
return true;
} catch (e) {
console.error(e);
@@ -80,6 +80,19 @@ export const useAuthStore = defineStore('auth', {
persist: {
afterRestore: (ctx) => {
api.defaults.headers['Authorization'] = 'Bearer ' + ctx.store.token;
}
//axios例外キャプチャー
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response && error.response.status === 401) {
// 認証エラーの場合再ログインする
console.error('(; ゚Д゚)/認証エラー(401)', error);
ctx.store.logout();
}
return Promise.reject(error);
}
);
},
},
});