security: migrate auth tokens to httpOnly cookies (hybrid bearer token approach)

Backend:
- CookieBearerToken middleware reads httpOnly cookie and injects Authorization
  header before Sanctum validates (prepended to API middleware group)
- SetAuthCookie trait provides cookie creation/expiry helpers with per-app
  cookie names (crewli_admin_token, crewli_app_token, crewli_portal_token)
- LoginController sets token via Set-Cookie, removes it from JSON body
- LogoutController expires the auth cookie on logout
- AuthRefreshController (POST /auth/refresh) rotates tokens with new cookie
- InvitationController accept also sets token via cookie, not JSON body
- All cookies: httpOnly, SameSite=Strict, Secure (in production)

Frontend (all three SPAs):
- Removed all localStorage token storage (apps/app, apps/portal)
- Removed all JS-readable cookie token storage (apps/admin)
- Removed Authorization: Bearer header interceptors from axios
- Auth stores now rely on GET /auth/me to validate httpOnly cookie
- Admin app: new Pinia auth store replaces useCookie-based auth pattern
- withCredentials: true ensures browser sends cookies automatically

Fixes security findings A13-1 (localStorage tokens) and A13-2 (admin
cookie flags). Tokens are now invisible to JavaScript.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-14 16:06:44 +02:00
parent 836cffa232
commit 513ca519b2
32 changed files with 826 additions and 227 deletions

View File

@@ -1,6 +1,5 @@
import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig } from 'axios'
import { useAuthStore } from '@/stores/useAuthStore'
const apiClient: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_URL,
@@ -14,12 +13,6 @@ const apiClient: AxiosInstance = axios.create({
apiClient.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
const authStore = useAuthStore()
if (authStore.token) {
config.headers.Authorization = `Bearer ${authStore.token}`
}
if (import.meta.env.DEV) {
console.log(`🚀 ${config.method?.toUpperCase()} ${config.url}`, config.data)
}
@@ -46,19 +39,13 @@ apiClient.interceptors.response.use(
}
if (error.response?.status === 401) {
const authStore = useAuthStore()
if (authStore.isInitialized) {
authStore.clearLocalSession()
if (typeof window !== 'undefined') {
const path = window.location.pathname
const publicPaths = ['/login', '/wachtwoord-vergeten', '/wachtwoord-resetten', '/verify-email-change']
if (!publicPaths.some(p => path.startsWith(p)) && !path.startsWith('/register')) {
window.location.href = '/login'
}
// Lazy import to avoid circular dependency
import('@/stores/useAuthStore').then(({ useAuthStore }) => {
const authStore = useAuthStore()
if (authStore.isInitialized) {
authStore.handleUnauthorized()
}
}
})
}
return Promise.reject(error)

View File

@@ -3,23 +3,12 @@ import { computed, ref } from 'vue'
import { apiClient } from '@/lib/axios'
import type { AuthMeUser } from '@/types/portal'
const TOKEN_KEY = 'crewli_portal_token'
export const useAuthStore = defineStore('auth', () => {
const token = ref<string | null>(localStorage.getItem(TOKEN_KEY))
const user = ref<AuthMeUser | null>(null)
const isInitialized = ref(false)
const isAuthenticated = computed(() => !!user.value)
function setToken(newToken: string | null) {
token.value = newToken
if (newToken)
localStorage.setItem(TOKEN_KEY, newToken)
else
localStorage.removeItem(TOKEN_KEY)
}
function setUser(data: AuthMeUser | null) {
user.value = data
}
@@ -29,13 +18,39 @@ export const useAuthStore = defineStore('auth', () => {
usePortalStore().reset()
}
async function fetchUser(): Promise<boolean> {
if (!token.value) {
setUser(null)
function clearState() {
user.value = null
void resetPortalStoresSync()
}
return false
function handleUnauthorized() {
clearState()
isInitialized.value = false
if (typeof window !== 'undefined') {
const path = window.location.pathname
const publicPaths = ['/login', '/wachtwoord-vergeten', '/wachtwoord-resetten', '/verify-email-change']
if (!publicPaths.some(p => path.startsWith(p)) && !path.startsWith('/register')) {
window.location.href = '/login'
}
}
}
async function login(email: string, password: string): Promise<void> {
const { data } = await apiClient.post<{
success: boolean
data: { user: AuthMeUser }
}>('/auth/login', { email, password })
// Token is set automatically via httpOnly Set-Cookie header
setUser(data.data.user)
// Validate by fetching full user data
const ok = await fetchUser()
if (!ok) throw new Error('Sessie kon niet worden gestart.')
}
async function fetchUser(): Promise<boolean> {
try {
const { data } = await apiClient.get<{ success: boolean; data: AuthMeUser }>('/auth/me')
setUser(data.data)
@@ -43,43 +58,20 @@ export const useAuthStore = defineStore('auth', () => {
return true
}
catch {
setToken(null)
setUser(null)
await resetPortalStoresSync()
clearState()
return false
}
}
async function login(email: string, password: string): Promise<void> {
const { data } = await apiClient.post<{
success: boolean
data: { user: AuthMeUser; token: string }
}>('/auth/login', { email, password })
setToken(data.data.token)
setUser(data.data.user)
const ok = await fetchUser()
if (!ok) throw new Error('Sessie kon niet worden gestart.')
}
function clearLocalSession(): void {
setToken(null)
setUser(null)
void resetPortalStoresSync()
}
async function logout(): Promise<void> {
try {
if (token.value)
await apiClient.post('/auth/logout')
await apiClient.post('/auth/logout')
}
catch {
// Ignore network errors; still clear local session
}
setToken(null)
setUser(null)
await resetPortalStoresSync()
clearState()
}
let initializePromise: Promise<void> | null = null
@@ -93,12 +85,6 @@ export const useAuthStore = defineStore('auth', () => {
}
async function doInitialize(): Promise<void> {
if (!token.value) {
isInitialized.value = true
return
}
try {
await fetchUser()
}
@@ -108,16 +94,14 @@ export const useAuthStore = defineStore('auth', () => {
}
return {
token,
user,
isAuthenticated,
isInitialized,
setToken,
setUser,
login,
logout,
fetchUser,
initialize,
clearLocalSession,
handleUnauthorized,
}
})