mirror of
https://github.com/ajurna/cbwebreader.git
synced 2026-11-02 10:36:55 +00:00
Implement cookie-based JWT authentication
- Introduced `CookieJWTAuthentication` for authentication via HttpOnly cookies, enabling browser-initiated requests without `Authorization` headers. - Added authentication views (`CookieTokenObtainPairView`, `CookieTokenRefreshView`, `CookieTokenBlacklistView`) to replace default SimpleJWT views. - Updated Vuex store and frontend logic to handle sessions using HttpOnly cookies instead of localStorage. - Enhanced backend and frontend configurations (Django settings, router, Vuex, and API service) to fully support cookie-based authentication. - Updated authentication tests to ensure correct cookie handling and authentication flows.
This commit is contained in:
1 parent
a7e9bd0743
commit
79c0647cc4
11 files changed
+369
-170
No files matched your search
+78
-101
@@ -1,16 +1,11 @@
|
||||
import { createStore } from 'vuex'
|
||||
import axios from 'axios'
|
||||
import { jwtDecode } from "jwt-decode";
|
||||
import {useToast} from "vue-toast-notification";
|
||||
import router from "@/router";
|
||||
import api from "@/api";
|
||||
|
||||
// We'll no longer use localStorage for tokens
|
||||
// Instead, tokens will be stored in httpOnly cookies by the backend
|
||||
// and automatically included in requests
|
||||
function get_jwt_from_storage(){
|
||||
return null; // Initial state will be null until login
|
||||
}
|
||||
// Tokens live in HttpOnly cookies set by the backend, so JavaScript cannot read
|
||||
// them. Only the user profile is kept in localStorage, to avoid a blank page
|
||||
// before the first request has been made.
|
||||
function get_user_from_storage(){
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem('u'))
|
||||
@@ -19,9 +14,18 @@ function get_user_from_storage(){
|
||||
}
|
||||
}
|
||||
|
||||
function session_expired_query(next){
|
||||
return {
|
||||
name: 'login',
|
||||
query: {
|
||||
next: next,
|
||||
error: 'Your session has expired. Please log in again.'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default createStore({
|
||||
state: {
|
||||
jwt: get_jwt_from_storage(),
|
||||
filters: {},
|
||||
user: get_user_from_storage(),
|
||||
classifications: [
|
||||
@@ -39,23 +43,14 @@ export default createStore({
|
||||
} else {
|
||||
return state.user.is_superuser
|
||||
}
|
||||
},
|
||||
isAuthenticated (state) {
|
||||
return state.user !== null
|
||||
}
|
||||
},
|
||||
mutations: {
|
||||
updateToken(state, newToken){
|
||||
// No longer storing tokens in localStorage
|
||||
// Tokens are stored in httpOnly cookies by the backend
|
||||
state.jwt = newToken;
|
||||
},
|
||||
logOut(state){
|
||||
// Clear user data from localStorage
|
||||
localStorage.removeItem('u')
|
||||
// Clear state
|
||||
|
||||
// Make a request to the backend to invalidate the token
|
||||
axios.post('/api/token/blacklist/', { refresh: state.jwt?.refresh })
|
||||
.catch(error => console.error('Error blacklisting token:', error));
|
||||
state.jwt = null;
|
||||
state.user = null
|
||||
},
|
||||
updateUser(state, userData){
|
||||
@@ -69,95 +64,77 @@ export default createStore({
|
||||
username: username,
|
||||
password: password
|
||||
}
|
||||
axios.post('/api/token/', payload)
|
||||
.then((response)=>{
|
||||
context.commit('updateToken', response.data);
|
||||
api.get('/api/account').then(response => {
|
||||
context.commit('updateUser', response.data)
|
||||
})
|
||||
if ('next' in router.currentRoute.value.query) {
|
||||
router.push(router.currentRoute.value.query.next)
|
||||
} else {
|
||||
router.push('browse')
|
||||
}
|
||||
|
||||
})
|
||||
.catch((error)=>{
|
||||
const $toast = useToast();
|
||||
if (error.response.data.detail) {
|
||||
$toast.error(error.response.data.detail, {position:'top'});
|
||||
}
|
||||
if (error.response.data.username) {
|
||||
$toast.error("Username: " + error.response.data.username, {position:'top'});
|
||||
}
|
||||
if (error.response.data.password) {
|
||||
$toast.error("Password: " + error.response.data.password, {position:'top'});
|
||||
}
|
||||
|
||||
})
|
||||
},
|
||||
refreshToken(){
|
||||
// Don't attempt to refresh if we don't have a token
|
||||
if (!this.state.jwt || !this.state.jwt.refresh) {
|
||||
return Promise.reject(new Error('No refresh token available'));
|
||||
}
|
||||
|
||||
const payload = {
|
||||
refresh: this.state.jwt.refresh
|
||||
}
|
||||
|
||||
return axios.post('/api/token/refresh/', payload)
|
||||
// The response body is empty: the backend stores the tokens as HttpOnly cookies.
|
||||
api.post('/api/token/', payload)
|
||||
.then(() => api.get('/api/account'))
|
||||
.then((response) => {
|
||||
this.commit('updateToken', response.data);
|
||||
return response.data;
|
||||
context.commit('updateUser', response.data)
|
||||
if ('next' in router.currentRoute.value.query) {
|
||||
router.push(router.currentRoute.value.query.next)
|
||||
} else {
|
||||
router.push('browse')
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
const $toast = useToast();
|
||||
const data = error.response?.data ?? {};
|
||||
if (data.detail) {
|
||||
$toast.error(data.detail, {position:'top'});
|
||||
}
|
||||
if (data.username) {
|
||||
$toast.error("Username: " + data.username, {position:'top'});
|
||||
}
|
||||
if (data.password) {
|
||||
$toast.error("Password: " + data.password, {position:'top'});
|
||||
}
|
||||
})
|
||||
},
|
||||
refreshToken(){
|
||||
if (!this.state.user) {
|
||||
return Promise.reject(new Error('Not logged in'));
|
||||
}
|
||||
|
||||
// The refresh token is read from the cookie by the backend.
|
||||
return api.post('/api/token/refresh/', {})
|
||||
.then((response) => response.data)
|
||||
.catch((error) => {
|
||||
console.error('Token refresh failed:', error);
|
||||
// If refresh fails, log the user out and redirect to login
|
||||
this.commit('logOut');
|
||||
router.push({
|
||||
name: 'login',
|
||||
query: {
|
||||
next: router.currentRoute.value.fullPath,
|
||||
error: 'Your session has expired. Please log in again.'
|
||||
}
|
||||
});
|
||||
router.push(session_expired_query(router.currentRoute.value.fullPath));
|
||||
return Promise.reject(error);
|
||||
});
|
||||
},
|
||||
inspectToken(){
|
||||
const token = this.state.jwt;
|
||||
if (!token) return;
|
||||
|
||||
try {
|
||||
// For access token
|
||||
const decoded = jwtDecode(token.access);
|
||||
const exp = decoded.exp;
|
||||
const now = Date.now() / 1000;
|
||||
|
||||
// Refresh when token is within 5 minutes of expiring
|
||||
const refreshThreshold = 300; // 5 minutes in seconds
|
||||
|
||||
if (exp - now < refreshThreshold) {
|
||||
// Token is about to expire, refresh it
|
||||
this.dispatch('refreshToken');
|
||||
} else if (exp < now) {
|
||||
// Token is already expired, force logout
|
||||
this.commit('logOut');
|
||||
router.push({
|
||||
name: 'login',
|
||||
query: {
|
||||
next: router.currentRoute.value.fullPath,
|
||||
error: 'Your session has expired. Please log in again.'
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error inspecting token:', error);
|
||||
// If we can't decode the token, log the user out
|
||||
this.commit('logOut');
|
||||
router.push({name: 'login'});
|
||||
// Check that the cookie still identifies the user stored in localStorage.
|
||||
restoreSession(){
|
||||
if (!this.state.user) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
return api.get('/api/account')
|
||||
.then((response) => {
|
||||
this.commit('updateUser', response.data);
|
||||
return response.data;
|
||||
})
|
||||
.catch((error) => {
|
||||
if (error.response?.status === 401) {
|
||||
this.commit('logOut');
|
||||
router.push({ name: 'login' });
|
||||
}
|
||||
return null;
|
||||
});
|
||||
},
|
||||
logout(){
|
||||
const wasLoggedIn = this.state.user !== null;
|
||||
this.commit('logOut');
|
||||
|
||||
if (!wasLoggedIn) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
return api.post('/api/token/blacklist/', {})
|
||||
.catch((error) => {
|
||||
console.error('Error blacklisting token:', error);
|
||||
});
|
||||
}
|
||||
},
|
||||
modules: {
|
||||
|
||||
Reference in new issue
Block a user