На своем уровне безопасности я использую два фильтра: AjaxAuthenticationFilter и JWTAuthenticationFilter (оба они расширяют AbstractAuthenticationProcessingFilter). Для первого я хочу использовать только oAjaxAuhtenticationProvider, а для второго - только JwtAuthenticationProvider.
Это основная причина моей проблемы, я не могу их разделить (authenticationProviders).
Я пробовал этот код, но не работает:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
public static final String AUTHENTICATION_HEADER_NAME = "Authorization";
public static final String AUTHENTICATION_URL = "/api/auth/login";
public static final String REFRESH_TOKEN_URL = "/api/auth/token";
public static final String API_ROOT_URL = "/api/**";
@Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
@Autowired private AjaxAwareAuthenticationSuccessHandler successHandler;
@Autowired private AjaxAwareAuthenticationFailureHandler failureHandler;
@Autowired private AjaxAuthenticationProvider ajaxAuthenticationProvider;
@Autowired private JwtAuthenticationProvider jwtAuthenticationProvider;
@Autowired private AuthenticationManager authenticationManager;
@Autowired private ObjectMapper objectMapper;
protected AjaxLoginProcessingFilter buildAjaxLoginProcessingFilter(String loginEntryPoint) throws Exception {
AjaxLoginProcessingFilter filter =
new AjaxLoginProcessingFilter(loginEntryPoint, successHandler, failureHandler, objectMapper);
filter.setAuthenticationManager(authenticationManager);
return filter;
}
protected JwtTokenAuthenticationProcessingFilter buildJwtTokenAuthenticationProcessingFilter(List<String> pathsToSkip, String pattern) {
SkipPathRequestMatcher matcher = new SkipPathRequestMatcher(pathsToSkip, pattern);
JwtTokenAuthenticationProcessingFilter filter =
new JwtTokenAuthenticationProcessingFilter(failureHandler, matcher);
filter.setAuthenticationManager(this.authenticationManager);
return filter;
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
List<String> permitAllEndpointsList = Arrays.asList(
AUTHENTICATION_URL,
REFRESH_TOKEN_URL,
"/console"
);
http.
csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(this.authenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(permitAllEndpointsList.toArray(new String[permitAllEndpointsList.size()]))
.permitAll()
.and()
.authorizeRequests()
.antMatchers(API_ROOT_URL).authenticated();
}
@Configuration
@Order(1)
public class AjaxWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.addFilterBefore(buildAjaxLoginProcessingFilter(AUTHENTICATION_URL), UsernamePasswordAuthenticationFilter.class)
.authenticationProvider(ajaxAuthenticationProvider);
}
}
@Configuration
@Order(2)
public class JwtWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
List<String> permitAllEndpointsList = Arrays.asList(
AUTHENTICATION_URL,
REFRESH_TOKEN_URL,
"/console"
);
http
.csrf().disable()
.addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(permitAllEndpointsList, API_ROOT_URL),
UsernamePasswordAuthenticationFilter.class)
.authenticationProvider(jwtAuthenticationProvider);
}
}
}
Спасибо за помощь. Мой код был совершенно неправильным. Неправильные аннотации и подход.
Я решил свою проблему с передачей правильного authManager в целевую конфигурацию (только conspect):
@Configuration
@Order(1)
public class AjaxWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// TODO Auto-generated method stub
auth.authenticationProvider(ajaxAuthenticationProvider);
}
}
@Configuration
public class JwtWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// TODO Auto-generated method stub
auth.authenticationProvider(jwtAuthenticationProvider);
}
}
В конфигурации с порядком (1) я должен определить antMacher в обязательном порядке:
.and()
.antMatcher("/api/auth/**")
.authorizeRequests()
.antMatchers(AUTHENTICATION_URL)
.permitAll()
И в последней конфигурации я должен определить antMatchers для "/ **"
.authorizeRequests()
.antMatchers("/**").authenticated()
Конечный результат:
@EnableWebSecurity
public class WebSecurityConfig {
public static final String AUTHENTICATION_HEADER_NAME = "Authorization";
public static final String AUTHENTICATION_URL = "/api/auth/login";
public static final String REFRESH_TOKEN_URL = "/api/auth/token";
public static final String API_ROOT_URL = "/api/**";
@Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
@Autowired private AjaxAwareAuthenticationSuccessHandler successHandler;
@Autowired private AjaxAwareAuthenticationFailureHandler failureHandler;
@Autowired private AjaxAuthenticationProvider ajaxAuthenticationProvider;
@Autowired private JwtAuthenticationProvider jwtAuthenticationProvider;
@Autowired private ObjectMapper objectMapper;
protected AjaxLoginProcessingFilter buildAjaxLoginProcessingFilter(String loginEntryPoint,
AuthenticationManager authManager) throws Exception {
AjaxLoginProcessingFilter filter =
new AjaxLoginProcessingFilter(loginEntryPoint, successHandler, failureHandler, objectMapper);
filter.setAuthenticationManager(authManager);
return filter;
}
protected JwtTokenAuthenticationProcessingFilter buildJwtTokenAuthenticationProcessingFilter(String urlForFilter,
AuthenticationManager authManager) {
//SkipPathRequestMatcher matcher = new SkipPathRequestMatcher(pathsToSkip, pattern);
JwtTokenAuthenticationProcessingFilter filter =
new JwtTokenAuthenticationProcessingFilter(failureHandler, urlForFilter);
filter.setAuthenticationManager(authManager);
return filter;
}
@Configuration
@Order(1)
public class AjaxWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// TODO Auto-generated method stub
auth.authenticationProvider(ajaxAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.antMatcher("/api/auth/**")
.authorizeRequests()
.antMatchers(AUTHENTICATION_URL)
.permitAll()
.and()
.addFilterBefore(buildAjaxLoginProcessingFilter(AUTHENTICATION_URL, super.authenticationManager()), UsernamePasswordAuthenticationFilter.class)
.authenticationProvider(ajaxAuthenticationProvider);
}
}
@Configuration
public class JwtWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// TODO Auto-generated method stub
auth.authenticationProvider(jwtAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/**").authenticated()
.and()
.addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(API_ROOT_URL, super.authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
.authenticationProvider(jwtAuthenticationProvider);
}
}
}
Возможный дубликат stackoverflow.com/questions/33603156/…