abus
abus

Reputation: 109

No 'Access-Control-Allow-Origin' with Spring Cloud API Gateway and OAuth2 Server

I'm facing a CORS issue when using Spring Cloud API Gateway along with a Spring Security OAuth2 server. My frontend application running on http://localhost:4200/ is blocked due to a missing Access-Control-Allow-Origin header in the response. "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."

I've already configured CORS in my application.yaml file with the following settings:

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "http://localhost:4200"
            allowedMethods: '*'
            allowedHeaders: '*'
    security:
      oauth2:
        resourceserver:
          jwt:
            issuer-uri: https://securetoken.google.com/<project-id>
            jwk-set-uri: https://www.googleapis.com/service_accounts/v1/jwk/[email protected]

Despite the configuration above, I'm still encountering the CORS error. Could someone please help me identify the potential reasons for this behavior and suggest further troubleshooting steps to resolve the issue?

Without using the oauth2 resourceserver dependency I don't have any CORS errors.

And how can I make my microservices without using the api gateway secure? Currently when I'm not using the api gateway for my request I don't have to authenticate and have access to all endpoints.

Upvotes: 0

Views: 558

Answers (1)

abus
abus

Reputation: 109

"CORS must be processed before Spring Security because the pre-flight request will not contain any cookies (i.e. the JSESSIONID). If the request does not contain any cookies and Spring Security is first, the request will determine the user is not authenticated (since there are no cookies in the request) and reject it."

https://docs.spring.io/spring-security/reference/reactive/integrations/cors.html

@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
class SecurityConfiguration {

    @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
    String issuerUri;

    @Bean
    public SecurityWebFilterChain securityFilterChain(ServerHttpSecurity http) {
        http
            .authorizeExchange(auth -> {
                auth.anyExchange().authenticated();
            })
            .oauth2ResourceServer(oauth2 -> oauth2
                    .jwt(withDefaults())
            )
            .cors(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    public ReactiveJwtDecoder jwtDecoder() {
        return ReactiveJwtDecoders.fromIssuerLocation(issuerUri);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

Upvotes: 1

Related Questions