Spring Security addCorsMappings не действует - PullRequest
0 голосов
/ 09 июля 2020

Я использую angular 5.0.5 и весеннюю загрузку 2.0.2.RELEASE

angular работает на localhost: 4200 Spring работает на localhost: 8181

пытается чтобы настроить cors в весенней безопасности, поэтому я включаю cors в WebSecurityConfigurerAdapter

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
                .csrf().disable()
                .authorizeRequests().antMatchers(authorizedPaths).permitAll()
                .anyRequest().authenticated()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

И я использую WebMvcConfigurer для конфигурации cors, но даже если я поставлю поддельное происхождение и ограничу httpMethod только УДАЛИТЬ Мое приложение angular по-прежнему имеет доступ к бэкэнду, и оно не отклоняется, как будто у меня нет конфигурации cors

@Configuration
@EnableWebMvc
public class WebMvcConfigurerImpl implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://fake-domain.com")
                .allowedMethods("DELETE")
                .allowedHeaders("header1", "header2", "header3")
                .exposedHeaders("header1", "header2")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

даже с почтальоном, я все равно могу использовать HTTP-запрос для доступа к бэкэнду. некоторое время пытался заставить его работать перед публикацией, поэтому я немного в отчаянии

1 Ответ

0 голосов
/ 09 июля 2020

Вы можете создать bean-компонент CorsConfigurationSource в том же классе, который расширяет WebSecurityConfigurerAdapter

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(asList("*"));
    configuration.setAllowedMethods(asList("HEAD",
            "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
    // setAllowCredentials(true) is important, otherwise:
    // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
    configuration.setAllowCredentials(true);
    // setAllowedHeaders is important! Without it, OPTIONS preflight request
    // will fail with 403 Invalid CORS request
    configuration.setAllowedHeaders(
            asList("Authorization", "Cache-Control", "Content-Type", "Access-Control-Allow-Origin",
                    "Access-Control-Expose-Headers", "Access-Control-Allow-Headers"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

См. https://github.com/techiesantosh/taskmanager-service/blob/develop/src/main/java/com/web/taskmanager/config/TaskConfig.java

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...