← Back to blog

September 24, 2026 · 11 min read

Securing Your API: Spring Security Fundamentals

Java & Spring Boot for Beginners · Part 13 of 14

  • #Java
  • #Spring Boot
  • #Beginners
  • #spring-security
  • #jwt
  • #security

Right now, anyone who can reach the task API can do anything with it. Create a task, rename it, delete every task in the database. Over the last four parts we made the API correct, persistent, strict about input and covered by tests. It still has no idea who's calling it.

This part fixes that. We'll add Spring Security to the same project, start with the simplest thing that works (HTTP Basic), move to bearer tokens (JWT), and lock down endpoints by role. At the end we'll update the tests from Part 12, because they're about to start failing.

Security has a lot of vocabulary and it's easy to get lost in it. Two words cover most of what you need today.

Authentication vs. authorization

  • Authentication answers who are you? A username and password, a token, a certificate. Something that proves identity.
  • Authorization answers what are you allowed to do? Once we know you're Ana, can Ana delete this task?

They fail differently, and HTTP has a separate status code for each. A request that couldn't be authenticated gets a 401 Unauthorized (the name is misleading; it really means "unauthenticated"). A request from someone we do know, asking for something they aren't allowed to do, gets a 403 Forbidden. Getting those two right is a small detail that makes an API much easier to use.

Two panels. On the left, 401 Unauthorized: we don't know who you are. Causes: no credentials, wrong password, expired or tampered token. Fix: log in, then retry. On the right, 403 Forbidden: we know who you are, and the answer is no. Causes: a USER calling an ADMIN-only endpoint. Fix: logging in again won't help; you need a different role.

Add the starter and watch everything lock

Add one dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Restart the app and call any endpoint:

curl -i http://localhost:8080/api/tasks
# HTTP/1.1 401

Every endpoint is now closed. Spring Boot's default is "secure everything," which is the right default. Look at the startup log and you'll find a line like Using generated security password: 3f1c.... That's a random password for a user called user, regenerated on every restart. It's there so you can poke around. Don't build on it.

To understand what just happened, you need one idea.

The filter chain, in plain terms

Before a request reaches your TaskController, it passes through a line of filters. Each filter looks at the request and either lets it continue, rejects it, or adds something to it. Spring Security adds its own group of filters to that line, called the SecurityFilterChain.

A request travels left to right. It enters the SecurityFilterChain, which contains three filters: BasicAuthenticationFilter reads the Authorization Basic header, BearerTokenAuthenticationFilter reads the Authorization Bearer header and validates the JWT, and AuthorizationFilter checks your rules against the endpoint. If authentication fails the request exits with 401; if the rules say no it exits with 403. Only requests that pass all filters reach the DispatcherServlet and then the TaskController.

The important part: all of this happens before your controller runs. A rejected request never reaches TaskController, never reaches TaskService, never touches the database. That's the point. It also explains something that surprises people: the @RestControllerAdvice from Part 11 doesn't handle 401s and 403s. The filters answer before Spring MVC gets involved. The default 401 and 403 responses have empty bodies, which is fine for now.

Your own security configuration

The defaults are a starting point. Here's a configuration that fits the task API:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(session ->
                session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.DELETE, "/api/tasks/**").hasRole("ADMIN")
                .requestMatchers("/api/tasks/**").hasAnyRole("USER", "ADMIN")
                .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults());
        return http.build();
    }
}

Read authorizeHttpRequests from the top down. The first rule that matches wins. A DELETE on a task needs ADMIN. Anything else under /api/tasks needs USER or ADMIN. Anything else at all needs a logged-in user. If you flipped the first two lines, the broad /api/tasks/** rule would match DELETE first and a plain user could delete tasks. Rule order bugs are some of the most common security bugs in real Spring apps, so put the specific rules first.

Two lines deserve an explanation, because they look like we're turning protection off:

  • STATELESS tells Spring not to create an HTTP session. Every request carries its own credentials. That's how APIs normally work, and it's what makes the token approach later on possible.
  • csrf.disable() turns off CSRF protection. CSRF is an attack where another website tricks your browser into sending a request with your cookies. It matters when authentication rides on cookies. This API doesn't use cookies at all, since credentials come in the Authorization header on every call, so the protection has nothing to protect. If you ever build a browser app with session cookies, turn it back on.

(One side effect: the H2 console from Part 10 is now behind a login too. If you still want it in development, add a permitAll() rule for /h2-console/** and allow frames for it, and make sure that rule never ships to production.)

Users, roles, and where password hashing happens

The chain needs to know who exists. For learning, an in-memory list is enough:

@Bean
PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

@Bean
UserDetailsService users(PasswordEncoder encoder) {
    UserDetails ana = User.withUsername("ana")
        .password(encoder.encode("ana-password"))
        .roles("USER")
        .build();
    UserDetails admin = User.withUsername("admin")
        .password(encoder.encode("admin-password"))
        .roles("ADMIN")
        .build();
    return new InMemoryUserDetailsManager(ana, admin);
}

Both beans go in SecurityConfig. The PasswordEncoder is where hashing happens, in both directions. When a user is created, encode() turns "ana-password" into something like {bcrypt}$2a$10$N9qo8uLO.... When Ana logs in, Spring calls matches() with the password she sent and the stored hash. The plain password is never stored and never compared directly.

The {bcrypt} prefix is there because of the delegating encoder. It records which algorithm produced each hash, so if you move to a stronger one years from now, old hashes keep working while new ones use the new algorithm. That kind of problem is hard to fix after the fact, and here you get it for free.

Two rules that aren't negotiable. Never store passwords in plain text, not even in a dev database you'll "clean up later." And never write your own hashing. BCrypt is slow on purpose, which is exactly what you want against someone trying billions of guesses. A quick SHA-256 of the password is not the same thing.

In a real application, users live in the database, not in code. You'd write a small class that implements UserDetailsService, load a User entity through a Spring Data repository (Part 10 again), and return it as UserDetails. The rest of the configuration stays the same.

Try it:

curl -u ana:ana-password http://localhost:8080/api/tasks          # 200
curl -u ana:ana-password -X DELETE http://localhost:8080/api/tasks/1  # 403
curl -u admin:admin-password -X DELETE http://localhost:8080/api/tasks/1  # 204

-u sends an Authorization: Basic ... header. That's HTTP Basic: the username and password, base64-encoded, on every single request. Base64 is an encoding, not encryption. Anyone who can read the header can read the password. Basic is acceptable over HTTPS for internal tools and scripts, and it's a good way to learn. For an API used by a frontend or a mobile app, you want something better.

From passwords to tokens: a JWT bearer flow

The idea is simple. The client sends its password once, in exchange for a token. Every request after that sends the token instead. The token expires, so a leaked one stops working on its own, and the password stays off the wire for everything else.

A sequence between a client and the task API. Step 1: the client sends POST /api/auth/token with Basic credentials. Step 2: the API checks the password hash and returns a signed JWT containing the subject ana, the roles, and an expiry one hour out. Step 3: the client calls GET /api/tasks with Authorization Bearer and the token. Step 4: the API verifies the signature and expiry, with no database lookup and no session, and returns 200.

A JWT (JSON Web Token) is three base64 chunks separated by dots: a header, a payload with claims like sub: "ana" and exp: ..., and a signature. The server signs the token with a secret key. Later, it can check the signature and know the token hasn't been changed, without looking anything up. The payload is readable by anyone, though, so never put anything secret in it.

Spring Security already knows how to validate JWTs. Add the resource server starter:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

Then give the app a key to sign and verify with. For a single service, a shared secret (HMAC) keeps things simple:

jwt:
  secret: ${JWT_SECRET:dev-only-secret-change-me-it-must-be-32-bytes+}
@Bean
JwtEncoder jwtEncoder(@Value("${jwt.secret}") String secret) {
    return new NimbusJwtEncoder(new ImmutableSecret<>(secret.getBytes()));
}

@Bean
JwtDecoder jwtDecoder(@Value("${jwt.secret}") String secret) {
    var key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
    return NimbusJwtDecoder.withSecretKey(key).build();
}

The secret needs at least 32 bytes for HS256. The default after the colon is for your laptop only. In Part 14 we'll read the real value from an environment variable, where secrets belong. For the production side of that (secret managers, and failing fast when a value is missing), see Spring Boot Configuration: Profiles, Properties, and Secrets.

Now an endpoint that hands out tokens. It's protected by Basic, so reaching it at all means the password was right:

@RestController
public class TokenController {

    private final JwtEncoder encoder;

    public TokenController(JwtEncoder encoder) {
        this.encoder = encoder;
    }

    @PostMapping("/api/auth/token")
    public Map<String, String> token(Authentication authentication) {
        Instant now = Instant.now();
        List<String> roles = authentication.getAuthorities().stream()
            .map(GrantedAuthority::getAuthority)
            .toList();

        JwtClaimsSet claims = JwtClaimsSet.builder()
            .issuer("task-api")
            .subject(authentication.getName())
            .issuedAt(now)
            .expiresAt(now.plus(1, ChronoUnit.HOURS))
            .claim("roles", roles)
            .build();

        var header = JwsHeader.with(MacAlgorithm.HS256).build();
        String token = encoder.encode(JwtEncoderParameters.from(header, claims))
            .getTokenValue();
        return Map.of("token", token);
    }
}

The last step is telling the chain to accept bearer tokens, and to read our roles claim so hasRole("ADMIN") keeps working. Add this to the chain, next to httpBasic:

.oauth2ResourceServer(oauth -> oauth.jwt(jwt ->
    jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())))
private JwtAuthenticationConverter jwtAuthenticationConverter() {
    var authorities = new JwtGrantedAuthoritiesConverter();
    authorities.setAuthoritiesClaimName("roles");
    authorities.setAuthorityPrefix(""); // values are already "ROLE_USER"
    var converter = new JwtAuthenticationConverter();
    converter.setJwtGrantedAuthoritiesConverter(authorities);
    return converter;
}

Without that converter, Spring looks for a scope claim and prefixes everything with SCOPE_. Your role rules would then quietly reject every token. It's an easy one to lose an afternoon on.

Try the whole flow:

TOKEN=$(curl -s -u ana:ana-password -X POST \
  http://localhost:8080/api/auth/token | jq -r .token)

curl -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/tasks   # 200

Paste the token into a JWT decoder and you'll see Ana's name, her role and the expiry in plain JSON. Change one character and the API answers 401.

One honest caveat. Issuing your own tokens like this is a good way to learn how they work, and it's fine for a small service. Bigger systems usually hand this job to a dedicated identity provider (Keycloak, Auth0, Cognito, Okta) and the API only validates tokens. The nice part is that your SecurityConfig barely changes when you make that switch. You'd point the decoder at the provider instead of a local secret.

Testing secured endpoints

Run the Part 12 tests now and the controller slice goes red with 401s. That's correct. The tests are calling a secured API without logging in.

Add the test support library:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

Then import your real security config into the slice, so the tests run your rules and not Boot's defaults, and pretend to be a user:

@WebMvcTest(TaskController.class)
@Import(SecurityConfig.class)
class TaskControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockitoBean
    private TaskService taskService;

    @Test
    void listTasks_returns401_withoutCredentials() throws Exception {
        mockMvc.perform(get("/api/tasks"))
            .andExpect(status().isUnauthorized());
    }

    @Test
    @WithMockUser(roles = "USER")
    void deleteTask_returns403_forPlainUser() throws Exception {
        mockMvc.perform(delete("/api/tasks/1"))
            .andExpect(status().isForbidden());

        verifyNoInteractions(taskService);
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void deleteTask_isAllowed_forAdmin() throws Exception {
        when(taskService.delete(1L)).thenReturn(true);

        mockMvc.perform(delete("/api/tasks/1"))
            .andExpect(status().isNoContent());
    }
}

@WithMockUser puts a fake, already-authenticated user in place for that test. Put it on the class to cover the older tests in one go. The verifyNoInteractions trick from Part 12 works here too: it proves the forbidden request never reached the service.

To test the token path specifically, use the jwt() request post-processor: mockMvc.perform(get("/api/tasks").with(jwt())). For the full-stack integration test, send real credentials with .with(httpBasic("ana", "ana-password")). Keep at least one test per rule that should say no. A missing 403 test is how a role rule gets deleted in a refactor and nobody notices.

What's next

The API now knows who's calling, decides what each caller can do, stores passwords safely and issues short-lived tokens. That covers the basics every backend needs. It isn't everything, though. Refresh tokens, rate limiting and a proper identity provider are the obvious next steps, and they belong to a real product more than to a tutorial.

There's one step left in the series. The app has only ever run on your machine. Part 14: Packaging and Running Your App builds it into a single jar, puts it in a Docker image, moves that JWT secret into real configuration, and deploys it somewhere other people can reach it.