Sub topic 1
Authentication and Authorization in Spring Security
Prerequisites
Assume you know Spring Boot REST controllers, Java annotations and lambdas, dependency injection, HTTP status codes, and the basic idea of passwords and tokens. Examples use Spring Security 6 style configuration.
Authentication and authorization
Authentication answers, “Who is making this request?” Spring Security authenticates credentials such as a username and password or a JWT bearer token.
Authorization answers, “What may this authenticated identity do?” Rules can require a role, an authority, or simply a valid identity. Authentication usually happens before authorization.
Request flow through the filter chain
Spring Security protects servlet requests with an ordered filter chain. Each filter can inspect the request, authenticate credentials, create a security context, or reject the request. After the chain authorizes the request, Spring MVC invokes the controller.
A missing or invalid identity commonly produces 401 Unauthorized. An authenticated identity without sufficient permission produces 403 Forbidden.
Defining a `SecurityFilterChain` bean
A SecurityFilterChain bean declares the HTTP security policy. This stateless example permits public paths, requires a role for order reads, and requires authentication elsewhere.
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(
SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/orders/**")
.hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}For a browser session or cookie-based authentication, do not disable CSRF without analyzing the threat model. A token sent in an authorization header is generally not sent automatically by a browser, so stateless APIs commonly disable CSRF.
Authentication flow and `SecurityContext`
An authentication filter passes credentials to an AuthenticationManager. The manager delegates to an AuthenticationProvider, which verifies the credentials. On success, Spring stores the resulting Authentication object in the SecurityContext for the request. Authorization rules and application code can then read the authenticated principal and authorities.
Exercise
A valid JWT reaches an endpoint but lacks the required authority. Should the response normally be 401 or 403?
Show answer
403, because the request is authenticated but not authorized.