Add jwt persistance inside localstorage
This commit is contained in:
parent
0b0261aaaa
commit
818110cd3b
@ -9,5 +9,6 @@ fun Application.corsFeature() {
|
|||||||
install(CORS) {
|
install(CORS) {
|
||||||
anyHost()
|
anyHost()
|
||||||
header(HttpHeaders.ContentType)
|
header(HttpHeaders.ContentType)
|
||||||
|
header(HttpHeaders.Authorization)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1,9 +1,27 @@
|
|||||||
import axios from 'axios'
|
import axios from 'axios'
|
||||||
|
import {mapState} from "vuex";
|
||||||
|
|
||||||
export default axios.create({
|
|
||||||
|
const state = mapState(['token'])
|
||||||
|
|
||||||
|
const Api = axios.create({
|
||||||
baseURL: 'http://localhost:8081',
|
baseURL: 'http://localhost:8081',
|
||||||
timeout: 4000,
|
timeout: 4000,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
axios.interceptors.request.use(
|
||||||
|
config => {
|
||||||
|
const token = state.token;
|
||||||
|
if (token) {
|
||||||
|
config.headers['Authorization'] = 'Bearer ' + token;
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
},
|
||||||
|
error => {
|
||||||
|
Promise.reject(error)
|
||||||
|
});
|
||||||
|
|
||||||
|
export default Api
|
||||||
20
web/src/jwt/index.js
Normal file
20
web/src/jwt/index.js
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import Api from '@/api'
|
||||||
|
|
||||||
|
export function setToken(token) {
|
||||||
|
localStorage.setItem('token', token)
|
||||||
|
Api.defaults.headers.common['Authorization'] = 'Bearer ' + token;
|
||||||
|
}
|
||||||
|
|
||||||
|
// should only be run at initialization
|
||||||
|
export function getToken() {
|
||||||
|
const token = localStorage.getItem('token')
|
||||||
|
Api.defaults.headers.common['Authorization'] = 'Bearer ' + token;
|
||||||
|
return token
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearToken() {
|
||||||
|
localStorage.removeItem('token')
|
||||||
|
delete Api.defaults.headers.common['Authorization']
|
||||||
|
}
|
||||||
|
|
||||||
|
export default {setToken, getToken, clearToken}
|
||||||
@ -1,15 +1,21 @@
|
|||||||
import Vue from 'vue'
|
import Vue from 'vue'
|
||||||
import Vuex from 'vuex'
|
import Vuex from 'vuex'
|
||||||
|
import {setToken, getToken, clearToken} from '@/jwt'
|
||||||
|
|
||||||
Vue.use(Vuex)
|
Vue.use(Vuex)
|
||||||
|
|
||||||
export default new Vuex.Store({
|
export default new Vuex.Store({
|
||||||
state: {
|
state: {
|
||||||
token: ''
|
token: getToken()
|
||||||
},
|
},
|
||||||
mutations: {
|
mutations: {
|
||||||
setToken: (state, {token}) => {
|
setToken: (state, {token}) => {
|
||||||
state.token = token;
|
state.token = token
|
||||||
|
setToken(token)
|
||||||
|
},
|
||||||
|
clearToken(state) {
|
||||||
|
state.token = ''
|
||||||
|
clearToken()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
actions: {}
|
actions: {}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user