我使用带有vuex的DRF和VueJs创建一个应用程序。我是axios
的新手,现在尝试创建一个axios
拦截器,该拦截器将从应用程序的auth/key
侧检查用户API
,以便blocked/deleted
和非auth
用户。我的目的是将用户key
的状态设置为null
。
我使用SessionAuthentication和TokenAuthentication:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
}
这是我到现在为止要使用的,但是它没有按预期运行,我的猜测是由于Authorization Bearer
:
export default function createAxiosResponseInterceptor() {
HTTP.interceptors.request.use(config => {
if (!config.headers['Authorization']) {
config.headers['Authorization'] = `Bearer ${store.state.user.accessKey}`
}
return config
}, error => {
return Promise.reject(error)
})
const interceptor = HTTP.interceptors.response.use(
response => response,
error => {
// Reject promise if usual error
if (error.response.status !== 403) {
return Promise.reject(error);
}
HTTP.interceptors.response.eject(interceptor);
return HTTP.post('/api/rest-auth/login/', {})
.then(response => {
store.commit('user/setUserKey', {accessKey: response.data.key});
error.response.config.headers['Authorization'] = 'Bearer ' + response.data.key;
return HTTP(error.response.config);
}).catch(error => {
store.commit('user/reset');
this.router.push({name: 'login'});
return Promise.reject(error);
}).finally(createAxiosResponseInterceptor);
}
);
}
和我的商店:
export action {
async loginUser(context, payload) {
try {
const response = await DjangoAPI.login(payload);
context.commit('setUserKey',{
accessKey: response.data.key,
});
//Vue.http.headers.common['Authorization'] = 'Bearer ' + response.body.key
return Promise.resolve(response);
} catch(err) {
console.log('err in user.actions/loginUser', err)
return Promise.reject(err);
}
},
}
export const mutations = {
setUserKey(state, payload) {
state.accessKey = payload.accessKey;
state.expiration = Date.now() + 30000
},
}
在用户登录后,我得到了密钥response
,如果我删除或阻止用户或者验证密钥超时,如何从localstorage
中删除密钥?
谢谢