I'm using spring-security 6 to implement custom authentication. Actual authentication is based on signature which is sent in a header. Therefore I have tried to implement a sample to get the structure working. Below are my code.
AuthenticatoinProvider:
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
final String name = authentication.getName();
final String password = authentication.getCredentials().toString();
if (!"admin".equals(name) || !"system".equals(password)) {
return null;
}
return authenticateAgainstThirdPartyAndGetAuthentication(name, password);
}
@Override
public boolean supports(Class<?> authentication) {
return true;
}
private static UsernamePasswordAuthenticationToken authenticateAgainstThirdPartyAndGetAuthentication(String name, String password) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
final UserDetails principal = new User(name, password, grantedAuths);
return new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
}
}
Fitler:
@Component
public class EverybodyAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
SecurityContextHolder.createEmptyContext();
// THIS IS ONLY FOR TESTS. TO GET THIS WORK SENDING HARD CODED TOKEN. THIS SHOULD BE
// CREATED FROM HEADER VALUES.
customAuthenticationProvider.authenticate(new UsernamePasswordAuthenticationToken("admin",
"system"));
filterChain.doFilter(request, response);
}
}
Security Config:
@EnableWebSecurity
@Configuration
@ComponentScan("com.example.demo")
public class SecurityConfig{
@Autowired
private CustomAuthenticationProvider authProvider;
@Bean
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder =
http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.authenticationProvider(authProvider);
return authenticationManagerBuilder.build();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http,
AuthenticationManager authenticationManager,
EverybodyAuthenticationFilter every) throws Exception {
return http.authorizeHttpRequests(expressionInterceptUrlRegistry ->
expressionInterceptUrlRegistry.anyRequest().authenticated())
.addFilterBefore(every, BasicAuthenticationFilter.class)
.authenticationManager(authenticationManager)
.build();
}
}
Controller:
@Controller
public class HomeController {
private static final String HOME_VIEW = "home/index";
@GetMapping("/home")
public String home(HttpServletRequest request){
return HOME_VIEW;
}
}
In this code EverybodyAuthenticationFilter
send hardcoded token just for testing. Therefore my understanding is this should work for all the requests. However I get 403 error. I came across following discussion where it says with spring-security 6 custome authentication provider works differently.
https://github.com/spring-projects/spring-security/issues/12602
How can i get this to work ?
Lets do a bit more integration with Spring Security and instead of the OncePerRequestFilter
extend the AbstractAuthenticationProcessingFilter
and let the filter use the AuthenticationManager
.
public class EverybodyAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public EverybodyAuthenticationFilter(AuthenticationManager authenticationManager) {
super("/**", authenticationManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken("admin", "system"));
}
}
And yes there are no annotations on this class.
Next to register this in the filter chain with Spring security create a custom DSL and apply that to the regular configuration.
public class CustomSecurityConfigurer extends AbstractHttpConfigurer<CustomSecurityConfigurer, HttpSecurity> {
@Override
public void configure(HttpSecurity http) throws Exception {
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
http.addFilterBefore(new EverybodyAuthenticationFilter(authenticationManager), BasicAuthenticationFilter.class);
}
public static CustomSecurityConfigurer customSecurityConfigurer() {
return new CustomSecurityConfigurer();
}
}
This will do 2 things it will re-use the shared pre-configured AuthenticationManager
which will include your custom AuthenticationProvider
and register it only in the security filter chain. The latter due this not being a spring managed bean anymore.
Lastly apply this DSL to the regular configuration.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.apply(CustomSecurityConfigurer.customSecurityConfigurer());
return http.authorizeHttpRequests( auth -> auth.anyRequest().authenticated())
.build();
}
}
Or when using Spring Boot 3.2 or up
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.with(CustomSecurityConfigurer.customSecurityConfigurer(), Customizer.withDefaults());
return http.authorizeHttpRequests( auth -> auth.anyRequest().authenticated()).build();
}
}
With this you integrate better with Spring Security and your CustomAuthenticationProvider
will be consulted. When issuing a request you can see that your filter and provider is being used in the logs.
2024-04-24T11:27:46.430+02:00 TRACE 59161 --- [nio-8081-exec-1] o.s.security.web.FilterChainProxy : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=any request, Filters=[org.springframework.security.web.session.DisableEncodeUrlFilter@d34f785, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@35ff8be7, org.springframework.security.web.context.SecurityContextHolderFilter@3984cdbb, org.springframework.security.web.header.HeaderWriterFilter@35c10b4c, org.springframework.security.web.csrf.CsrfFilter@544d6d67, org.springframework.security.web.authentication.logout.LogoutFilter@53bd8b05, com.example.demo.config.EverybodyAuthenticationFilter@732016bc, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@7667877e, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@6dad8960, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@1eeb4095, org.springframework.security.web.access.ExceptionTranslationFilter@2654da2e, org.springframework.security.web.access.intercept.AuthorizationFilter@3601de4a]] (1/1)
2024-04-24T11:27:46.430+02:00 DEBUG 59161 --- [nio-8081-exec-1] o.s.security.web.FilterChainProxy : Securing GET /home
2024-04-24T11:27:46.430+02:00 TRACE 59161 --- [nio-8081-exec-1] o.s.security.web.FilterChainProxy : Invoking DisableEncodeUrlFilter (1/12)
2024-04-24T11:27:46.430+02:00 TRACE 59161 --- [nio-8081-exec-1] o.s.security.web.FilterChainProxy : Invoking WebAsyncManagerIntegrationFilter (2/12)
2024-04-24T11:27:46.431+02:00 TRACE 59161 --- [nio-8081-exec-1] o.s.security.web.FilterChainProxy : Invoking SecurityContextHolderFilter (3/12)
2024-04-24T11:27:46.432+02:00 TRACE 59161 --- [nio-8081-exec-1] o.s.security.web.FilterChainProxy : Invoking HeaderWriterFilter (4/12)
2024-04-24T11:27:46.433+02:00 TRACE 59161 --- [nio-8081-exec-1] o.s.security.web.FilterChainProxy : Invoking CsrfFilter (5/12)
2024-04-24T11:27:46.433+02:00 TRACE 59161 --- [nio-8081-exec-1] o.s.security.web.csrf.CsrfFilter : Did not protect against CSRF since request did not match CsrfNotRequired [TRACE, HEAD, GET, OPTIONS]
2024-04-24T11:27:46.433+02:00 TRACE 59161 --- [nio-8081-exec-1] o.s.security.web.FilterChainProxy : Invoking LogoutFilter (6/12)
2024-04-24T11:27:46.433+02:00 TRACE 59161 --- [nio-8081-exec-1] o.s.s.w.a.logout.LogoutFilter : Did not match request to Ant [pattern='/logout', POST]
2024-04-24T11:27:46.433+02:00 TRACE 59161 --- [nio-8081-exec-1] o.s.security.web.FilterChainProxy : Invoking EverybodyAuthenticationFilter (7/12)
2024-04-24T11:27:46.433+02:00 TRACE 59161 --- [nio-8081-exec-1] o.s.s.authentication.ProviderManager : Authenticating request with CustomAuthenticationProvider (1/1)