CORS в весенней загрузке - PullRequest
       8

CORS в весенней загрузке

0 голосов
/ 25 февраля 2019

Я пытаюсь настроить серверное приложение с настройкой 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 корректно управляется на всех конечных точках

Ответы [ 2 ]

0 голосов
/ 26 февраля 2019

Попробуйте это

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**") //or the URLs you would like to add
            .allowedMethods("GET", "POST");
}
0 голосов
/ 25 февраля 2019

Попробуйте это:

@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(HttpMethod.OPTIONS,"/login/**").permitAll() // this
        .anyRequest().authenticated();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...