Spring Security | JWT

Cookie-based JWT Authentication with Spring Security

Zeeshan Adil
JavaToDev
12 min readNov 9, 2023

--

In my recent projects, I’ve consistently utilized JWT as an authentication token. However, a recurring question arises: what is the optimal storage location for server-side issued JWTs? While discussions typically focus on the browser scenario, considering three available options.

1. Cookies

The server can transmit the JWT token to the browser via a cookie, and upon requesting the server-side interface, the browser automatically includes the JWT token in the cookie header. Authentication is then achieved by the server verifying the JWT token in the cookie header. However, this approach is susceptible to CSRF attacks.

To mitigate this vulnerability, a solution involves configuring the SameSite property of the cookie to Strict. This means the cookie will only be transmitted if the current page’s URL matches the request target.

While cookies address CSRF concerns, they are still exposed to XSS attacks. Malicious actors can extract information from cookies using JavaScript scripts. To bolster security, the cookie property can be set to HttpOnly, preventing unauthorized access via client-side scripts.

2. localStorage

--

--

Zeeshan Adil
JavaToDev

Full Stack Developer || Educator || Technical Blogger 🧑‍💻Let's Connect : https://www.linkedin.com/in/zeeshan-adil-a94b3867/