Member-only story
đ Securely Store Keycloak Tokens Using HttpOnly Cookies in Django â The Right Way to Protect Your SPA
If youâre integrating Keycloak into your application and using it with a React frontend and a Django backend, youâre on the right track. But thereâs one mistake many developers make: storing tokens in localStorage.
Thatâs a security risk. Instead, letâs store Keycloak tokens securely using HttpOnly cookies â so theyâre safe from XSS attacks and handled only by the backend.
In this tutorial, youâll learn:
- Why
HttpOnly
cookies are better than localStorage - How to implement the OAuth2 Authorization Code flow with Django
- How to securely store and refresh tokens with Keycloak
- Full example code you can copy and run
đ§ Why Not Use localStorage
?
When you store tokens in localStorage
, any malicious JavaScript running on your page (via XSS) can access them.
If attackers can steal your tokens, they can impersonate your users.
With HttpOnly
cookies:
- Tokens are never exposed to JavaScript
- Automatically sent with every request
- Can be marked
Secure
,SameSite
, andâŚ