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

@@ -30,7 +30,8 @@ SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
# In production, use: SESSION_DOMAIN=.crewli.app
SESSION_DOMAIN=localhost
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Api\V1\Traits\SetAuthCookie;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\V1\MeResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
final class AuthRefreshController extends Controller
{
use SetAuthCookie;
public function __invoke(Request $request): JsonResponse
{
$user = $request->user();
// Revoke the current token
$request->user()->currentAccessToken()->delete();
// Create a new token
$newToken = $user->createToken('auth-token')->plainTextToken;
$cookieName = $this->resolveCookieName($request);
$user->load(['organisations', 'roles', 'permissions']);
Log::info('Auth token refreshed', [
'user_id' => $user->id,
'ip' => $request->ip(),
]);
return $this->success(new MeResource($user), 'Token refreshed')
->withCookie($this->makeAuthCookie($cookieName, $newToken));
}
}

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Api\V1\Traits\SetAuthCookie;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\AcceptInvitationRequest;
use App\Http\Requests\Api\V1\StoreInvitationRequest;
@@ -16,6 +17,7 @@ use Illuminate\Support\Facades\Gate;
final class InvitationController extends Controller
{
use SetAuthCookie;
public function __construct(
private readonly InvitationService $invitationService,
) {}
@@ -63,6 +65,7 @@ final class InvitationController extends Controller
);
$sanctumToken = $user->createToken('auth-token')->plainTextToken;
$cookieName = $this->resolveCookieName($request);
return $this->success([
'user' => [
@@ -72,8 +75,8 @@ final class InvitationController extends Controller
'full_name' => $user->full_name,
'email' => $user->email,
],
'token' => $sanctumToken,
], 'Uitnodiging geaccepteerd');
], 'Uitnodiging geaccepteerd')
->withCookie($this->makeAuthCookie($cookieName, $sanctumToken));
}
public function revoke(Organisation $organisation, UserInvitation $invitation): JsonResponse

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Api\V1\Traits\SetAuthCookie;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\LoginRequest;
use App\Http\Resources\Api\V1\UserResource;
@@ -13,6 +14,8 @@ use Illuminate\Support\Facades\Log;
final class LoginController extends Controller
{
use SetAuthCookie;
public function __invoke(LoginRequest $request): JsonResponse
{
if (!Auth::attempt($request->only('email', 'password'))) {
@@ -27,10 +30,11 @@ final class LoginController extends Controller
$user = Auth::user()->load(['organisations', 'roles']);
$token = $user->createToken('auth-token')->plainTextToken;
$cookieName = $this->resolveCookieName($request);
return $this->success([
'user' => new UserResource($user),
'token' => $token,
], 'Login successful');
], 'Login successful')
->withCookie($this->makeAuthCookie($cookieName, $token));
}
}

View File

@@ -4,16 +4,22 @@ declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Api\V1\Traits\SetAuthCookie;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final class LogoutController extends Controller
{
use SetAuthCookie;
public function __invoke(Request $request): JsonResponse
{
$request->user()->currentAccessToken()->delete();
return $this->success(null, 'Logged out successfully');
$cookieName = $this->resolveCookieName($request);
return $this->success(null, 'Logged out successfully')
->withCookie($this->forgetAuthCookie($cookieName));
}
}

View File

@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1\Traits;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Cookie;
trait SetAuthCookie
{
private const COOKIE_MAP = [
'admin' => 'crewli_admin_token',
'app' => 'crewli_app_token',
'portal' => 'crewli_portal_token',
];
private const COOKIE_TTL_MINUTES = 60 * 24 * 7; // 7 days
protected function resolveCookieName(Request $request): string
{
$origin = $request->headers->get('Origin')
?? $request->headers->get('Referer')
?? '';
$adminUrl = config('app.frontend_admin_url', 'http://localhost:5173');
$appUrl = config('app.frontend_app_url', 'http://localhost:5174');
$portalUrl = config('app.frontend_portal_url', 'http://localhost:5175');
if ($this->originMatches($origin, $adminUrl)) {
return self::COOKIE_MAP['admin'];
}
if ($this->originMatches($origin, $appUrl)) {
return self::COOKIE_MAP['app'];
}
if ($this->originMatches($origin, $portalUrl)) {
return self::COOKIE_MAP['portal'];
}
return self::COOKIE_MAP['app'];
}
protected function makeAuthCookie(string $cookieName, string $token): Cookie
{
return new Cookie(
name: $cookieName,
value: $token,
expire: now()->addMinutes(self::COOKIE_TTL_MINUTES),
path: '/',
domain: config('session.domain'),
secure: config('app.env') === 'production',
httpOnly: true,
sameSite: 'Strict',
);
}
protected function forgetAuthCookie(string $cookieName): Cookie
{
return new Cookie(
name: $cookieName,
value: '',
expire: now()->subMinute(),
path: '/',
domain: config('session.domain'),
secure: config('app.env') === 'production',
httpOnly: true,
sameSite: 'Strict',
);
}
private function originMatches(string $origin, string $configuredUrl): bool
{
if ($origin === '' || $configuredUrl === '') {
return false;
}
// Parse to compare host+port, ignoring trailing slashes and paths
$originHost = parse_url($origin, PHP_URL_HOST);
$originPort = parse_url($origin, PHP_URL_PORT);
$configHost = parse_url($configuredUrl, PHP_URL_HOST);
$configPort = parse_url($configuredUrl, PHP_URL_PORT);
return $originHost === $configHost && $originPort === $configPort;
}
}

View File

@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
final class CookieBearerToken
{
private const COOKIE_NAMES = [
'crewli_admin_token',
'crewli_app_token',
'crewli_portal_token',
];
public function handle(Request $request, Closure $next): Response
{
// Skip if an Authorization header is already present
if ($request->hasHeader('Authorization')) {
return $next($request);
}
foreach (self::COOKIE_NAMES as $cookieName) {
$token = $request->cookie($cookieName);
if ($token) {
$request->headers->set('Authorization', 'Bearer ' . $token);
break;
}
}
return $next($request);
}
}

View File

@@ -27,6 +27,11 @@ return Application::configure(basePath: dirname(__DIR__))
$middleware->append(\App\Http\Middleware\SecurityHeaders::class);
// Read httpOnly auth cookie and inject as Authorization header (before Sanctum)
$middleware->api(prepend: [
\App\Http\Middleware\CookieBearerToken::class,
]);
$middleware->alias([
'portal.token' => \App\Http\Middleware\PortalTokenMiddleware::class,
]);

View File

@@ -30,6 +30,7 @@ use App\Http\Controllers\Api\V1\VolunteerRegistrationController;
use App\Http\Controllers\Api\V1\PublicRegistrationDataController;
use App\Http\Controllers\Api\V1\PortalTokenController;
use App\Http\Controllers\Api\V1\AccountController;
use App\Http\Controllers\Api\V1\AuthRefreshController;
use App\Http\Controllers\Api\V1\EmailChangeController;
use App\Http\Controllers\Api\V1\PasswordResetController;
use App\Http\Controllers\Api\V1\PortalMeController;
@@ -82,6 +83,7 @@ Route::middleware('auth:sanctum')->group(function () {
// Auth
Route::get('auth/me', MeController::class);
Route::post('auth/logout', LogoutController::class);
Route::post('auth/refresh', AuthRefreshController::class);
// Account management (self-service)
Route::post('me/change-password', [AccountController::class, 'changePassword']);

View File

@@ -24,10 +24,13 @@ class LoginTest extends TestCase
$response->assertOk()
->assertJsonStructure([
'success',
'data' => ['user' => ['id', 'first_name', 'last_name', 'full_name', 'email'], 'token'],
'data' => ['user' => ['id', 'first_name', 'last_name', 'full_name', 'email']],
'message',
])
->assertJson(['success' => true]);
// Token must NOT be in response body (set via httpOnly cookie)
$this->assertArrayNotHasKey('token', $response->json('data'));
}
public function test_login_fails_with_invalid_credentials(): void

View File

@@ -159,7 +159,9 @@ class InvitationTest extends TestCase
]);
$response->assertOk();
$response->assertJsonStructure(['data' => ['user' => ['id', 'first_name', 'last_name', 'full_name', 'email'], 'token']]);
$response->assertJsonStructure(['data' => ['user' => ['id', 'first_name', 'last_name', 'full_name', 'email']]]);
// Token must NOT be in response body (set via httpOnly cookie)
$this->assertArrayNotHasKey('token', $response->json('data'));
$this->assertDatabaseHas('users', ['email' => 'newuser@test.nl']);
$this->assertDatabaseHas('organisation_user', [
@@ -187,7 +189,9 @@ class InvitationTest extends TestCase
$response = $this->postJson("/api/v1/invitations/{$invitation->plainToken}/accept");
$response->assertOk();
$response->assertJsonStructure(['data' => ['user', 'token']]);
$response->assertJsonStructure(['data' => ['user']]);
// Token must NOT be in response body (set via httpOnly cookie)
$this->assertArrayNotHasKey('token', $response->json('data'));
$this->assertDatabaseHas('organisation_user', [
'user_id' => $existingUser->id,

View File

@@ -0,0 +1,207 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Security;
use App\Models\User;
use Database\Seeders\RoleSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
final class HttpOnlyCookieAuthTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed(RoleSeeder::class);
// Enable cookies for JSON requests (required for cookie-based auth testing)
$this->withCredentials();
}
// --- Login Cookie Tests ---
public function test_login_response_does_not_contain_token_in_json_body(): void
{
$user = User::factory()->create();
$response = $this->postJson('/api/v1/auth/login', [
'email' => $user->email,
'password' => 'password',
]);
$response->assertOk();
$response->assertJsonMissing(['token']);
$this->assertArrayNotHasKey('token', $response->json('data'));
}
public function test_login_response_sets_httponly_cookie(): void
{
$user = User::factory()->create();
$response = $this->postJson('/api/v1/auth/login', [
'email' => $user->email,
'password' => 'password',
], ['Origin' => 'http://localhost:5174']);
$response->assertOk();
$response->assertCookie('crewli_app_token');
}
public function test_login_cookie_has_httponly_flag(): void
{
$user = User::factory()->create();
$response = $this->postJson('/api/v1/auth/login', [
'email' => $user->email,
'password' => 'password',
], ['Origin' => 'http://localhost:5174']);
$cookie = $this->findCookie($response, 'crewli_app_token');
$this->assertNotNull($cookie, 'Cookie crewli_app_token not found');
$this->assertTrue($cookie->isHttpOnly(), 'Cookie must be httpOnly');
}
public function test_login_cookie_has_samesite_strict(): void
{
$user = User::factory()->create();
$response = $this->postJson('/api/v1/auth/login', [
'email' => $user->email,
'password' => 'password',
], ['Origin' => 'http://localhost:5174']);
$cookie = $this->findCookie($response, 'crewli_app_token');
$this->assertNotNull($cookie);
$this->assertEquals('strict', strtolower($cookie->getSameSite()));
}
public function test_login_sets_admin_cookie_for_admin_origin(): void
{
$user = User::factory()->create();
$response = $this->postJson('/api/v1/auth/login', [
'email' => $user->email,
'password' => 'password',
], ['Origin' => 'http://localhost:5173']);
$response->assertOk();
$response->assertCookie('crewli_admin_token');
}
public function test_login_sets_portal_cookie_for_portal_origin(): void
{
$user = User::factory()->create();
$response = $this->postJson('/api/v1/auth/login', [
'email' => $user->email,
'password' => 'password',
], ['Origin' => 'http://localhost:5175']);
$response->assertOk();
$response->assertCookie('crewli_portal_token');
}
// --- Middleware Tests ---
public function test_request_with_auth_cookie_is_authenticated(): void
{
$user = User::factory()->create();
$token = $user->createToken('auth-token')->plainTextToken;
$response = $this->withUnencryptedCookie('crewli_app_token', $token)
->getJson('/api/v1/auth/me');
$response->assertOk();
$response->assertJsonPath('data.id', $user->id);
}
public function test_request_with_invalid_cookie_returns_401(): void
{
$response = $this->withUnencryptedCookie('crewli_app_token', 'invalid-token-value')
->getJson('/api/v1/auth/me');
$response->assertUnauthorized();
}
public function test_request_without_cookie_or_header_returns_401(): void
{
$response = $this->getJson('/api/v1/auth/me');
$response->assertUnauthorized();
}
// --- Logout Tests ---
public function test_logout_expires_auth_cookie(): void
{
$user = User::factory()->create();
$token = $user->createToken('auth-token')->plainTextToken;
$response = $this->withUnencryptedCookie('crewli_app_token', $token)
->postJson('/api/v1/auth/logout', [], ['Origin' => 'http://localhost:5174']);
$response->assertOk();
$cookie = $this->findCookie($response, 'crewli_app_token');
$this->assertNotNull($cookie, 'Cookie crewli_app_token not found in logout response');
// Expired cookie has a past expiry time
$this->assertTrue($cookie->getExpiresTime() < time(), 'Logout cookie must be expired');
}
// --- Refresh Tests ---
public function test_refresh_revokes_old_token_and_sets_new_cookie(): void
{
$user = User::factory()->create();
$accessToken = $user->createToken('auth-token');
$token = $accessToken->plainTextToken;
$response = $this->withUnencryptedCookie('crewli_app_token', $token)
->postJson('/api/v1/auth/refresh', [], ['Origin' => 'http://localhost:5174']);
$response->assertOk();
$response->assertCookie('crewli_app_token');
// New cookie should contain a different token
$newCookie = $this->findCookie($response, 'crewli_app_token');
$this->assertNotNull($newCookie);
$this->assertNotEquals($token, $newCookie->getValue(), 'New token must differ from old token');
// Old token should be revoked in the database
$this->assertNull(
\Laravel\Sanctum\PersonalAccessToken::findToken($token),
'Old token must be deleted from database',
);
// New token should be valid in the database
$this->assertNotNull(
\Laravel\Sanctum\PersonalAccessToken::findToken($newCookie->getValue()),
'New token must exist in database',
);
}
public function test_refresh_with_expired_token_returns_401(): void
{
$response = $this->withUnencryptedCookie('crewli_app_token', 'expired-or-invalid-token')
->postJson('/api/v1/auth/refresh');
$response->assertUnauthorized();
}
// --- Helper ---
private function findCookie($response, string $name): ?\Symfony\Component\HttpFoundation\Cookie
{
foreach ($response->headers->getCookies() as $cookie) {
if ($cookie->getName() === $name) {
return $cookie;
}
}
return null;
}
}

View File

@@ -1,4 +1,4 @@
import { useCookie } from '@core/composable/useCookie'
import { useAuthStore } from '@/stores/useAuthStore'
import { computed } from 'vue'
export interface AuthOrganisationSummary {
@@ -17,12 +17,12 @@ export interface AuthUserCookie {
}
/**
* First organisation from the session cookie (set at login). Super-admins still need an organisation context for nested event routes.
* First organisation from the auth store (set at login). Super-admins still need an organisation context for nested event routes.
*/
export function useCurrentOrganisationId() {
const userData = useCookie<AuthUserCookie | null>('userData')
const authStore = useAuthStore()
const organisationId = computed(() => userData.value?.organisations?.[0]?.id ?? null)
const organisationId = computed(() => authStore.user?.organisations?.[0]?.id ?? null)
return { organisationId }
}

View File

@@ -1,37 +1,21 @@
<script setup lang="ts">
import { PerfectScrollbar } from 'vue3-perfect-scrollbar'
import { useAuthStore } from '@/stores/useAuthStore'
const router = useRouter()
const ability = useAbility()
const authStore = useAuthStore()
// TODO: Get type from backend
const userData = useCookie<any>('userData')
const userData = computed(() => authStore.user)
const logout = async () => {
try {
// Call API logout endpoint
await $api('/auth/logout', { method: 'POST' })
}
catch (err) {
// Continue with logout even if API call fails
console.error('Logout API error:', err)
}
// Remove "accessToken" from cookie
useCookie('accessToken').value = null
// Remove "userData" from cookie
userData.value = null
// Redirect to login page
await router.push('/login')
// We had to remove abilities in then block because if we don't nav menu items mutation is visible while redirecting user to login page
// Remove "userAbilities" from cookie
useCookie('userAbilityRules').value = null
await authStore.logout()
// Reset ability to initial ability
ability.update([])
// Redirect to login page
await router.push('/login')
}
const userProfileList = [

View File

@@ -1,9 +1,9 @@
import axios from 'axios'
import { parse } from 'cookie-es'
import type { AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig } from 'axios'
const apiClient: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_URL,
withCredentials: true,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
@@ -11,21 +11,8 @@ const apiClient: AxiosInstance = axios.create({
timeout: 30000,
})
function getAccessToken(): string | null {
if (typeof document === 'undefined') return null
const cookies = parse(document.cookie)
const token = cookies.accessToken
return token ?? null
}
apiClient.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
const token = getAccessToken()
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
if (import.meta.env.DEV) {
console.log(`🚀 ${config.method?.toUpperCase()} ${config.url}`, config.data)
}
@@ -52,13 +39,13 @@ apiClient.interceptors.response.use(
}
if (error.response?.status === 401) {
document.cookie = 'accessToken=; path=/; max-age=0'
document.cookie = 'userData=; path=/; max-age=0'
document.cookie = 'userAbilityRules=; path=/; max-age=0'
const publicPaths = ['/login', '/forgot-password', '/reset-password', '/verify-email-change']
if (!publicPaths.some(p => window.location.pathname.startsWith(p))) {
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

@@ -12,14 +12,13 @@ import authV2MaskLight from '@images/pages/misc-mask-light.png'
import { VNodeRenderer } from '@layouts/components/VNodeRenderer'
import { themeConfig } from '@themeConfig'
import { getUserAbilityRules } from '@/utils/auth-ability'
import type { Rule } from '@/plugins/casl/ability'
import { useAuthStore } from '@/stores/useAuthStore'
import type { AuthUserCookie } from '@/composables/useOrganisationContext'
interface LoginApiPayload {
success: boolean
data: {
user: AuthUserCookie & Record<string, unknown>
token: string
}
message?: string
}
@@ -43,6 +42,7 @@ const router = useRouter()
const passwordResetDone = computed(() => route.query.reset === '1')
const ability = useAbility()
const authStore = useAuthStore()
const errors = ref<Record<string, string | undefined>>({
email: undefined,
@@ -80,20 +80,16 @@ const login = async () => {
},
})
// Handle our API response format: { success, data: { user, token }, message }
// Token is set automatically via httpOnly Set-Cookie header
const { data } = res
const userData = data.user
const accessToken = data.token
const roles = Array.isArray(userData.roles) ? userData.roles : []
const userAbilityRules = getUserAbilityRules(roles)
useCookie<Rule[]>('userAbilityRules').value = userAbilityRules
authStore.setUser(userData, roles)
ability.update(userAbilityRules)
useCookie<AuthUserCookie>('userData').value = userData
useCookie<string>('accessToken').value = accessToken
// Redirect to `to` query if exist or redirect to index route
await nextTick()
const rawTo = route.query.to ? String(route.query.to) : ''

View File

@@ -5,14 +5,13 @@ import AuthProvider from '@/views/pages/authentication/AuthProvider.vue'
import { VNodeRenderer } from '@layouts/components/VNodeRenderer'
import { themeConfig } from '@themeConfig'
import { getUserAbilityRules } from '@/utils/auth-ability'
import type { Rule } from '@/plugins/casl/ability'
import { useAuthStore } from '@/stores/useAuthStore'
import type { AuthUserCookie } from '@/composables/useOrganisationContext'
interface RegisterApiPayload {
success: boolean
data: {
user: AuthUserCookie & Record<string, unknown>
token: string
}
message?: string
}
@@ -84,18 +83,16 @@ const register = async () => {
},
})
// Handle our API response format
// Token is set automatically via httpOnly Set-Cookie header
const { data } = res
const userData = data.user
const accessToken = data.token
const roles = Array.isArray(userData.roles) ? userData.roles : []
const userAbilityRules = getUserAbilityRules(roles)
useCookie<Rule[]>('userAbilityRules').value = userAbilityRules
const authStore = useAuthStore()
authStore.setUser(userData, roles)
ability.update(userAbilityRules)
useCookie<AuthUserCookie>('userData').value = userData
useCookie<string>('accessToken').value = accessToken
await nextTick(() => {
router.replace('/')

View File

@@ -2,6 +2,7 @@
import { VNodeRenderer } from '@layouts/components/VNodeRenderer'
import { themeConfig } from '@themeConfig'
import { apiClient } from '@/lib/axios'
import { useAuthStore } from '@/stores/useAuthStore'
definePage({
meta: {
@@ -26,10 +27,9 @@ onMounted(async () => {
try {
await apiClient.post('/verify-email-change', { token })
success.value = true
// Clear auth cookies — email changed, force re-login
document.cookie = 'accessToken=; path=/; max-age=0'
document.cookie = 'userData=; path=/; max-age=0'
document.cookie = 'userAbilityRules=; path=/; max-age=0'
// Clear auth state — email changed, force re-login
const authStore = useAuthStore()
authStore.clearState()
}
catch (error: unknown) {
const ax = error as { response?: { data?: { errors?: Record<string, string[]>; message?: string } } }

View File

@@ -1,4 +1,5 @@
import type { RouteRecordRaw } from 'vue-router/auto'
import { useAuthStore } from '@/stores/useAuthStore'
const emailRouteComponent = () => import('@/pages/apps/email/index.vue')
@@ -10,23 +11,14 @@ export const redirects: RouteRecordRaw[] = [
path: '/',
name: 'index',
redirect: to => {
const userData = useCookie<Record<string, unknown> | null | undefined>('userData')
const accessToken = useCookie<string | null | undefined>('accessToken')
const isLoggedIn = !!(userData.value && accessToken.value)
const authStore = useAuthStore()
if (!isLoggedIn)
if (!authStore.isAuthenticated)
return { name: 'login', query: to.query }
// Laravel API + Spatie: `roles` is string[] (e.g. super_admin, org_admin)
const roles = Array.isArray(userData.value?.roles)
? (userData.value!.roles as string[])
const roles = Array.isArray(authStore.user?.roles)
? authStore.user!.roles
: []
const legacyRole = userData.value?.role as string | undefined
if (legacyRole === 'admin')
return { name: 'dashboards-crm' }
if (legacyRole === 'client')
return { name: 'access-control' }
const isOrgUser = roles.some(r =>
['super_admin', 'org_admin', 'org_member', 'org_readonly'].includes(r),

View File

@@ -1,13 +1,24 @@
import type { RouteNamedMap, _RouterTyped } from "unplugin-vue-router";
import { canNavigate } from "@layouts/plugins/casl";
import { useAuthStore } from "@/stores/useAuthStore";
export const setupGuards = (
router: _RouterTyped<RouteNamedMap & { [key: string]: any }>
) => {
// 👉 router.beforeEach
// Docs: https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards
router.beforeEach((to, from) => {
// Debug logging
router.beforeEach(async (to, from) => {
const authStore = useAuthStore();
// Wait for initialization to complete (only blocks on first navigation)
if (!authStore.isInitialized) {
await authStore.initialize();
// Update CASL ability after initialization
if (authStore.isAuthenticated && authStore.abilityRules.length > 0) {
const ability = useAbility();
ability.update(authStore.abilityRules);
}
}
if (import.meta.env.DEV) {
console.log("🔒 Router Guard:", {
to: to.path,
@@ -33,27 +44,12 @@ export const setupGuards = (
return;
}
/**
* Check if user is logged in by checking if token & user data exists in local storage
* Feel free to update this logic to suit your needs
*/
const userData = useCookie("userData").value;
const accessToken = useCookie("accessToken").value;
const isLoggedIn = !!(userData && accessToken);
const isLoggedIn = authStore.isAuthenticated;
if (import.meta.env.DEV) {
const userDataObj = userData as Record<string, any> | null;
console.log("🔐 Auth Check:", {
isLoggedIn,
hasUserData: !!userData,
hasAccessToken: !!accessToken,
userData: userDataObj
? {
id: userDataObj.id,
email: userDataObj.email,
role: userDataObj.role,
}
: null,
hasUser: !!authStore.user,
});
}

View File

@@ -2,11 +2,10 @@ import type { App } from 'vue'
import { createMongoAbility } from '@casl/ability'
import { abilitiesPlugin } from '@casl/vue'
import type { Rule } from './ability'
export default function (app: App) {
const userAbilityRules = useCookie<Rule[]>('userAbilityRules')
const initialAbility = createMongoAbility(userAbilityRules.value ?? [])
// Initial ability is empty — gets populated after auth initialization
const initialAbility = createMongoAbility([])
app.use(abilitiesPlugin, initialAbility, {
useGlobalProperties: true,

View File

@@ -0,0 +1,112 @@
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { apiClient } from '@/lib/axios'
import { getUserAbilityRules } from '@/utils/auth-ability'
import type { Rule } from '@/plugins/casl/ability'
import type { AuthUserCookie } from '@/composables/useOrganisationContext'
interface MeResponse {
id: string
first_name: string
last_name: string
full_name: string
email: string
timezone: string
locale: string
avatar: string | null
organisations: Array<{
id: string
name: string
slug: string
role: string
}>
app_roles: string[]
permissions: string[]
}
export const useAuthStore = defineStore('auth', () => {
const user = ref<AuthUserCookie | null>(null)
const abilityRules = ref<Rule[]>([])
const isInitialized = ref(false)
const isAuthenticated = computed(() => !!user.value)
function setUser(userData: AuthUserCookie, roles: string[]) {
user.value = userData
abilityRules.value = getUserAbilityRules(roles)
}
function clearState() {
user.value = null
abilityRules.value = []
}
function handleUnauthorized() {
clearState()
isInitialized.value = false
if (typeof window !== 'undefined') {
const publicPaths = ['/login', '/forgot-password', '/reset-password', '/verify-email-change']
if (!publicPaths.some(p => window.location.pathname.startsWith(p))) {
window.location.href = '/login'
}
}
}
async function logout() {
try {
await apiClient.post('/auth/logout')
}
catch {
// Continue with logout even if API call fails
}
clearState()
}
let initializePromise: Promise<void> | null = null
function initialize(): Promise<void> {
if (isInitialized.value) return Promise.resolve()
if (!initializePromise) {
initializePromise = doInitialize()
}
return initializePromise
}
async function doInitialize(): Promise<void> {
try {
const { data } = await apiClient.get<{ success: boolean; data: MeResponse }>('/auth/me')
const me = data.data
const roles = me.app_roles ?? []
setUser(
{
id: me.id,
name: me.full_name,
email: me.email,
roles,
organisations: me.organisations,
},
roles,
)
}
catch {
clearState()
}
finally {
isInitialized.value = true
}
}
return {
user,
abilityRules,
isAuthenticated,
isInitialized,
setUser,
clearState,
logout,
handleUnauthorized,
initialize,
}
})

View File

@@ -13,7 +13,7 @@ export function useLogin() {
return data
},
onSuccess: (data) => {
authStore.setToken(data.data.token)
// Token is set automatically via httpOnly Set-Cookie header
authStore.setUser(data.data.user)
queryClient.setQueryData(['auth', 'me'], data.data.user)
},

View File

@@ -1,6 +1,5 @@
import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig } from 'axios'
import { useAuthStore } from '@/stores/useAuthStore'
import { useNotificationStore } from '@/stores/useNotificationStore'
import { useOrganisationStore } from '@/stores/useOrganisationStore'
@@ -16,13 +15,8 @@ const apiClient: AxiosInstance = axios.create({
apiClient.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
const authStore = useAuthStore()
const orgStore = useOrganisationStore()
if (authStore.token) {
config.headers.Authorization = `Bearer ${authStore.token}`
}
if (orgStore.activeOrganisationId) {
config.headers['X-Organisation-Id'] = orgStore.activeOrganisationId
}
@@ -53,16 +47,13 @@ apiClient.interceptors.response.use(
const notificationStore = useNotificationStore()
if (status === 401) {
const authStore = useAuthStore()
// During initialization, let initialize() handle the 401 — skip redirect
if (authStore.isInitialized) {
authStore.logout()
if (typeof window !== 'undefined' && window.location.pathname !== '/login') {
window.location.href = '/login'
// Lazy import to avoid circular dependency
import('@/stores/useAuthStore').then(({ useAuthStore }) => {
const authStore = useAuthStore()
if (authStore.isInitialized) {
authStore.handleUnauthorized()
}
}
})
}
else if (status === 403) {
notificationStore.show('You don\'t have permission for this action.', 'error')

View File

@@ -64,7 +64,7 @@ function onSubmit() {
{ token: token.value, ...payload },
{
onSuccess: (response) => {
authStore.setToken(response.data.token)
// Token is set automatically via httpOnly Set-Cookie header
authStore.setUser(response.data.user)
router.replace('/dashboard')
},

View File

@@ -4,18 +4,14 @@ import { apiClient } from '@/lib/axios'
import { useOrganisationStore } from '@/stores/useOrganisationStore'
import type { MeResponse, Organisation, User } from '@/types/auth'
const TOKEN_KEY = 'crewli_token'
export const useAuthStore = defineStore('auth', () => {
const token = ref<string | null>(localStorage.getItem(TOKEN_KEY))
const user = ref<User | null>(null)
const organisations = ref<Organisation[]>([])
const appRoles = ref<string[]>([])
const permissions = ref<string[]>([])
const isInitialized = ref(false)
// Requires both a token AND a validated user — token alone is not enough
const isAuthenticated = computed(() => !!token.value && !!user.value)
const isAuthenticated = computed(() => !!user.value)
const isSuperAdmin = computed(() => appRoles.value?.includes('super_admin') ?? false)
const currentOrganisation = computed(() => {
@@ -25,11 +21,6 @@ export const useAuthStore = defineStore('auth', () => {
?? null
})
function setToken(newToken: string) {
token.value = newToken
localStorage.setItem(TOKEN_KEY, newToken)
}
function setUser(me: MeResponse) {
user.value = {
id: me.id,
@@ -57,21 +48,40 @@ export const useAuthStore = defineStore('auth', () => {
orgStore.setActiveOrganisation(id)
}
function logout() {
token.value = null
function clearState() {
user.value = null
organisations.value = []
appRoles.value = []
permissions.value = []
localStorage.removeItem(TOKEN_KEY)
const orgStore = useOrganisationStore()
orgStore.clear()
}
function handleUnauthorized() {
clearState()
isInitialized.value = false
if (typeof window !== 'undefined' && window.location.pathname !== '/login') {
window.location.href = '/login'
}
}
async function logout() {
try {
await apiClient.post('/auth/logout')
}
catch {
// Ignore network errors; still clear local state
}
finally {
clearState()
}
}
/**
* Called once on app startup. If a token exists in localStorage,
* validates it by calling GET /auth/me. On 401, clears everything.
* Called once on app startup. Validates the httpOnly cookie by calling
* GET /auth/me. On 401, clears everything.
* Safe to call multiple times — subsequent calls return the same promise.
*/
let initializePromise: Promise<void> | null = null
@@ -85,18 +95,13 @@ export const useAuthStore = defineStore('auth', () => {
}
async function doInitialize(): Promise<void> {
if (!token.value) {
isInitialized.value = true
return
}
try {
const { data } = await apiClient.get<{ success: boolean; data: MeResponse }>('/auth/me')
setUser(data.data)
}
catch {
// Token invalid/expired — clear everything
logout()
// Cookie invalid/expired or not present — clear everything
clearState()
}
finally {
isInitialized.value = true
@@ -104,7 +109,6 @@ export const useAuthStore = defineStore('auth', () => {
}
return {
token,
user,
organisations,
appRoles,
@@ -113,10 +117,10 @@ export const useAuthStore = defineStore('auth', () => {
isInitialized,
isSuperAdmin,
currentOrganisation,
setToken,
setUser,
setActiveOrganisation,
logout,
handleUnauthorized,
initialize,
}
})

View File

@@ -39,7 +39,6 @@ export interface LoginResponse {
success: boolean
data: {
user: MeResponse
token: string
}
message: string
}

View File

@@ -83,7 +83,6 @@ export interface AcceptInvitationResponse {
app_roles: string[]
permissions: string[]
}
token: string
}
message: string
}

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,
}
})

View File

@@ -2,13 +2,14 @@
Base path: `/api/v1/`
Auth: Bearer token (Sanctum)
Auth: Bearer token (Sanctum) — token delivered via httpOnly cookie, never in the JSON response body. See `/dev-docs/AUTH_ARCHITECTURE.md` for full details.
## Auth
- `POST /auth/login`
- `POST /auth/login` — returns user data in JSON body. The Sanctum bearer token is set as an httpOnly cookie via `Set-Cookie` header (not included in response body).
- `POST /auth/logout`
- `GET /auth/me`
- `POST /auth/refresh` — rotates the Sanctum token: revokes current token, creates new one, sets new httpOnly cookie. Returns current user data.
- `POST /auth/forgot-password` — request password reset (public, rate-limited). Body: `{ email, app: "app"|"portal"|"admin" }`. Always returns 200 (no email enumeration).
- `POST /auth/reset-password` — reset password with token (public). Body: `{ token, email, password, password_confirmation }`.

View File

@@ -0,0 +1,173 @@
# Crewli — Authentication Architecture
> Version: 1.0 — April 2026
> Audience: security auditors, backend developers
---
## 1. Authentication Overview
Crewli uses **stateless token-based authentication** via Laravel Sanctum. Three SPA clients communicate with a single REST API. Tokens are stored exclusively in **httpOnly cookies** set by the server — they are never exposed to JavaScript via response bodies, localStorage, or JS-readable cookies.
### Client Applications
| App | URL (dev) | URL (prod) | Purpose |
|-----|-----------|------------|---------|
| Admin | localhost:5173 | admin.crewli.app | Super admin / platform management |
| App | localhost:5174 | app.crewli.app | Organiser dashboard |
| Portal | localhost:5175 | portal.crewli.app | Volunteers, artists, suppliers |
### Access Modes
The Portal supports two access modes:
1. **Cookie-based** (`auth:sanctum`): volunteers and crew who have a `user_id` — login with email/password, httpOnly cookie set on login
2. **Token-based** (`portal.token` middleware): artists, suppliers, press — stateless per-request token via `Authorization: Bearer` header or `?token=` query parameter. No cookies involved.
---
## 2. Cookie Specification
| App | Cookie Name | Domain | Secure | httpOnly | SameSite | Max-Age |
|-----|-------------|--------|--------|----------|----------|---------|
| Admin | `crewli_admin_token` | `.crewli.app` (prod) / `localhost` (dev) | Yes (prod) | Yes | Strict | 7 days |
| App | `crewli_app_token` | `.crewli.app` (prod) / `localhost` (dev) | Yes (prod) | Yes | Strict | 7 days |
| Portal | `crewli_portal_token` | `.crewli.app` (prod) / `localhost` (dev) | Yes (prod) | Yes | Strict | 7 days |
Each SPA gets its own cookie name to prevent shared auth state between apps. The cookie domain is configured via `SESSION_DOMAIN` in `.env`.
---
## 3. Token Lifecycle
### Creation
On successful login (`POST /auth/login`), the server:
1. Validates credentials via `Auth::attempt()`
2. Creates a Sanctum personal access token
3. Resolves the cookie name from the `Origin` header
4. Returns user data in the JSON body (no token in body)
5. Attaches the token as a `Set-Cookie` header with httpOnly flag
### Validation
The `CookieBearerToken` middleware (registered before `auth:sanctum` in the API middleware stack):
1. Checks for any of the three cookie names in the request
2. If found, sets the `Authorization: Bearer` header on the request
3. Sanctum's existing token validation processes the header normally
If an `Authorization` header is already present (e.g. from the portal token flow), the middleware skips cookie injection.
### Rotation
`POST /auth/refresh` (authenticated endpoint):
1. Revokes the current access token
2. Creates a new token
3. Returns user data with a new httpOnly cookie
4. Logs the refresh event
Clients should call this endpoint periodically (recommended: every 24 hours) to rotate tokens.
### Expiration
Tokens expire after **7 days** (configured in `config/sanctum.php`). After expiration, Sanctum rejects the token and the client receives a 401. The cookie's `Max-Age` matches the token expiration.
### Revocation
Tokens are revoked on:
- **Logout** (`POST /auth/logout`): current token deleted, cookie expired
- **Password reset**: all user tokens revoked
- **Password change**: other session tokens revoked
- **Email change verification**: all user sessions revoked
- **Token refresh**: old token replaced with new one
---
## 4. CSRF Protection
**CSRF tokens are not required.** The `SameSite=Strict` cookie attribute prevents the browser from sending the auth cookie on cross-origin requests. This means:
- A malicious site cannot forge authenticated requests because the cookie is never attached to cross-origin submissions
- `SameSite=Strict` is stricter than `Lax` — even top-level navigations from other sites will not include the cookie
Reference: [OWASP CSRF Prevention Cheat Sheet — SameSite Cookie Attribute](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#samesite-cookie-attribute)
---
## 5. Attack Surface Analysis
### XSS — Token Theft
**Mitigated.** The bearer token is stored in an `httpOnly` cookie and is never present in:
- The JSON response body
- `localStorage` or `sessionStorage`
- JS-readable cookies (`document.cookie`)
Even if an XSS vulnerability exists, the attacker cannot read the token. They can make authenticated requests from the user's browser session, but cannot exfiltrate the token for use elsewhere.
### CSRF — Cross-Site Request Forgery
**Mitigated.** `SameSite=Strict` prevents the browser from attaching the cookie to any request originating from a different site, including form submissions and top-level navigations.
### Network Interception — Token Theft
**Mitigated in production.** The `Secure` flag ensures the cookie is only sent over HTTPS connections. In development (localhost), `Secure` is disabled to allow HTTP.
### Server Compromise — Token Theft
**Partially mitigated.** Sanctum hashes tokens in the `personal_access_tokens` table using SHA-256. An attacker with database read access sees hashed tokens, not plaintext values. However, an attacker with full server access could intercept tokens in memory.
### Token Fixation
**Not applicable.** Tokens are generated server-side using cryptographically secure random values. The client never provides or influences the token value.
---
## 6. Portal Token-Based Flow (Artists / Suppliers)
This flow is separate from the httpOnly cookie system and is NOT affected by this architecture.
### How It Works
1. The portal generates a unique token per artist/supplier, stored as a SHA-256 hash in the `artists` or `production_requests` table
2. The plaintext token is sent to the person (e.g. via email link)
3. The person accesses a portal URL with the token as a query parameter or `Authorization: Bearer` header
4. `PortalTokenMiddleware` validates the hash, resolves the person and event context
5. The request proceeds with `portal_context`, `portal_person`, and `portal_event` attributes
### Security Properties
- Tokens are hashed at rest (SHA-256)
- No cookies or sessions involved — each request is independently authenticated
- Token validity is tied to event status (draft and closed events reject tokens)
- No user account required — the token IS the identity
---
## 7. Middleware Stack (Relevant Portion)
```
Request
→ CookieBearerToken (reads cookie → injects Authorization header)
→ auth:sanctum (validates bearer token)
→ Controller
```
For portal token routes:
```
Request
→ portal.token (validates portal-specific token)
→ Controller
```
---
## 8. Configuration Reference
| Setting | Location | Purpose |
|---------|----------|---------|
| `SESSION_DOMAIN` | `.env` | Cookie domain (`.crewli.app` in prod, `localhost` in dev) |
| `FRONTEND_ADMIN_URL` | `.env` / `config/app.php` | Admin SPA origin (cookie name resolution + CORS) |
| `FRONTEND_APP_URL` | `.env` / `config/app.php` | App SPA origin |
| `FRONTEND_PORTAL_URL` | `.env` / `config/app.php` | Portal SPA origin |
| `sanctum.expiration` | `config/sanctum.php` | Token TTL (7 days = 10080 minutes) |