The first time I added login to a Spring Boot and React app, I tried to force session cookies through CORS and spent two days debugging. The cleaner answer is JWT: the server hands the client a signed token at login, and the client attaches it to every request. Here is the whole flow, end to end, in the smallest version that actually works.

Key takeaways

  • JWT authentication: the server issues a signed token at login, and the client attaches it as an Authorization header on every request instead of relying on session cookies.
  • A Spring Security filter verifies the token on each request, so no server-side session storage is needed.
  • Store tokens in memory (React state or context), not localStorage: any script on the page can read localStorage, so one cross-site scripting hole leaks every token.
  • Set tokens to expire, with fifteen minutes as a common starting point; a token that lives forever is a stolen credential that works forever.
  • When the backend starts answering 401, send the user back to login; refresh tokens can later rotate credentials silently without another login.

What a JWT is

A JSON Web Token is three Base64 parts joined by dots: a header, a payload, and a signature. The payload carries claims like the username and an expiry time. The signature is created with a secret that only your server knows, so the server can verify the token is genuine without storing it anywhere. A token is signed, not encrypted: anyone can read the payload, so never put secrets in it. What makes it safe is that nobody can forge the signature without your secret.

The login flow

The flow has four steps and it never changes: the React app posts the username and password to a public login endpoint. The backend checks the password, and if it matches, generates a token and sends it back. React stores the token in memory. From then on, every API call carries the token in the Authorization: Bearer <token> header, and a filter on the backend validates it before the request reaches your controller. No sessions, nothing stored server-side, which is exactly why JWT fits APIs that serve a React frontend.

Configure Spring Security

Spring Security blocks everything by default, so the first job is to open the login endpoint, close everything else, and make the API stateless. A SecurityFilterChain bean does all three:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .csrf(csrf -> csrf.disable())
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/auth/**").permitAll()
            .anyRequest().authenticated())
        .sessionManagement(session ->
            session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    return http.build();
}

Disabling CSRF is correct here because the API has no sessions for CSRF to attack; the token itself is the protection. Stateless sessions keep Spring from creating a session per user, which is what makes the API genuinely token-based.

The login endpoint

The login endpoint authenticates the credentials with the AuthenticationManager, then issues a token through your token service. Passwords must be stored hashed, never plain text, so register a BCryptPasswordEncoder bean and use it when creating users:

@PostMapping("/login")
public ResponseEntity<AuthResponse> login(
        @RequestBody LoginRequest req) {
    Authentication auth = authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(
            req.getUsername(), req.getPassword()));
    String token = jwtService.generateToken(auth.getName());
    return ResponseEntity.ok(new AuthResponse(token));
}

If the credentials are wrong, the authentication manager throws and the client gets a 401. Only correct credentials ever receive a token.

The filter that checks the token

A filter that extends OncePerRequestFilter runs before every protected request, pulls the token out of the header, and validates it:

@Override
protected void doFilterInternal(HttpServletRequest request,
        HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    String header = request.getHeader("Authorization");
    if (header != null && header.startsWith("Bearer ")) {
        String token = header.substring(7);
        if (jwtService.isValid(token)) {
            String username = jwtService.extractUsername(token);
            UsernamePasswordAuthenticationToken auth =
                new UsernamePasswordAuthenticationToken(
                    username, null, List.of());
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
    }
    chain.doFilter(request, response);
}

When the token is valid, the filter places an authentication object into the security context and the request proceeds. When it is missing or invalid, the request reaches your endpoint unauthenticated and Spring Security answers with 403.

The React side

On the frontend, login is a plain POST. Store the token in React state, not anywhere else, and attach it to every subsequent request:

// login
const response = await fetch("http://localhost:8080/api/auth/login", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ username, password }),
});
const { token } = await response.json();
setToken(token);

// every later request
const rooms = await fetch("http://localhost:8080/api/rooms", {
  headers: { Authorization: "Bearer " + token },
});

If you already use axios, an interceptor that adds the header automatically is cleaner than repeating it on every call.

Where to store the token

Beginners usually reach for localStorage, and most tutorials do too, but it is the weak choice: any script running on your page can read it, so a single cross-site scripting hole leaks every token. In-memory storage, a React state value or a context, disappears on page refresh, which sounds like a downside but is actually the security property you want. The trade-off is real, users log in again after refresh, which is why production apps add short-lived access tokens plus refresh tokens. For a first project, memory storage plus a sensible expiry is the honest baseline.

Token expiry is a feature, not a bug

Set tokens to expire. A token that lives forever is a stolen credential that works forever. Generate tokens with a short lifetime, fifteen minutes is a common starting point, and have the frontend send the user back to login when the backend starts answering 401. When that flow feels natural, you are ready for the next step: refresh tokens, which rotate credentials silently without another login screen.