DEV Community

Shreya
Shreya

Posted on Edited on

Stateless Authentication in Spring Security Using JWTs

What Is Stateless Authentication?

In conventional session-based authentication, the server manages session information for each authenticated user. Stateless authentication, however, involves each request carrying the information needed to authenticate a user. This means the server doesn’t need to maintain previous request or session data.

Each request carries an unique identifier or token (such as a signed, self-contained JWT) that the server validates before granting access. This process is more independent and can be easily adopted for distributed applications. It is also well suited for REST APIs, where JWTs enable stateless authentication without requiring server-side session storage.

APIs are constant targets for unauthorized access and exposure of sensitive information. Securing them requires authentication, authorization, and token validation at every endpoint. This ensures that only authorized users can create, update, or delete resources.

How Does the Authentication Process Work?

In OAuth2 protocol, first the Resource Owner grants permission to the Client, which then requests authorized access from the Auth Server. Once approved, the Authorization Server issues JWT signature as an access token, which the Client sends to the Resource Server (API).

A typical stateless authentication flow is as follows:

  1. The user provides credentials (username and password) to the Authorization Server.
  2. The server verifies the given credentials and issues an access token for a specific period of time (depends on the type of access being granted).
  3. On every API call, the client adds the access token to the Authorization: Bearer <token> header of the request.
  4. At last, the backend (Spring Security) validates the token’s signature, expiry, and claims (scope, permissions, and roles), and then provides an authorised access to protected resources.

This allows the server to independently authenticate each request without relying on previous session data. JwtAuthenticationConverter checks the claims in JWT and maps them to a collection of GrantedAuthority objects. For that particular request, a stateless Authentication object is placed in the SecurityContext.

Setting Up Stateless Authentication in Spring Security

Spring Security has built-in support for stateless authentication. SecurityFilterChain is used to configure security rules and disable any server-side HTTP sessions (SessionCreationPolicy.STATELESS). JWT authentication components validate tokens for incoming requests. In simple steps, this can be implemented as follows:

  1. Add the Spring Security dependency and a JWT library to your project.
  2. Create a JwtService to generate and verify access tokens. Add JWT filters to run once per HTTP request.
  3. Create a SecurityFilterChain bean to set security rules. Since the backend will not store session cookies, you can disable CSRF.
  4. Use SessionCreationPolicy.STATELESS to disable session-based authentication. Authentication will rely on the JWT sent with each request.
  5. Configure a JwtDecoder to validate the token's signature, issuer, and expiration before accepting it.
  6. Use JwtAuthenticationConverter to map roles and permissions to Spring Security authorities.

JWTs for Authentication

Once the security configuration is ready, JWTs can handle authentication for incoming HTTP requests. The client sends the access token in the Authorization header (Authorization: Bearer <token>), and Spring Security validates it.

If the token is valid (and has not expired yet), the request is processed. If the token is invalid, the API throws an authentication error.

Below is a simple implementation of how to configure JWT authentication in Spring Security:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .csrf(csrf -> csrf.disable())
        .sessionManagement(session ->
            session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        )
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/public/**").permitAll()
            .anyRequest().authenticated()
        )
        .oauth2ResourceServer(oauth ->
            oauth.jwt(Customizer.withDefaults())
        );

    return http.build();
}
Enter fullscreen mode Exit fullscreen mode

This keeps the authentication stateless while allowing Spring Security to verify each incoming request with JWT.

Where to Go from Here

APIs are the gateways between applications and protected data, which is why securing them is essential. Otherwise, anyone with an API endpoint could potentially access sensitive data. This tutorial shows how to secure a Spring Boot API with OAuth2 and JWTs, so the backend validates tokens without ever touching the user credentials itself. OAuth2 and JWTs work together: OAuth2 manages delegated access and JWTs carry the verified identity and access claims.

If you’re building a Spring Boot API and have been putting off the security aspects, this tutorial is a good starting point. It is particularly relevant to Kotlin developers with basic Spring Security knowledge who want to implement stateless authentication in REST APIs. In practice, I could take the same approach of using a custom JwtAuthenticationConverter that maps and centralises roles and permissions, and then enforce them with @PreAuthorize for method-level authorization.

Top comments (0)