У меня Cors настроен следующим образом:
Код: Выделить всё
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://goods.example.com"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "OPTIONS"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control-Allow-Origin", "Content-Type",
"Accept", "Jwt-Token", "Authorization", "X-Requested-With",
"Access-Control-Request-Method", "Access-Control-Request-Headers"));
configuration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Jwt-Token", "Authorization",
"Access-Control-Allow-Origin", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials", "Filename"));
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
Код: Выделить всё
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors()
.configurationSource(corsConfigurationSource())
.and()
.csrf()
.disable()
// .requiresChannel()
// .anyRequest()
// .requiresSecure()
// .and()
.authorizeHttpRequests( authCustomizer -> authCustomizer
.requestMatchers(HttpMethod.POST, "/api/v1/auth/authenticate").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/test").permitAll()
)
.authorizeHttpRequests()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.headers()
.xssProtection()
.and()
.contentSecurityPolicy("default-src 'self' data: blob:;");
return httpSecurity.build();
}
Когда я вызываю конечную точку аутентификации с действительными учетными данными, она показывает следующие заголовки:
Код: Выделить всё
HTTP/1.1 403
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: http://goods.example.com
Access-Control-Expose-Headers: Origin, Content-Type, Accept, Jwt-Token, Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Filename
Access-Control-Allow-Credentials: true
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 03 May 2023 09:11:19 GMT
Keep-Alive: timeout=20
Connection: keep-alive
На мой взгляд, я явно перечисляю разрешенные источники в моей конфигурации cors, но по какой-то причине это не работает...
Что я пробовал:
- Я пробовал менять Коллекции. SingletonList() для Arrays.asList()
- Удаление XSS и CSP
- Изменение порядка аннотаций класса на: @Order(Ordered.HIGHEST_PRECEDENCE)< /li>
Проверьте, есть ли активные правила cors в Tomcat (я не могу их найти) - Используйте setAllowedOriginPatterns ИЛИ addAllowedOriginPattern вместо setAllowOrigins
- Добавьте аннотацию @Bean в мой CorsConfigurationSource
Просто уточняю: у меня не возникает ошибка в браузере, только в Java/Tomcat. Вероятно, потому, что Spring Boot возвращает правильный заголовок...
Спасибо за помощь!
Подробнее здесь: https://stackoverflow.com/questions/761 ... in-cant-be
Мобильная версия