Spring Boot
Bearer Authentication
Security
Java
API Authorization

How to enable Bearer authentication on Spring Boot application?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Enabling bearer authentication in Spring Boot usually means teaching Spring Security to accept an Authorization: Bearer ... header, validate the token, and attach an authenticated principal to the request. The cleanest implementation depends on whether your application validates JWTs directly or uses a custom token format.

For modern Spring Boot applications, the most common solution is a stateless API secured with Spring Security and JWT bearer tokens. Spring can do most of the work for you if you configure the application as a resource server.

Add The Security Dependencies

For JWT-based bearer authentication, a typical Maven setup includes web, security, and OAuth2 resource server support.

xml
1<dependencies>
2    <dependency>
3        <groupId>org.springframework.boot</groupId>
4        <artifactId>spring-boot-starter-web</artifactId>
5    </dependency>
6    <dependency>
7        <groupId>org.springframework.boot</groupId>
8        <artifactId>spring-boot-starter-security</artifactId>
9    </dependency>
10    <dependency>
11        <groupId>org.springframework.boot</groupId>
12        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
13    </dependency>
14</dependencies>

That gives you the infrastructure for decoding and validating bearer tokens without writing a custom servlet filter from scratch.

Configure A Stateless Security Filter Chain

In Spring Security 6, security is usually configured with a SecurityFilterChain bean.

java
1import org.springframework.context.annotation.Bean;
2import org.springframework.context.annotation.Configuration;
3import org.springframework.security.config.Customizer;
4import org.springframework.security.config.annotation.web.builders.HttpSecurity;
5import org.springframework.security.config.http.SessionCreationPolicy;
6import org.springframework.security.web.SecurityFilterChain;
7
8@Configuration
9public class SecurityConfig {
10
11    @Bean
12    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
13        return http
14            .csrf(csrf -> csrf.disable())
15            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
16            .authorizeHttpRequests(auth -> auth
17                .requestMatchers("/public/**").permitAll()
18                .anyRequest().authenticated()
19            )
20            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
21            .build();
22    }
23}

The important parts are the stateless session policy and the resource-server JWT configuration. That tells Spring to read bearer tokens from the Authorization header and validate them for protected endpoints.

Configure JWT Validation

If you validate tokens signed by an authorization server, point Spring at the issuer or JWK set.

yaml
1spring:
2  security:
3    oauth2:
4      resourceserver:
5        jwt:
6          issuer-uri: https://auth.example.com/realms/app

Spring will fetch the signing metadata and validate incoming JWTs automatically. That is the standard production setup when tokens come from an identity provider such as Keycloak, Auth0, or another OpenID Connect server.

A Protected Controller Example

Once security is enabled, protected endpoints require a valid bearer token.

java
1import org.springframework.web.bind.annotation.GetMapping;
2import org.springframework.web.bind.annotation.RestController;
3
4@RestController
5public class ProfileController {
6
7    @GetMapping("/public/health")
8    public String health() {
9        return "ok";
10    }
11
12    @GetMapping("/api/profile")
13    public String profile() {
14        return "secured profile";
15    }
16}

A request without a bearer token to /api/profile will receive 401 Unauthorized. A request with a valid token will pass.

Testing With curl

You can test the protected route like this:

bash
curl http://localhost:8080/api/profile

That should fail with 401. Then try again with a token:

bash
curl -H "Authorization: Bearer eyJ..." http://localhost:8080/api/profile

If token validation succeeds, the endpoint responds normally.

What If You Use Custom Tokens

Not every system uses JWT. If your application stores opaque bearer tokens in a database or cache, you usually implement a custom OncePerRequestFilter that extracts the header, looks up the token, and creates an Authentication object.

That works, but it is more code and more security responsibility. If you can use standard JWT validation through the resource server support, that is usually the better default.

Common Pitfalls

  • Enabling Spring Security without making the application stateless.
  • Expecting bearer authentication to work before configuring token validation.
  • Forgetting to permit public endpoints such as health or login paths.
  • Using a custom token filter when the built-in resource server support would be enough.
  • Sending the token in the wrong header instead of Authorization: Bearer ....

Summary

  • Bearer authentication in Spring Boot is usually implemented with Spring Security and a stateless filter chain.
  • For JWTs, spring-boot-starter-oauth2-resource-server is the standard approach.
  • Configure token validation with an issuer URI or JWK set.
  • Protected endpoints then automatically require Authorization: Bearer ....
  • Use a custom filter only when your tokens are not standard JWTs.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.