Я пробовал различные варианты, позволяющие моему интерфейсу взаимодействовать с конечной точкой весной, избегая при этом проблемы с Cors. Здесь я предлагаю вам одно из решений, которые я пробовал, но все равно не сработало. Конечная точка — /api/v1/test
Специальный класс конфигурации cors (я хочу разрешить запросы всех источников):
Код: Выделить всё
@Component
public class CustomCorsConfiguration implements CorsConfigurationSource {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("*"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("*"));
return config;
}
}
Код: Выделить всё
@Autowired
CustomCorsConfiguration customCorsConfiguration;
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.cors(c -> c.configurationSource(customCorsConfiguration))
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers(
AntPathRequestMatcher.antMatcher("/api/v1/test")
)
.permitAll()
.requestMatchers("/api/**")
.authenticated()
)
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
}
Код: Выделить всё
@RestController
@CrossOrigin
@RequestMapping(value = "/api/v1/")
@Slf4j
public class TestController {
@GetMapping(value = "test", produces = "application/json")
@Operation(method = "GET")
public ResponseEntity getTest() {
...
Доступ к XMLHttpRequest по адресу «https://» имя_сервера/api/v1/test' из
источника 'http://localhost:5123' заблокировано политикой CORS:
Ответ на предполетный запрос не проходит проверку контроля доступа: Нет
Заголовок Access-Control-Allow-Origin присутствует в запрошенном
ресурсе.
Подробнее здесь: https://stackoverflow.com/questions/790 ... -http-loca