У нас есть CustomAuthenticationProvider (AuthenticationProvider), разработанный для Spring, который работает с CustomAuthenticationRequest (Аутентификация), CustomAuthentication (Аутентификация), CustomUser .
Как только мы проверяем учетные данные при вызове нашего контроллера, мы создаем запрос CustomAuthenticationRequest на основе учетных данных.
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(new CustomAuthenticationRequest(new CustomUser(account.getUsername())));
Отладочный логин подтверждает, что CustomAuthenticationRequest был сохранен в HTTPSession.
HttpSessionSecurityContextRepository - SecurityContext 'org.springframework.security.core.context.SecurityContextImpl@730db7d8: Authentication: pro.someplace.spring.CustomAuthenticationRequest@730db7d8' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade@5da80010
WebSecurityConfigurerAdapter регистрирует нашего провайдера аутентификации:
@Override
public void configure(AuthenticationManagerBuilder builder)
throws Exception {
builder.authenticationProvider(new CustomAuthenticationProvider());
}
И устанавливает, что могут и не могут видеть анонимные и аутентифицированные пользователи.
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login", "/registration").permitAll()
.anyRequest()
.authenticated();
}
Проблема, с которой мы столкнулись, заключается в том, что до FilterSecurityInterceptor можно узнать, какой AuthenticationProvider подходит для шагов AnonymousAuthenticationFilter:
o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@4cc1f847: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffd148a: RemoteIpAddress: 127.0.0.1; SessionId: 74DB809F1CB5CFB1F977EC20B37B218E; Granted Authorities: ROLE_ANONYMOUS'
Если я удалю AnonymousAuthenticationFilter, я не смогу получить доступ к allowAll () в конфигурации (другая ошибка).
Любопытно, что в конце обработки запроса я заметил следующее сообщение:
SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
Ok. Поэтому SecurityContextPersistenceFilter должен был сохранить контекст в HttpSessionSecurityContextRepository.
Но когда появляется следующий запрос, SecurityContextPersistenceFilter не имеет такого объекта. Это было сохранено вообще? Это было удалено?
o.s.security.web.FilterChainProxy - /ordervalidator at position 2 of 10 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
o.s.s.w.c.HttpSessionSecurityContextRepository - No HttpSession currently exists
o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
Как я могу сконфигурировать Spring, чтобы разрешить аутентифицированным пользователям там, где я хочу, и использовать мой CustomAuthenticationProvider , когда он доступен в HTTPSession? Где находится объект безопасности и почему он не хранится?