Spring безопасность AnonymousAuthenticationToken после обновленияJAVA

Программисты JAVA общаются здесь
Anonymous
Spring безопасность AnonymousAuthenticationToken после обновления

Сообщение Anonymous »

Я обновил свое приложение весенней загрузки с 2.7.7 до 3.2.5 (версия безопасности с 5.7.11 до 6.2.4). После этого обновления я успешно прошел аутентификацию с помощью UsernamePasswordAuthenticationToken. Но после запроса аутентификации в каждом запросе я получаю AnonymousAuthenticationToken.
Я перепробовал все об этом в stackoverflow....
Ниже вы можете найдите мои старые и новые конфигурации.
старая конфигурация безопасности

Код: Выделить всё

@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);
}
новая конфигурация безопасности

Код: Выделить всё

@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) {
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);
}
вот внутренняя часть 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;
}
Короче говоря, с моей старой конфигурацией я мог войти в систему, а затем отправлять другие запросы со старой загрузкой Spring, теперь я не могу, и я также не могу с новой конфигурацией и новой загрузкой Spring. Теперь я могу войти в систему только после этого, все анонимно

Подробнее здесь: https://stackoverflow.com/questions/785 ... er-upgrade

Вернуться в «JAVA»