Custom authentication logic replaces or extends framework defaults when an application needs an authentication method that standard implementations cannot express. In Spring Security, an AuthenticationProvider receives an Authentication request and defines how it is evaluated. section 2.3.4 section 6.1
Implement a custom AuthenticationProvider in a short sequence:
- Declare a class implementing AuthenticationProvider and register it as a Spring component. section 6.1.3
- Implement supports(Class<?>) so the provider accepts the intended Authentication type, such as UsernamePasswordAuthenticationToken. section 6.1.2 section 6.1.3
- Implement authenticate(Authentication), returning a fully authenticated object on success and throwing AuthenticationException on failure. section 6.1.2
- Register the provider with SecurityFilterChain through http.authenticationProvider(authenticationProvider). section 6.1.3
A practical provider reads the username and credentials, loads UserDetails through UserDetailsService, and checks the password with PasswordEncoder. It returns the username and authorities after success, while rejecting an unknown user or incorrect password. Remove sensitive credentials from the resulting authentication object when they are no longer needed. section 6.1.3 section 6.1.2
HTTP Basic provider
Configure HTTP Basic authentication, register the custom provider, and require authentication for every request. A request using curl -u john:12345 http://localhost:8080/hello receives Hello!, while invalid credentials produce a 401 Unauthorized response. section 2.3.4 section 18.5
Figure 2.3 The AuthenticationProvider implements the authentication logic. It receives the request from the AuthenticationManager and delegates finding the user to a UserDetailsService, verifying the password to a PasswordEncoder.
Trace how AuthenticationManager delegates an authentication request to AuthenticationProvider, which can delegate user lookup and password verification. section 2.3.4
