Я пытаюсь настроить серверное приложение с настройкой cors.Здесь конфигурация, но любой запрос cors на login
будет иметь код ответа 403:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
public WebSecurityConfig(JwtAuthenticationEntryPoint unauthorizedHandler) {
this.unauthorizedHandler = unauthorizedHandler;
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("*"));
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowedHeaders(Collections.singletonList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new JwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class)
.cors().and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.csrf().disable()
.antMatcher("/api/**").authorizeRequests()
.antMatchers("/login/**").permitAll()
.anyRequest().authenticated();
}
}
EDIT Я решил добавить еще один класс конфигурациии удаление beand из websecurity one.
Просто поймите, что конфигурация cors должна быть настроена в Spring Boot, а не в Spring Security.
Класс, который я добавил:
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
.allowedHeaders("*")
.allowCredentials(true);
}
}
И WebSeurityConfig стал следующим:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
public WebSecurityConfig(JwtAuthenticationEntryPoint unauthorizedHandler) {
this.unauthorizedHandler = unauthorizedHandler;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new JwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class)
.cors().and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.csrf().disable()
.antMatcher("/api/**").authorizeRequests()
.antMatchers("/login/**").permitAll()
.anyRequest().authenticated();
}
}
Теперь все работает как положено, cors корректно управляется на всех конечных точках