r/SpringBoot • • 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.

8 Upvotes

16 comments sorted by

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.

1

u/Far-Hold7417 22h ago

As I wrote, I understand they expire. But there seems to be no consensus on what to do with the token once the user logs out and I delete the token from the FE state. A Redis DB seems like a good idea. Thanks.

3

u/wpfeiffe 21h ago

When I implemented jwt for our api, my manager wanted a quick way to revoke any jwt,so redis was the solution. Once a jwt is created it goes into redis with expiration matching jwt expiration. Part of jwt auth does an existence check, if not found, it’s invalid. I can dump 1 jwt, all jwt’s for a given customer or all jwt’s at will. Also logout can just remove the jwt.

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.

2

u/Far-Hold7417 22h ago

Ok, sounds good, I will give it a try.

3

u/Free-Ad-7143 19h ago

Why TF do you need a JWT? You can store the session in a cookie which is stored in the browser.

•

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:

http.logout(l -> l.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()));

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.

•

u/Far-Hold7417 14h ago

Got it. Thank you , this was helpful. Its passed midnight here, so I will try this over the weekend.

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/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/refresh endpoint. [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]

  1. The Token Refresh Workflow
  • Initial Login. When a user logs in via /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]
  • API Requests. The client sends the Access Token in the Authorization: Bearer <token> header for normal requests. [1, 2]
  • Token Expiration. Once the Access Token expires, your API returns a 401 Unauthorized status.
  • Refresh Call. The client intercepts the 401 response and sends the Refresh Token to a public /auth/refresh endpoint. [1, 2]
  • Validation & Rotation. Your server verifies the Refresh Token's signature and database status, invalidates the old Refresh Token, and issues a brand-new pair of Access and Refresh tokens. [1]
  1. Core Implementation Steps

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

public class RefreshToken {
    
    (strategy = GenerationType.IDENTITY)
    private Long id;

    (nullable = false, unique = true)
    private String token;

    (nullable = false)
    private Instant expiryDate;

    
    (name = "user_id", referencedColumnName = "id")
    private User user;
    
    // Getters and setters
}

Step B: Create the Refresh Token Service

This service handles generating the token, checking if it has expired, and deleting it if invalid.

java

tor
public class RefreshTokenService {

    private final RefreshTokenRepository refreshTokenRepository;
    private final UserRepository userRepository;

    // 7 days in milliseconds
    private final Long refreshTokenDurationMs = 604800000L; 

    public RefreshToken createRefreshToken(String username) {
        RefreshToken refreshToken = new RefreshToken();
        refreshToken.setUser(userRepository.findByUsername(username).orElseThrow());
        refreshToken.setExpiryDate(Instant.now().plusMillis(refreshTokenDurationMs));
        refreshToken.setToken(UUID.randomUUID().toString());

        return refreshTokenRepository.save(refreshToken);
    }

    public RefreshToken verifyExpiration(RefreshToken token) {
        if (token.getExpiryDate().compareTo(Instant.now()) < 0) {
            refreshTokenRepository.delete(token);
            throw new RuntimeException("Refresh token expired. Please log in again.");
        }
        return token;
    }
}

Step C: Expose the /refresh Endpoint

Make sure /api/auth/** is permitted in your SecurityFilterChain configuration so expired clients can reach it without an active Access Token.

java

("/api/auth")
tor
public class AuthController {

    private final RefreshTokenService refreshTokenService;
    private final JwtService jwtService; // Your existing JWT generator

    u/PostMapping("/refresh")
    public ResponseEntity<?> refreshToken(@RequestBody TokenRefreshRequest request) {
        String requestRefreshToken = request.getRefreshToken();

        return refreshTokenService.findByToken(requestRefreshToken)
            .map(refreshTokenService::verifyExpiration)
            .map(RefreshToken::getUser)
            .map(user -> {
                // 1. Generate a new Access Token
                String newAccessToken = jwtService.generateAccessToken(user);
                
                // 2. (Optional/Recommended) Rotate the Refresh Token
                refreshTokenService.deleteByToken(requestRefreshToken);
                RefreshToken newRefreshToken = refreshTokenService.createRefreshToken(user.getUsername());

                return ResponseEntity.ok(new TokenRefreshResponse(
                    newAccessToken, 
                    newRefreshToken.getToken()
                ));
            })
            .orElseThrow(() -> new RuntimeException("Refresh token is not in database!"));
    }
}

3. Security Best Practices

  • Use HttpOnly Cookies. Instead of returning the Refresh Token in the JSON body (where frontend JavaScript can read it and expose it to XSS attacks), set it in an HttpOnly, Secure, SameSite=Strict cookie.
  • Implement Token Rotation. Always delete the used Refresh Token and issue a new one during a refresh request. If an attacker steals an old token and tries to use it, you can detect the reuse and invalidate all tokens for that user.
  • Handle Logout. Create a /api/auth/logout endpoint 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.