← Java

Java · 20 / 24

Spring Security: authentication and authorization

Distinguish unauthenticated requests from authenticated users lacking the required role.

  • Large
  • Advanced
  • 90 min

Prerequisites: Spring Boot REST with validation

In this tutorial
  1. Read the domain contract
  2. Start an isolated environment
  3. Verify success and failure
  4. Make a regression visible
  5. Extend the contract
  6. Explain the solution and its limits
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

JDK 21, Maven 3.9 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-20 on Linux x86_64. Real HTTP requests check missing authentication, wrong role, allowed access and a rejected write without a CSRF token. Fixed demo credentials belong only in the local learning environment.

Authentication identifies the caller while authorization decides whether an action is allowed. This local example uses HTTP Basic and two explicitly synthetic accounts. It is not production account management. CSRF remains enabled. A write request without a CSRF token is rejected even with a valid password.

Package contents and individual files

01Read the domain contract

Authentication identifies the caller. Authorization checks what that caller may do. The filter chain applies both before the controller. Under this configuration a browser write also requires valid CSRF evidence.

src/main/java/tutorial/Application.java · javaOpen file
package tutorial;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

@org.springframework.context.annotation.Configuration
class Security {

  @org.springframework.context.annotation.Bean
  org.springframework.security.web.SecurityFilterChain filter(
    org.springframework.security.config.annotation.web.builders.HttpSecurity http
  ) throws Exception {
    return http
      .authorizeHttpRequests(a ->
        a
          .dispatcherTypeMatchers(jakarta.servlet.DispatcherType.ERROR)
          .permitAll()
          .requestMatchers("/public")
          .permitAll()
          .requestMatchers("/admin")
          .hasRole("ADMIN")
          .anyRequest()
          .authenticated()
      )
      .httpBasic(org.springframework.security.config.Customizer.withDefaults())
      .build();
  }

  @org.springframework.context.annotation.Bean
  org.springframework.security.core.userdetails.UserDetailsService users() {
    var encoder =
      org.springframework.security.crypto.factory.PasswordEncoderFactories.createDelegatingPasswordEncoder();
    return new org.springframework.security.provisioning.InMemoryUserDetailsManager(
      org.springframework.security.core.userdetails.User.withUsername("reader")
        .password(encoder.encode("local-reader"))
        .roles("USER")
        .build(),
      org.springframework.security.core.userdetails.User.withUsername("admin")
        .password(encoder.encode("local-admin"))
        .roles("ADMIN")
        .build()
    );
  }
}

@org.springframework.web.bind.annotation.RestController
class Api {

  @org.springframework.web.bind.annotation.GetMapping("/public")
  String publicPage() {
    return "public";
  }

  @org.springframework.web.bind.annotation.GetMapping("/admin")
  String admin() {
    return "admin";
  }

  @org.springframework.web.bind.annotation.PostMapping("/admin")
  String write() {
    return "changed";
  }
}

02Start an isolated environment

Java 21 is the language baseline. Maven resolves dependencies from the POM. Tests use their own data. HTTP tests start a server on a randomly assigned local port.

pom.xml · xmlOpen file
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>4.1.0</version></parent>
<groupId>learning</groupId><artifactId>tutorial</artifactId><version>1.0</version>
<properties><java.version>21</java.version></properties>
<dependencies>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
</dependencies>
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

03Verify success and failure

Real HTTP requests check missing authentication, wrong role, allowed access and a rejected write without a CSRF token. Fixed demo credentials belong only in the local learning environment.

src/test/java/tutorial/LessonTest.java · javaOpen file
package tutorial;

import static org.junit.jupiter.api.Assertions.*;

import java.net.*;
import java.net.http.*;
import java.util.Base64;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class LessonTest {

  @LocalServerPort
  int port;

  HttpResponse<String> request(String path, String credentials, String method)
    throws Exception {
    var b = HttpRequest.newBuilder(
      URI.create("http://127.0.0.1:" + port + path)
    ).method(method, HttpRequest.BodyPublishers.noBody());
    if (credentials != null) b.header(
      "Authorization",
      "Basic " +
        Base64.getEncoder().encodeToString(
          credentials.getBytes(java.nio.charset.StandardCharsets.UTF_8)
        )
    );
    return HttpClient.newHttpClient().send(
      b.build(),
      HttpResponse.BodyHandlers.ofString()
    );
  }

  @Test
  void identityAndRoleAreDifferent() throws Exception {
    assertEquals(200, request("/public", null, "GET").statusCode());
    assertEquals(401, request("/admin", null, "GET").statusCode());
    assertEquals(
      403,
      request("/admin", "reader:local-reader", "GET").statusCode()
    );
    assertEquals(
      200,
      request("/admin", "admin:local-admin", "GET").statusCode()
    );
    assertEquals(
      403,
      request("/admin", "admin:local-admin", "POST").statusCode()
    );
  }
}

Run / check

mvn test
Expected result

Real HTTP requests check missing authentication, wrong role, allowed access and a rejected write without a CSRF token. Fixed demo credentials belong only in the local learning environment.

04Make a regression visible

Change a domain expectation and rerun the test. Maven must report failure. A skipped database test is not evidence. Restore the correct expectation afterwards.

05Extend the contract

Explicitly test an incorrect password.

06Explain the solution and its limits

An incorrect password must return 401. This differs from 403 for a valid account lacking a role. Product credentials belong neither in source nor in URLs. HTTP Basic requires protected transport outside this local example. Copy solution/LessonTest.java over the test file and repeat the same verification.

Expected result

All tests pass, including the additional solution expectation.

Your exercise

Explicitly test an incorrect password.

Show the solution and explanation

An incorrect password must return 401. This differs from 403 for a valid account lacking a role. Product credentials belong neither in source nor in URLs. HTTP Basic requires protected transport outside this local example.

solution/LessonTest.java · javaOpen file
package tutorial;

import static org.junit.jupiter.api.Assertions.*;

import java.net.*;
import java.net.http.*;
import java.util.Base64;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class LessonTest {

  @LocalServerPort
  int port;

  HttpResponse<String> request(String path, String credentials, String method)
    throws Exception {
    var b = HttpRequest.newBuilder(
      URI.create("http://127.0.0.1:" + port + path)
    ).method(method, HttpRequest.BodyPublishers.noBody());
    if (credentials != null) b.header(
      "Authorization",
      "Basic " +
        Base64.getEncoder().encodeToString(
          credentials.getBytes(java.nio.charset.StandardCharsets.UTF_8)
        )
    );
    return HttpClient.newHttpClient().send(
      b.build(),
      HttpResponse.BodyHandlers.ofString()
    );
  }

  @Test
  void identityAndRoleAreDifferent() throws Exception {
    assertEquals(401, request("/admin", "reader:wrong", "GET").statusCode());
    assertEquals(200, request("/public", null, "GET").statusCode());
    assertEquals(401, request("/admin", null, "GET").statusCode());
    assertEquals(
      403,
      request("/admin", "reader:local-reader", "GET").statusCode()
    );
    assertEquals(
      200,
      request("/admin", "admin:local-admin", "GET").statusCode()
    );
    assertEquals(
      403,
      request("/admin", "admin:local-admin", "POST").statusCode()
    );
  }
}

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.