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
+30
-56
@@ -1,47 +1,15 @@
|
||||
import axios from "axios";
|
||||
import router from "@/router";
|
||||
import store from "@/store";
|
||||
import { jwtDecode } from "jwt-decode";
|
||||
|
||||
/**
|
||||
* Gets a valid access token or refreshes if needed
|
||||
* Uses a consistent 5-minute threshold for token expiration
|
||||
*/
|
||||
async function get_access_token() {
|
||||
// If we don't have tokens in the store, return null
|
||||
if (!store.state.jwt || !store.state.jwt.access) {
|
||||
return null;
|
||||
}
|
||||
// Authentication is cookie based: the browser sends the HttpOnly access token
|
||||
// automatically, so there is no Authorization header to set here.
|
||||
const axios_jwt = axios.create({ withCredentials: true });
|
||||
|
||||
try {
|
||||
const access = jwtDecode(store.state.jwt.access);
|
||||
const now = Date.now() / 1000;
|
||||
const refreshThreshold = 300; // 5 minutes in seconds
|
||||
|
||||
// If token is about to expire, refresh it
|
||||
if (access.exp - now < refreshThreshold) {
|
||||
try {
|
||||
// Wait for the token to refresh
|
||||
await store.dispatch('refreshToken');
|
||||
return store.state.jwt.access;
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh token:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return store.state.jwt.access;
|
||||
} catch (error) {
|
||||
console.error('Error decoding token:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const axios_jwt = axios.create();
|
||||
|
||||
// Add CSRF token to all requests if using cookies for authentication
|
||||
// Add the CSRF header if a csrftoken cookie exists. Cookie authentication is
|
||||
// protected against cross-site form posts by SameSite=Lax, so this is only used
|
||||
// when the backend does set the cookie.
|
||||
axios_jwt.interceptors.request.use(function(config) {
|
||||
// Get CSRF token from cookie if it exists
|
||||
const csrfToken = document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith('csrftoken='))
|
||||
@@ -54,26 +22,32 @@ axios_jwt.interceptors.request.use(function(config) {
|
||||
return config;
|
||||
});
|
||||
|
||||
// Add JWT token to all requests
|
||||
axios_jwt.interceptors.request.use(async function (config) {
|
||||
const access_token = await get_access_token();
|
||||
// A 401 means the access cookie is no longer valid. Try to refresh it once; if
|
||||
// that fails the session is gone, so log out and send the user to the login page.
|
||||
axios_jwt.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
const config = error.config;
|
||||
|
||||
if (access_token) {
|
||||
config.headers.Authorization = "Bearer " + access_token;
|
||||
} else if (!router.currentRoute.value.fullPath.includes('login')) {
|
||||
// Only redirect if we're not already on the login page
|
||||
router.push({
|
||||
name: 'login',
|
||||
query: {
|
||||
next: router.currentRoute.value.fullPath,
|
||||
error: 'Please log in to continue'
|
||||
if (error.response?.status === 401 && config && !config._retried && !config.url.includes('/token/')) {
|
||||
config._retried = true;
|
||||
try {
|
||||
await store.dispatch('refreshToken');
|
||||
return await axios_jwt.request(config);
|
||||
} catch {
|
||||
store.commit('logOut');
|
||||
router.push({
|
||||
name: 'login',
|
||||
query: {
|
||||
next: config.url,
|
||||
error: 'Your session has expired. Please log in again.'
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
}, function (error) {
|
||||
return Promise.reject(error);
|
||||
});
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export default axios_jwt
|
||||
@@ -51,12 +51,12 @@ export default {
|
||||
},
|
||||
computed: {
|
||||
isAuthenticated() {
|
||||
return !!this.$store.state.jwt;
|
||||
return this.$store.getters.isAuthenticated;
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
logout () {
|
||||
store.commit('logOut')
|
||||
store.dispatch('logout')
|
||||
router.push({name: 'login'})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,9 +21,14 @@ library.add(faBook, faBookOpen, faEdit, faTurnUp, faTimes, faCheck)
|
||||
import router from './router'
|
||||
import store from './store'
|
||||
|
||||
Vue.createApp(App)
|
||||
const app = Vue.createApp(App)
|
||||
.use(ToastPlugin)
|
||||
.use(store)
|
||||
.use(router)
|
||||
.component('font-awesome-icon', FontAwesomeIcon)
|
||||
.mount('#app')
|
||||
|
||||
// Validate the cookie before the first navigation, so the router guards see the
|
||||
// real session instead of whatever is left in localStorage.
|
||||
store.dispatch('restoreSession').finally(() => {
|
||||
app.mount('#app')
|
||||
})
|
||||
@@ -11,7 +11,7 @@ const HistoryView = () => import('@/views/HistoryView')
|
||||
|
||||
// Navigation guard to check if user is authenticated
|
||||
function requireAuth(to, from, next) {
|
||||
if (!store.state.jwt) {
|
||||
if (!store.getters.isAuthenticated) {
|
||||
next({
|
||||
name: 'login',
|
||||
query: { next: to.fullPath, error: 'Please log in to access this page' }
|
||||
@@ -23,7 +23,7 @@ function requireAuth(to, from, next) {
|
||||
|
||||
// Navigation guard to check if user is admin
|
||||
function requireAdmin(to, from, next) {
|
||||
if (!store.state.jwt || !store.getters.is_superuser) {
|
||||
if (!store.getters.isAuthenticated || !store.getters.is_superuser) {
|
||||
next({
|
||||
name: 'login',
|
||||
query: { next: to.fullPath, error: 'Admin access required' }
|
||||
|
||||
+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: {
|
||||
|
||||
@@ -3,6 +3,11 @@ const { VueLoaderPlugin } = require('vue-loader')
|
||||
const BundleTracker = require('webpack-bundle-tracker');
|
||||
const webpack = require('webpack')
|
||||
|
||||
// The dev server port. Keep this and the publicPath in sync - django-webpack-loader
|
||||
// builds the script URL from the publicPath written into webpack-stats.json.
|
||||
const DEV_PORT = process.env.DEV_PORT || 8001
|
||||
const DEV_PUBLIC_PATH = `http://localhost:${DEV_PORT}/`
|
||||
|
||||
module.exports = () => {
|
||||
return {
|
||||
|
||||
@@ -11,6 +16,7 @@ module.exports = () => {
|
||||
entry: path.resolve(__dirname, './src/main.js'),
|
||||
output: {
|
||||
path: path.resolve(__dirname, './dist/bundles/'),
|
||||
publicPath: DEV_PUBLIC_PATH,
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
@@ -47,7 +53,7 @@ module.exports = () => {
|
||||
new BundleTracker({
|
||||
filename: 'webpack-stats.json',
|
||||
path: path.resolve(__dirname, './'),
|
||||
publicPath: 'http://localhost:8080/'
|
||||
publicPath: DEV_PUBLIC_PATH
|
||||
}),
|
||||
new webpack.DefinePlugin({
|
||||
'process.env.BASE_URL': JSON.stringify(process.env.BASE_URL),
|
||||
@@ -55,6 +61,7 @@ module.exports = () => {
|
||||
new webpack.DefinePlugin({ __VUE_OPTIONS_API__: true, __VUE_PROD_DEVTOOLS__: true }),
|
||||
],
|
||||
devServer: {
|
||||
port: DEV_PORT,
|
||||
headers: {
|
||||
"Access-Control-Allow-Origin":"*"
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user