Sitemap

Member-only story

🔐 Securely Store Keycloak Tokens Using HttpOnly Cookies in Django — The Right Way to Protect Your SPA

3 min readJun 5, 2025

--

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…

--

--

Er Raj Aryan
Er Raj Aryan

Written by Er Raj Aryan

I'm a passionate Senior Software Development Engineer building fast, responsive, and scalable web applications.

No responses yet