Accessing API from browser (a jQuery script) is getting blocked. Here is the error message I am getting:
Access to XMLHttpRequest at 'http://localhost:8765/conversion/convert' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My jQuery script in a HTML file:
$.ajax({
type: 'POST',
url: 'http://localhost:8765/conversion/convert',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer MY_JWT_TOKEN'
},
data: JSON.stringify({
id: 1,
from: 'usd',
to: 'bdt',
quantity: 100
}),
success: function(data) {
console.log(data);
},
error: function(error) {
console.error(error);
}
});
Maven Dependencies and Versions:
- spring-cloud-gateway: 2022.0.4
- spring-cloud-starter-gateway: 3.1.6
- spring-boot-starter-oauth2-resource-server: 3.1.6
- spring-cloud-starter-netflix-eureka-client
I have configured OAuth2 (Keycloak) with my API gateway and used CORS (globalcors) config in my Gateway service config file (yml) as directed on official Spring Cloud page. I also tried all the different approaches from internet, nothing seems working.
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-ui: http://localhost:9000/realms/Microservices-demo-realm
jws-algorithm: RS256
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*"
allowedMethods: "*"
allowedHeaders: "*"
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin RETAIN_UNIQUE
- name: TokenRelay
routes:
- id: conversion-service
uri: lb://currency-conversion
predicates:
- Path=/conversion/**
Here is the Google Chrome Network Console:
I have also tried from a tiny ReactJS app and CORS are being block from there as well. Here is a screenshot:
Please help!


OPTIONSrequests outside of any authentication requirements@Bean public SecurityWebFilterChain filterChain(ServerHttpSecurity http) { http .authorizeExchange(autorize -> autorize .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll() .pathMatchers("/actuator/health/**").permitAll() .anyExchange().authenticated()) .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())); return http.build(); }