I try to secure access to SpringBoot REST services via a Bearer Token. I followed: https://www.baeldung.com/spring-boot-api-key-secret
Although I set a URL "api/v1/security/auth/login" to permitAll, still the AuthenticationSecurity Filter is triggered.
My Config:
@Log4j2
@EnableWebSecurity
@Configuration
public class AuthenticationRESTControllerSecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
log.traceEntry("securityFilterChain is build");
http
.csrf(AbstractHttpConfigurer::disable)
.cors(AbstractHttpConfigurer::disable)
.authorizeHttpRequests((requests) -> requests
.requestMatchers("api/v1/security/auth/login").permitAll()
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults())
.sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.NEVER))
.addFilterBefore(new AuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
log.traceEntry("securityFilterChain build completed");
return http.build();
}
}
The authentication filter:
public class AuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
log.traceEntry();
try {
Authentication authentication = AuthenticationService.getAuthentication((HttpServletRequest) request);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
} catch (Exception exp) {
log.debug("API Key Authentication failed with: {}", exp.getMessage());
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
PrintWriter writer = httpResponse.getWriter();
writer.print(exp.getMessage());
writer.flush();
writer.close();
} finally {
log.traceExit();
}
}
}
I expected that .authorizeHttpRequests((requests) -> requests.requestMatchers("api/v1/security/auth/login").permitAll() from the Config would cause spring to omit the Authentication Filter. I can not see why it is called and Authentication is attempted.