Если вы хотите пропустить автоматическую настройку Spring Security, добавьте класс @Configuration
с @EnableWebSecurity
. Не регистрируйте пустое AuthenticationManager
.
Добавьте компонент для своего провайдера и зарегистрируйте его с помощью AuthenticationManager
через AuthenticationManagerBuilder
.
@Configuration
@EnableWebSecurity
public void WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
public void configure(HttpSecurity http) { ... // Security config here}
@Bean
public CustomAuthenticationProvider customProvider() {
return new CustomAuthenticationProvider();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customProvider());
}
}
Это настроит AuthenticationManager
на использование настроенного вами AuthenticationProvider
. Если вы используете последнюю версию Spring Security (не уверен, какая версия включает это), достаточно просто настроить свой пользовательский AuthenticationProvider
, который будет автоматически обнаружен AuthenticationManagerBuilder
. См. Также Spring Security Documentation .
SecurityContext
устанавливается цепочкой фильтров (например, через UsernamePasswordAuthenticationFilter
, который делегирует аутентификацию AuthenticationManager
.
Обновление
Важной частью вашего проекта является то, что ваша конечная точка входа в систему в основном игнорирует все в Spring Security. Основная часть Spring Security реализована в фильтрах, если вы хотите пройти аутентификацию в сети. Приложение (независимо от механизма) вам необходимо добавить фильтр в цепочку.
public CustomAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final ObjectMapper mapper;
public CustomAuthenticationFilter(ObjectMapper mapper) {
super(new AntPathRequestMatcher("/auth/login", "POST"));
this.mapper=mapper;
}
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException, IOException,
ServletException {
MyPrincipal principal = mapper.readValue(request.getInputStream(), MyPrincipal.class);
MyAuthentication authentication = new MyAuthentication(principal);
setDetails(request, authentication); //assuming you are extending AbstractAuthenticationToken
return getAuthenticationManager().authenticate(authentication);
}
protected void setDetails(HttpServletRequest request,
MyAuthentication authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
}
В вашей конфигурации добавьте этот фильтр в Spring Security и настройте фильтр соответствующим образом.
@Bean
public CustomAuthenticationFilter customAuthenticationFilter(ObjectMapper mapper) {
CustomAuthenticationFilter filter = new CustomAuthenticationFilter(mapper);
filter.setAuthenticationManager(authenticationManagerBean());
return filter;
}
// To prevent registering the filter in the default filter chain!
@Bean
public FilterRegistrationbean customAuthenticationFilterRegistration() {
FilterRegistrationBean filterReg = new FilterRegistrationBean(customAuthenticationFilter());
filterReg.setEnabled(false);
return filterReg;
}
@Override
public void configure(HttpSecurity http) {
http.addFilterBefore(customerAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
// other config here
}
Теперь ваша аутентификация является частью Spring Security.