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:
ajurna committed 2026-10-13 13:38:48 +01:00
1 parent a7e9bd0743
commit 79c0647cc4
11 files changed
+369 -170

No files matched your search

+66
View File
@@ -0,0 +1,66 @@
"""Cookie based JWT authentication.
Tokens are kept in HttpOnly cookies rather than in JavaScript storage. That is
what makes browser initiated requests work: an `<img>` tag cannot send an
`Authorization` header, so protected page images can only be served through
cookie authentication.
The views live in comic/auth_views.py: importing rest_framework.views here would
resolve DEFAULT_AUTHENTICATION_CLASSES while this module is still being imported.
"""
from typing import Any
from django.conf import settings
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework_simplejwt.authentication import AUTH_HEADER_TYPES, JWTAuthentication
def access_cookie_name() -> str:
return settings.JWT_ACCESS_COOKIE_NAME
def refresh_cookie_name() -> str:
return settings.JWT_REFRESH_COOKIE_NAME
def _cookie_options() -> dict[str, Any]:
return {
'httponly': True,
'secure': settings.JWT_COOKIE_SECURE,
'samesite': settings.JWT_COOKIE_SAMESITE,
'path': settings.JWT_COOKIE_PATH,
}
def set_auth_cookies(response: Response, tokens: dict[str, Any]) -> None:
"""Write the access and refresh tokens into HttpOnly cookies."""
simple_jwt = settings.SIMPLE_JWT
for name, token, lifetime in (
(access_cookie_name(), tokens.get('access'), simple_jwt['ACCESS_TOKEN_LIFETIME']),
(refresh_cookie_name(), tokens.get('refresh'), simple_jwt['REFRESH_TOKEN_LIFETIME']),
):
if token:
response.set_cookie(name, token, max_age=int(lifetime.total_seconds()), **_cookie_options())
def clear_auth_cookies(response: Response) -> None:
for name in (access_cookie_name(), refresh_cookie_name()):
response.delete_cookie(name, path=settings.JWT_COOKIE_PATH)
class CookieJWTAuthentication(JWTAuthentication):
"""Authenticate from the Authorization header, or from the access cookie.
Keeping the header path means API clients that send a bearer token still work.
"""
def get_header(self, request: Request) -> bytes | None:
header = super().get_header(request)
if header:
return header
token = request.COOKIES.get(access_cookie_name())
if not token:
return None
return f'{AUTH_HEADER_TYPES[0]} {token}'.encode()
+72
View File
@@ -0,0 +1,72 @@
"""Token views that store JWTs in HttpOnly cookies (see comic/auth.py)."""
from rest_framework import status
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework_simplejwt.exceptions import TokenError
from rest_framework_simplejwt.serializers import TokenBlacklistSerializer, TokenRefreshSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
from comic.auth import clear_auth_cookies, refresh_cookie_name, set_auth_cookies
def _refresh_value(request: Request) -> str | None:
"""The refresh token from the request body, or from the refresh cookie."""
value = request.data.get('refresh') if isinstance(request.data, dict) else None
return value or request.COOKIES.get(refresh_cookie_name())
class CookieTokenObtainPairView(TokenObtainPairView):
"""Log in: issue tokens and store them in HttpOnly cookies."""
def post(self, request: Request, *args: object, **kwargs: object) -> Response:
response = super().post(request, *args, **kwargs)
if response.status_code == status.HTTP_200_OK and isinstance(response.data, dict):
set_auth_cookies(response, response.data)
# The tokens live in HttpOnly cookies, so they are not returned to JavaScript.
response.data = {}
return response
class CookieTokenRefreshView(TokenObtainPairView):
"""Refresh using the refresh cookie and update both cookies."""
serializer_class = TokenRefreshSerializer
def post(self, request: Request, *args: object, **kwargs: object) -> Response:
refresh = _refresh_value(request)
if not refresh:
return Response(status=status.HTTP_401_UNAUTHORIZED, data={'errors': 'No refresh token.'})
serializer = self.get_serializer(data={'refresh': refresh})
try:
serializer.is_valid(raise_exception=True)
except TokenError as exc:
raise AuthenticationFailed(exc.args[0]) from exc
response = Response(status=status.HTTP_200_OK)
set_auth_cookies(response, serializer.validated_data)
# Keep the cookies out of the body so JavaScript never sees the tokens.
return response
class CookieTokenBlacklistView(TokenObtainPairView):
"""Log out: blacklist the refresh cookie and clear both cookies."""
serializer_class = TokenBlacklistSerializer
def post(self, request: Request, *args: object, **kwargs: object) -> Response:
refresh = _refresh_value(request)
if not refresh:
return Response(status=status.HTTP_401_UNAUTHORIZED, data={'errors': 'No refresh token.'})
serializer = self.get_serializer(data={'refresh': refresh})
try:
serializer.is_valid(raise_exception=True)
except TokenError as exc:
raise AuthenticationFailed(exc.args[0]) from exc
response = Response(status=status.HTTP_204_NO_CONTENT)
clear_auth_cookies(response)
return response
+87
View File
@@ -0,0 +1,87 @@
"""Tests for cookie based JWT authentication."""
import json
import pytest
from django.test import Client
from comic import auth
CREDENTIALS = {'username': 'reader', 'password': 'password12345'}
def _store_cookies(client: Client, response) -> None:
"""Copy Set-Cookie headers into the test client, which does not do it itself."""
for name, morsel in response.cookies.items():
if morsel.value:
client.cookies[name] = morsel.value
elif name in client.cookies:
del client.cookies[name]
@pytest.mark.django_db
def test_login_sets_http_only_cookies(client: Client, reader_user) -> None:
response = client.post('/api/token/', CREDENTIALS)
assert response.status_code == 200
# The tokens are not returned to JavaScript, only stored as cookies.
assert json.loads(response.content) == {}
for name in (auth.access_cookie_name(), auth.refresh_cookie_name()):
assert response.cookies[name].value
assert response.cookies[name]['httponly']
@pytest.mark.django_db
def test_a_cookie_authenticates_a_request(client: Client, reader_user) -> None:
_store_cookies(client, client.post('/api/token/', CREDENTIALS))
response = client.get('/api/account/')
assert response.status_code == 200
assert json.loads(response.content)['username'] == reader_user.username
@pytest.mark.django_db
def test_anonymous_request_without_a_cookie_is_rejected(client: Client) -> None:
assert client.get('/api/account/').status_code == 401
@pytest.mark.django_db
def test_the_authorization_header_still_works(client: Client, reader_user) -> None:
response = client.post('/api/token/', CREDENTIALS)
token = response.cookies[auth.access_cookie_name()].value
response = client.get('/api/account/', headers={'Authorization': f'Bearer {token}'})
assert response.status_code == 200
@pytest.mark.django_db
def test_refresh_rotates_the_access_cookie(client: Client, reader_user) -> None:
_store_cookies(client, client.post('/api/token/', CREDENTIALS))
old_access = client.cookies[auth.access_cookie_name()].value
old_refresh = client.cookies[auth.refresh_cookie_name()].value
response = client.post('/api/token/refresh/', {})
assert response.status_code == 200
_store_cookies(client, response)
assert client.cookies[auth.access_cookie_name()].value != old_access
assert client.cookies[auth.refresh_cookie_name()].value != old_refresh
# The rotated refresh token is blacklisted, so the original one no longer works.
assert client.post('/api/token/refresh/', {'refresh': old_refresh}).status_code == 401
@pytest.mark.django_db
def test_blacklisting_clears_the_cookies(client: Client, reader_user) -> None:
_store_cookies(client, client.post('/api/token/', CREDENTIALS))
response = client.post('/api/token/blacklist/', {})
assert response.status_code == 204
_store_cookies(client, response)
for name in (auth.access_cookie_name(), auth.refresh_cookie_name()):
assert name not in client.cookies
assert client.get('/api/account/').status_code == 401
@pytest.mark.django_db
def test_page_images_can_be_loaded_with_a_cookie(client: Client, book, reader_user) -> None:
"""Browser initiated requests cannot send a header, so they rely on the cookie."""
_store_cookies(client, client.post('/api/token/', CREDENTIALS))
assert client.get(f'/api/read/{book.selector}/image/1/').status_code == 200