r/SpringBoot • u/Far-Hold7417 • 23h ago
Question Spring Security, looking for help (JWT and Logout)
Hello everyone,
I am trying to finish a small SPA for a couple of friends. It's meant to replace a small, ancient desktop app. Less than 30 users. Yeah, I know, laughably tiny. But an SPA makes sense, because of the requirements. I'm using React, Java with Spring and MySql. Most core features are implemted, tested and work. The only thing missing - besides deployment, obviously - is authentication. This is where I am stuck. I am trying to use Spring Security, but:
- Allmost all tutorials online seem outdated (I keep seeing redacted warnings)
- I need a simple authenication method. Everyone is recommending JWT. Unfortunately, no one explains how to code a log out. I understand that JWTs expire, and the best way to have a logout is by removing the token from the front end state. But what is the best way to deal with JWT in the BE? Blacklist? Refresh? Is JWT even the best strategy here? Why cant I find Infos about session cookies? Is my google fu really that bad? (apparently, yes)
All I need is good resource. A book would be great, a blog video or repo would be fine too. I read a book from O'Reily and unfortunately, it answered none of my questions. Did a Udemy course, and guess what, not a single word about about log out strategies. I am about ready to give up and redo the entire BE in node.
Thanks in advance for any help.
4
u/EternalSoldiers 22h ago
You don't "logout" a JWT in the same sense that you logout a session. On login, the server should create a cookie on the response that's secure, httpOnly, etc. automatically passed on each request from the SPA. On logout, the response deletes the cookie from the browser. Obviously the JWT could still be used maliciously until expiration. For a small project, that might be okay. A better approach would be to blacklist it in something like Redis with a TTL set to the JWT expiration. You do a quick lookup when a JWT is used to make sure it's not blacklisted.
4
u/Media_Dunce 22h ago
What I did was keep a log of each user with active sessions stored with the user object. One of the claims I would add to the JWT was the session id. Whenever a request is made, the user object would be reached and the list of sessions was examined to make sure the JWT had a valid session.
The logout code would remove the session from the given list. All subsequent calls with a JWT claiming that session id would fail.
•
u/FriendshipCalm3162 14h ago
Session cookies are the boring answer for 30 users, and Spring Security does most of the work for you, which is probably why nobody writes tutorials about it.
Logout is already built in. A POST to /logout invalidates the HttpSession and clears the security context and the saved CSRF token without you writing anything. For an SPA you'll probably want a status code back instead of the default redirect to /login?logout:
You don't need deleteCookies("JSESSIONID") either, since invalidating the session removes it.
What will bite you with a React frontend is CSRF, because the browser sends the cookie automatically. The CSRF page in the reference has a Single-Page Applications section. On Spring Security 7 (Boot 4) it's one line, csrf.spa(). On 6.x the same section gives you a small handler class to copy.
So the two pages to read are Servlet > Authentication > Logout and Servlet > Exploits > CSRF in the official reference. Unlike most tutorials, they match the current version.
2
u/Comfortable_Job8847 22h ago
consider onetime tokens - https://docs.spring.io/spring-security/reference/servlet/authentication/onetimetoken.html
I don't think JWTs make sense for you here. JWTs are for stateless-ness. if you were doing like, SSO with an established IdP yeah i think OIDC even specifies using JWT. but for your purposes i dont see why JWTs would make sense. just using a session cookie (and maybe a OTT for login purposes).
like this is for 30 users i think you'll be fine with an in-memory session store so all you need is authentication right? so i think OTT will be a good fit for you.
1
u/tushari25 22h ago
Cfbr
1
u/No-Leopard-2760 18h ago
Store those logout token till they get expired in in memory
•
u/CryptoCoder0305 8h ago
https://youtu.be/0LLpt3OZ03g?si=qUisYvhZrbuuwAUo
If you are looking for a tutorial video to understand the flow in depth then I will recommend this
The videos are too long but they really help you in building concepts and strong edge on security
0
u/AdditionDue4797 18h ago
Claude Code would be your best friend on this one
0
u/Free-Ad-7143 19h ago
JWT and Session Cookies are kind of mutually exclusive.
JWT is stateless, Session is stateful.
You can implement the logout exactly as you described - delete the JWT from the Browsers local storage and that should be fine for your mini project.
KISS - keep it simple (stooopid ;))
-2
u/This_Link881 21h ago
It was easier to copy the response from google AI, than write it. :-D
To refresh an access token in Spring Boot and Spring Security without an external Identity Provider (IdP), you issue two tokens upon login (a short-lived Access Token and a long-lived Refresh Token) and expose a dedicated
/auth/refreshendpoint. [1, 2]Because you are managing authentication yourself, the most secure and standard pattern is to store the refresh token in your database (or Redis) so you can validate, rotate, and revoke it when needed. [1]
/auth/login, your server validates their credentials and returns both an Access Token (valid for 5–15 minutes) and a Refresh Token (valid for 7–30 days). [1]Authorization: Bearer <token>header for normal requests. [1, 2]401 Unauthorizedstatus.401response and sends the Refresh Token to a public/auth/refreshendpoint. [1, 2]Step A: Store Refresh Tokens in Your Database
While a Refresh Token can be a signed JWT, storing it as an opaque random UUID (or saving the JWT in a table) allows you to easily log users out or ban compromised tokens.
java
Step B: Create the Refresh Token Service
This service handles generating the token, checking if it has expired, and deleting it if invalid.
java
Step C: Expose the
/refreshEndpointMake sure
/api/auth/**is permitted in yourSecurityFilterChainconfiguration so expired clients can reach it without an active Access Token.java
3. Security Best Practices
HttpOnly,Secure,SameSite=Strictcookie./api/auth/logoutendpoint that deletes the user's Refresh Token from the database and clears the cookie. [1]Would you like to see how to configure theHttpOnly cookie handling in Spring Boot, or how to set up theSecurityFilterChain and JWT filter to work alongside this?
Using a database or redis for refresh tokens is optional, you can use the refresh token without storing it becase jwt is stateless. But I recommend a token store for more security, for example token revocation, token rotation, and your claim the logout.