Search code examples
javaspringspring-bootspring-cloud-gateway

How do I set the value of CORS allowed origin for Spring Cloud Gatweay from the environment?


Complements How do I get the value of CORS allowed origin from spring cloud gateway

What environment variable would map to the following point?

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "*" # << how do I change this?

Solution

  • Depending upon OS, the key might not be allowed, but the one of the option would be to use SPRING_APPLICATION_JSON. Check externalize configuration.

    Lets say you have following properties

    spring:
      cloud:
        gateway:
          globalcors:
            corsConfigurations:
              '[/**]':
                allowedOrigins: "*"
                allowedHeaders: "*"
                allowedMethods:
                - GET
                - POST
    

    Convert this yaml to json. For eg

    {
      "spring": {
        "cloud": {
          "gateway": {
            "globalcors": {
              "corsConfigurations": {
                "[/**]": {
                  "allowedOrigins": "*",
                  "allowedHeaders": "*",
                  "allowedMethods": [
                    "GET",
                    "POST"
                  ]
                }
              }
            }
          }
        }
      }
    }
    

    Trim any white spaces for eg using

    {"spring":{"cloud":{"gateway":{"globalcors":{"corsConfigurations":{"[/**]":{"allowedOrigins":"*","allowedHeaders":"*","allowedMethods":["GET","POST"]}}}}}}}
    

    Now in your env variable you can set

    SPRING_APPLICATION_JSON = '{"spring":{"cloud":{"gateway":{"globalcors":{"corsConfigurations":{"[/**]":{"allowedOrigins":"*","allowedHeaders":"*","allowedMethods":["GET","POST"]}}}}}}}'
    

    You can write some kind of CLI script to do this.