I have upgraded my spring boot application from 2.7.7 to 3.2.5 ( security version from 5.7.11 to 6.2.4) after this upgrade i successfully authenticate with UsernamePasswordAuthenticationToken. But after the authenticate request in every request i get AnonymousAuthenticationToken.
I have tried everything about this in the stackoverflow ….
Below you can find my old and new configs.
old security config
@Configuration
@EnableWebSecurity
public class sampleSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private sampleAuthenticationProvider sampleAuthenticationProvider;
@Autowired
private thirdAuthenticationProvider thirdAuthenticationProvider;
@Autowired
private secondAuthenticationProvider secondAuthenticationProvider;
@Autowired
private sampleAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private sampleAuthenticationFailureHandler authenticationFailureHandler;
@Autowired
private sampleLogoutSuccessHandler logoutSuccessHandler;
@Autowired
private sampleInvalidSessionStrategy invalidSessionStrategy;
@Autowired
private sampleSessionInformationExpiredStrategy expiredSessionStrategy;
@Autowired
private CompositeSessionAuthenticationStrategy compositeSessionAuthenticationStrategy;
@Autowired
private sampleConcurrentSessionFilter concurrentSessionFilter;
@Autowired
private RateLimitFilter rateLimitFilter;
@Autowired
private CustomLogoutHandler logoutHandler;
@Value("${anonymous.endpoints}")
private String[] anonymousEndpoints;
@Value("${maximum.concurrent.session.count:#{1}}")
private int concurrentSessionCount;
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public sampleAuthenticationFilter sampleAuthenticationFilter() throws Exception {
final sampleAuthenticationFilter filter = new sampleAuthenticationFilter();
filter.setAuthenticationManager(authenticationManagerBean());
filter.setAuthenticationFailureHandler(authenticationFailureHandler);
filter.setSessionAuthenticationStrategy(compositeSessionAuthenticationStrategy);
return filter;
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) {
auth.authenticationProvider(sampleAuthenticationProvider);
}
@Bean
public secondAuthenticationFilter secondAuthenticationFilter() throws Exception {
final secondAuthenticationFilter filter = new secondAuthenticationFilter();
filter.setAuthenticationManager(authenticationManagerBean());
filter.setAuthenticationFailureHandler(authenticationFailureHandler);
filter.setSessionAuthenticationStrategy(compositeSessionAuthenticationStrategy);
return filter;
}
@Bean
public thirdAuthenticationFilter thirdAuthenticationFilter() throws Exception {
final thirdAuthenticationFilter filter = new thirdAuthenticationFilter();
filter.setAuthenticationManager(authenticationManagerBean());
filter.setAuthenticationFailureHandler(authenticationFailureHandler);
filter.setSessionAuthenticationStrategy(compositeSessionAuthenticationStrategy);
return filter;
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
RequestMatcher csrfRequestMatcher = new RequestMatcher() {
// Disable CSFR protection on the following urls:
private AntPathRequestMatcher[] requestMatchers = {
new AntPathRequestMatcher("/login/**"),
new AntPathRequestMatcher("/session/auth/check-auth-token"),
new AntPathRequestMatcher("/logout"),
};
@Override
public boolean matches(final HttpServletRequest request) {
// If the request match one url the CSFR protection will be disabled
for (AntPathRequestMatcher rm : requestMatchers) {
if (rm.matches(request)) {
return false;
}
}
return true;
}
};
http
.csrf().requireCsrfProtectionMatcher(csrfRequestMatcher).disable()
.cors()
.and()
.authorizeRequests()
.antMatchers(anonymousEndpoints)
.permitAll()
.anyRequest()
.authenticated()
.and()
.addFilterBefore(secondAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(thirdAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(sampleAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(concurrentSessionFilter, sampleConcurrentSessionFilter.class)
.addFilterAfter(rateLimitFilter, sampleConcurrentSessionFilter.class)
.authenticationProvider(secondAuthenticationProvider)
.authenticationProvider(thirdAuthenticationProvider)
.authenticationProvider(sampleAuthenticationProvider)
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.formLogin()
.failureHandler(authenticationFailureHandler)
.and()
.logout()
.logoutUrl("/user/logout")
.addLogoutHandler(logoutHandler)
.logoutSuccessHandler(logoutSuccessHandler)
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies(RequestHeaderConstant.JSESSIONID)
.and()
.sessionManagement()
.invalidSessionStrategy(invalidSessionStrategy)
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.maximumSessions(concurrentSessionCount)
.maxSessionsPreventsLogin(false)
.expiredSessionStrategy(expiredSessionStrategy);
http
.headers().frameOptions().sameOrigin();
}
@Override
public void configure(final WebSecurity web) {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers(ClientApiEndpointConstant.LOGIN_NOT_REQUIRED_URLS);
}
new security config
@Configuration
@EnableWebSecurity
public class sampleSecurityConfig {
@Autowired
private sampleAuthenticationProvider sampleAuthenticationProvider;
@Autowired
private thirdAuthenticationProvider thirdAuthenticationProvider;
@Autowired
private secodAuthenticationProvider secodAuthenticationProvider;
@Autowired
private sampleAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private sampleAuthenticationFailureHandler authenticationFailureHandler;
@Autowired
private sampleLogoutSuccessHandler logoutSuccessHandler;
@Autowired
private sampleInvalidSessionStrategy invalidSessionStrategy;
@Autowired
private sampleSessionInformationExpiredStrategy expiredSessionStrategy;
@Autowired
private CompositeSessionAuthenticationStrategy compositeSessionAuthenticationStrategy;
@Autowired
private sampleConcurrentSessionFilter concurrentSessionFilter;
@Autowired
private RateLimitFilter rateLimitFilter;
@Autowired
private CustomLogoutHandler logoutHandler;
@Value("${anonymous.endpoints}")
private String[] anonymousEndpoints;
@Value("${maximum.concurrent.session.count:#{1}}")
private int concurrentSessionCount;
@Bean
public AuthenticationManager authenticationManagerBean(final List<AuthenticationProvider> authenticationProvider) {
return new ProviderManager(authenticationProvider);
}
@Bean
public sampleAuthenticationFilter sampleAuthenticationFilter(final AuthenticationConfiguration authenticationConfiguration) throws Exception {
final sampleAuthenticationFilter filter = new sampleAuthenticationFilter();
filter.setAuthenticationManager(authenticationManagerBean(Collections.singletonList(sampleAuthenticationProvider)));
filter.setAuthenticationFailureHandler(authenticationFailureHandler);
filter.setSessionAuthenticationStrategy(compositeSessionAuthenticationStrategy);
return filter;
}
@Bean
public secodAuthenticationFilter secodAuthenticationFilter() throws Exception {
final secodAuthenticationFilter filter = new secodAuthenticationFilter();
filter.setAuthenticationManager(authenticationManagerBean(Collections.singletonList(secodAuthenticationProvider)));
filter.setAuthenticationFailureHandler(authenticationFailureHandler);
filter.setSessionAuthenticationStrategy(compositeSessionAuthenticationStrategy);
return filter;
}
@Bean
public thirdAuthenticationFilter thirdAuthenticationFilter() throws Exception {
final thirdAuthenticationFilter filter = new thirdAuthenticationFilter();
filter.setAuthenticationManager(authenticationManagerBean(Collections.singletonList(thirdAuthenticationProvider)));
filter.setAuthenticationFailureHandler(authenticationFailureHandler);
filter.setSessionAuthenticationStrategy(compositeSessionAuthenticationStrategy);
return filter;
}*
@Bean
public SecurityFilterChain filterChain(final HttpSecurity http, final AuthenticationConfiguration authenticationConfiguration) throws Exception {
RequestMatcher csrfRequestMatcher = new RequestMatcher() {
private final AntPathRequestMatcher[] requestMatchers = {
new AntPathRequestMatcher("/user/login/*"),
new AntPathRequestMatcher("/session/auth/check-auth-token"),
new AntPathRequestMatcher("/logout"),
};
@Override
public boolean matches(final HttpServletRequest request) {
// If the request match one url the CSFR protection will be disabled
for (AntPathRequestMatcher rm : requestMatchers) {
if (rm.matches(request)) {
return false;
}
}
return true;
}
};
http
.csrf(csrfConfigurer -> csrfConfigurer.requireCsrfProtectionMatcher(csrfRequestMatcher))
.cors(corsConfigurer -> corsConfigurer.configure(http))
.authorizeHttpRequests(auth -> auth.requestMatchers(anonymousEndpoints).permitAll()
.anyRequest().authenticated())
.addFilterBefore(secodAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(thirdAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(sampleAuthenticationFilter(authenticationConfiguration), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(concurrentSessionFilter, sampleConcurrentSessionFilter.class)
.addFilterAfter(rateLimitFilter, sampleConcurrentSessionFilter.class)
.authenticationProvider(secodAuthenticationProvider)
.authenticationProvider(thirdAuthenticationProvider)
.authenticationProvider(sampleAuthenticationProvider)
.exceptionHandling(exceptionHandlingConfigurer -> exceptionHandlingConfigurer.authenticationEntryPoint(authenticationEntryPoint))
.formLogin(formLoginConfigurer -> formLoginConfigurer.failureHandler(authenticationFailureHandler))
.logout(logoutConfigurer -> logoutConfigurer.logoutUrl("/user/logout")
.addLogoutHandler(logoutHandler)
.logoutSuccessHandler(logoutSuccessHandler)
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies(RequestHeaderConstant.JSESSIONID))
.sessionManagement(sessionManagementConfigurer -> sessionManagementConfigurer
.invalidSessionStrategy(invalidSessionStrategy)
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.maximumSessions(concurrentSessionCount)
.maxSessionsPreventsLogin(false)
.expiredSessionStrategy(expiredSessionStrategy));
http
.headers(headersConfigurer -> headersConfigurer.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin));
return http.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return web -> web.ignoring()
.requestMatchers(HttpMethod.OPTIONS, "/*")
.requestMatchers(ClientApiEndpointConstant.LOGIN_NOT_REQUIRED_URLS);
}
here is the inside of xBankAuthenticationProvider
`
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
final String username;
final String password = (String) authentication.getCredentials();
// verify username and password is correct from backend
final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
username,
password,
authorities
);
token.setDetails(loginResponse);
return token;
}
So in brief with my old config i used to be able to login and then send other requests with old spring boot now i cant and i also cant with the new config and new spring boot. I am now only able to login after that everything is anonymous
serdarunlusoy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.