spring-cloud-gateway: spring cloud gateway version 3 CORS Origin policy problem can't be modify

I think this is a bug because I tried every solution that I get on the internet but it does not work. still CORS Origin policy error I’m getting

It always shows a CORS origin problem or 403 error but in Postman works perfectly.

If you know the solution please reply or else please fix this bug I think this is a bug or I’m going something wrong

application.yml file

server:
  port: 9999

spring:
  cloud:
    gateway:
      globalcors:
        add-to-simple-url-handler-mapping: true

        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods:
              - GET
              - POST
              - PUT
              - DELETE
              - PATCH
            allowedHeaders:
              - "Origin"
              - "Content-Type"
              - "Accept"
              - "Authorization"
              - "User-Key"
              - "Request-Tracker"
              - "Session-Tracker"
              - "X-XSRF-TOKEN"
              - "X-IBM-CLIENT-ID"
              - "Message-ID"
              - "X-IBM-CLIENT-SECRET"
      default-filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin, RETAIN_FIRST


      routes:
        - id: ADMIN-SERVICE
          uri: https://example
          predicates:
            - Path=/v1.0.0/registration/example


        - id: ADMIN-SERVICE
          uri:  https://example
          predicates:
            - Path=/v1.0.0/registration/example/**
          filters:
            - AuthenticationFilter

      httpclient:
        ssl:
          useInsecureTrustManager: true

AuthenticationFilter.java

package com.api.filter;

import com.api.exception.MissingAuthorizationHeaderException;
import com.api.exception.UnauthorizedAccessException;
import com.api.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;


@Slf4j
@Component
public class AuthenticationFilter extends AbstractGatewayFilterFactory<AuthenticationFilter.Config> {

    @Autowired
    private RouteValidation routeValidation;

    @Autowired
    private JwtUtil jwtUtil;

    public AuthenticationFilter() {
        super(Config.class);
        log.info("AuthenticationFilter() -> | ");
    }

    @Override
    public GatewayFilter apply(Config config) {

        log.info("============== Apply Method Start ==============");
        log.info("apply(Config) -> | Config : {}", config);

        GatewayFilter bearer = (exchange, chain) -> {

            log.info("apply(Config) -> | Exchange : {} | Chain : {}", exchange, chain);

            if (routeValidation.isSecured.test(exchange.getRequest())) {
                log.info("apply(Config) -> | Route Validation isSecured : ");
                //header contains token or not
                log.info("apply(Config) -> | HttpHeader Check : {}", HttpHeaders.AUTHORIZATION);

                if (!exchange.getRequest().getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) {
                    log.error("apply(Config) -> | MissingAuthorizationHeaderException Throw :");
                    throw new MissingAuthorizationHeaderException();
                }

                log.info("apply(Config) -> | authorization header present");
                String authHeader = exchange.getRequest().getHeaders().get(HttpHeaders.AUTHORIZATION).get(0);
                log.info("apply(Config) -> | AuthHeader : {}", authHeader);

                if (authHeader != null && authHeader.startsWith("Bearer ")) {
                    authHeader = authHeader.substring(7);
                    log.info("apply(Config) -> | After Delete AuthHeader : {}", authHeader);
                }

                try {

                    log.info("apply(Config) -> | Try to validateToken");
                    jwtUtil.validateToken(authHeader);

                } catch (Exception e) {
                    log.error("apply(Config) -> | Exception Message : {} | Exception Cause : {}", e.getMessage(), e.getCause());
                    log.error("apply(Config) -> | UnauthorizedAccessException Throw | invalid access...");
                    throw new UnauthorizedAccessException();
                }

            }

            Mono<Void> filter = chain.filter(exchange);
            log.info("apply(Config) -> | Mono<Void> : {}", filter);

            return filter;
        };

        log.info("apply(Config) -> | GatewayFilter Object : {}", bearer);
        log.info("============== Apply Method End ==============");
        return bearer;
    }

    public static class Config {
        public Config() {
            log.info("Config() -> | Create Object Config class of sub class AuthenticationFilter extends by AbstractGatewayFilterFactory");
        }
    }

}

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 18 (1 by maintainers)

Most upvoted comments

I have fixed it! Now it works !!! Just copy it in order:

server:
  port: 2620
  address: 25.68.201.55
eureka:
  client:
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: Api GateWay
  cloud:
    gateway:
      globalcors:
        add-to-simple-url-handler-mapping: true
        corsConfigurations:
          '[/**]':
            allowedOrigins: "http://127.0.0.1:5500"
            allowedHeaders:
              - "Origin"
              - "Content-Type"
              - "Accept"
              - "Authorization"
              - "Referer"
            allowedMethods:
              - POST
              - GET
              - OPTIONS
      routes:
        - id: Customer Login
          uri: http://localhost:8080
          predicates:
            - Path=/api/v1/auth/login
        - id: Customer Registration
          uri: http://localhost:8080
          predicates:
            - Path=/api/v1/auth/register
        - id: Customer Google login
          uri: http://localhost:8080
          predicates:
            - Path=/api/v1/auth/google/login
        - id: Confirm email
          uri: http://localhost:8081
          predicates:
            - Path=/confirm
      default-filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin, RETAIN_FIRST

I faced the same issue, but as n0rb33rt mentioned the below configuration worked for me, add-to-simple-url-handler-mapping: true As also mentioned in Spring Doc

I tried using the configuration file method but it failed. However configuration via Bean works fine.

@Configuration
public class CorsConf extends CorsConfiguration {
    @Bean
    public CorsWebFilter corsFilter()
    {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials( true );
//        config.setAllowedOrigins( List.of( "*" ) ) //Collections.singtonList(....);
        config.setAllowedOriginPatterns(List.of( "*" ));
        config.setAllowedMethods( List.of( "GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD" ) );
        config.setAllowedHeaders( List.of( "origin", "content-type", "accept", "authorization", "cookie" ) );

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration( "/**", config );

        return new CorsWebFilter(source);
    }