For the latest stable version, please use Spring Security 6.4.1!spring-doc.cn

Basic Authentication

This section provides details on how Spring Security provides support for Basic HTTP Authentication for servlet based applications.spring-doc.cn

Let’s take a look at how HTTP Basic Authentication works within Spring Security. First, we see the WWW-Authenticate header is sent back to an unauthenticated client.spring-doc.cn

basicauthenticationentrypoint
Figure 1. Sending WWW-Authenticate Header

The figure builds off our SecurityFilterChain diagram.spring-doc.cn

number 1 First, a user makes an unauthenticated request to the resource /private for which it is not authorized.spring-doc.cn

number 2 Spring Security’s FilterSecurityInterceptor indicates that the unauthenticated request is Denied by throwing an AccessDeniedException.spring-doc.cn

number 3 Since the user is not authenticated, ExceptionTranslationFilter initiates Start Authentication. The configured AuthenticationEntryPoint is an instance of BasicAuthenticationEntryPoint which sends a WWW-Authenticate header. The RequestCache is typically a NullRequestCache that does not save the request since the client is capable of replaying the requests it originally requested.spring-doc.cn

When a client receives the WWW-Authenticate header it knows it should retry with a username and password. Below is the flow for the username and password being processed.spring-doc.cn

basicauthenticationfilter
Figure 2. Authenticating Username and Password

The figure builds off our SecurityFilterChain diagram.spring-doc.cn

number 1 When the user submits their username and password, the BasicAuthenticationFilter creates a UsernamePasswordAuthenticationToken which is a type of Authentication by extracting the username and password from the HttpServletRequest.spring-doc.cn

number 2 Next, the UsernamePasswordAuthenticationToken is passed into the AuthenticationManager to be authenticated. The details of what AuthenticationManager looks like depend on how the user information is stored.spring-doc.cn

number 3 If authentication fails, then Failurespring-doc.cn

number 4 If authentication is successful, then Success.spring-doc.cn

Spring Security’s HTTP Basic Authentication support in is enabled by default. However, as soon as any servlet based configuration is provided, HTTP Basic must be explicitly provided.spring-doc.cn

A minimal, explicit configuration can be found below:spring-doc.cn

Explicit HTTP Basic Configuration
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
	http
		// ...
		.httpBasic(withDefaults());
	return http.build();
}
<http>
	<!-- ... -->
	<http-basic />
</http>
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
	http {
		// ...
		httpBasic { }
	}
	return http.build()
}