Enable wildcard in CORS spring security + webFlux












0















I have spring security + CORS enable into a project that is made with spring webFlux. My problem here is that we accept for example requests from: http://localhost:4200. How I can make that CORS will accept reqs from http://*.localhost:4200 like http://a.localhost:4200, http://b.localhost:4200 ?



My CORS config looks like:



@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public CorsWebFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);

config.setAllowedOrigins(corsConfigData.getAllowedOrigins());
config.setAllowedHeaders(corsConfigData.getAllowedHeaders());
config.setAllowedMethods(corsConfigData.getAllowedMethods());

source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}


Do you have any ideas ???










share|improve this question



























    0















    I have spring security + CORS enable into a project that is made with spring webFlux. My problem here is that we accept for example requests from: http://localhost:4200. How I can make that CORS will accept reqs from http://*.localhost:4200 like http://a.localhost:4200, http://b.localhost:4200 ?



    My CORS config looks like:



    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public CorsWebFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);

    config.setAllowedOrigins(corsConfigData.getAllowedOrigins());
    config.setAllowedHeaders(corsConfigData.getAllowedHeaders());
    config.setAllowedMethods(corsConfigData.getAllowedMethods());

    source.registerCorsConfiguration("/**", config);
    return new CorsWebFilter(source);
    }


    Do you have any ideas ???










    share|improve this question

























      0












      0








      0








      I have spring security + CORS enable into a project that is made with spring webFlux. My problem here is that we accept for example requests from: http://localhost:4200. How I can make that CORS will accept reqs from http://*.localhost:4200 like http://a.localhost:4200, http://b.localhost:4200 ?



      My CORS config looks like:



      @Bean
      @Order(Ordered.HIGHEST_PRECEDENCE)
      public CorsWebFilter corsFilter() {
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      CorsConfiguration config = new CorsConfiguration();
      config.setAllowCredentials(true);

      config.setAllowedOrigins(corsConfigData.getAllowedOrigins());
      config.setAllowedHeaders(corsConfigData.getAllowedHeaders());
      config.setAllowedMethods(corsConfigData.getAllowedMethods());

      source.registerCorsConfiguration("/**", config);
      return new CorsWebFilter(source);
      }


      Do you have any ideas ???










      share|improve this question














      I have spring security + CORS enable into a project that is made with spring webFlux. My problem here is that we accept for example requests from: http://localhost:4200. How I can make that CORS will accept reqs from http://*.localhost:4200 like http://a.localhost:4200, http://b.localhost:4200 ?



      My CORS config looks like:



      @Bean
      @Order(Ordered.HIGHEST_PRECEDENCE)
      public CorsWebFilter corsFilter() {
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      CorsConfiguration config = new CorsConfiguration();
      config.setAllowCredentials(true);

      config.setAllowedOrigins(corsConfigData.getAllowedOrigins());
      config.setAllowedHeaders(corsConfigData.getAllowedHeaders());
      config.setAllowedMethods(corsConfigData.getAllowedMethods());

      source.registerCorsConfiguration("/**", config);
      return new CorsWebFilter(source);
      }


      Do you have any ideas ???







      spring-boot spring-security spring-webflux






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 12:36









      brebDevbrebDev

      13210




      13210
























          2 Answers
          2






          active

          oldest

          votes


















          2














          I think, as indicated in responses to this question, the CORS specification doesn't allow for wildcarding a subdomain. Specifically see https://www.w3.org/TR/cors/#access-control-allow-origin-response-header



          You could follow their advice on that answer and move the processing into some middleware layer like NGINX or Apache which could set the CORS header dynamically based on the domain in the request, or specify all the the subdomains you'd want in the spring boot config if that doesn't total into an unmanageable amount.



          Although, in the first part of your question you state that you accept requests from http://localhost:4200., this shouldn't be a problem if you don't need subdomains then you can just explicitly whitelist that one domain, or did I misunderstand?






          share|improve this answer


























          • Basically, all our other services accept sub-domains, so this is why I'm trying to find a solution for this new service. Yep so I need something like something.localhost:4200 to be accepted. There are some solution like CrossOriginFilter from org.eclipse.jetty.servlets, but we are not any more into a Servlet stack. We started this new service with spring WebFlux so we are in a reactive stack and that solution doesn't work anymore..

            – brebDev
            Nov 21 '18 at 13:46











          • I see, I think the main point is that you can't use a header value of http://*.localhost:4200. You can achieve your end goal, but you'd either have to explicitly tell spring all of the permitted subdomains or implement some more custom solution to intercept the request, determine the origin header value, decide whether it's permitted for CORS and if so append the relevant header to the response. You might be able to write your own interceptor for this rather than using the spring cors features. I'm not aware of any built in feature of spring to allow that out of the box.

            – David Goate
            Nov 21 '18 at 14:02













          • I think I managed to find out a solution. Please take a look above.

            – brebDev
            Nov 22 '18 at 14:55



















          0














          I think I found a solution that works. That simply means creating a custom CorsConfiguration, overriding the checkOrigin method and create a custom matcher that will interpret http://*.localhost:4200 correctly. The code looks like this:



          public class RegexCorsConfiguration extends CorsConfiguration {

          private List<String> allowedOriginsRegexes = new ArrayList<>();

          /**
          * Check the origin of the request against the configured allowed origins.
          * @param requestOrigin the origin to check
          * @return the origin to use for the response, possibly {@code null} which
          * means the request origin is not allowed
          */
          public String checkOrigin(String requestOrigin) {
          if (!StringUtils.hasText(requestOrigin)) {
          return null;
          }

          if (this.allowedOriginsRegexes.isEmpty()) {
          return null;
          }

          if (this.allowedOriginsRegexes.contains(ALL)) {
          if (getAllowCredentials() != Boolean.TRUE) {
          return ALL;
          } else {
          return requestOrigin;
          }
          }

          for (String allowedOriginRegex : this.allowedOriginsRegexes) {
          if (createMatcher(requestOrigin, allowedOriginRegex).matches()) {
          return requestOrigin;
          }
          }

          return null;
          }

          public void setAllowedOriginRegex(List<String> allowedOriginsRegexes) {
          this.allowedOriginsRegexes = allowedOriginsRegexes;
          }

          private Matcher createMatcher(String origin, String allowedOrigin) {
          String regex = this.parseAllowedWildcardOriginToRegex(allowedOrigin);
          Pattern pattern = Pattern.compile(regex);
          return pattern.matcher(origin);
          }

          private String parseAllowedWildcardOriginToRegex(String allowedOrigin) {
          String regex = allowedOrigin.replace(".", "\.");
          return regex.replace("*", ".*");
          }}


          and of course, inject corsConfig from configuration classes like this:



              @Bean
          @Order(Ordered.HIGHEST_PRECEDENCE)
          public CorsWebFilter corsFilter() {
          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
          RegexCorsConfiguration regexCorsConfiguration = new RegexCorsConfiguration();
          regexCorsConfiguration.setAllowCredentials(true);

          regexCorsConfiguration.setAllowedOriginRegex(corsConfigData.getAllowedOrigins());
          regexCorsConfiguration.setAllowedHeaders(corsConfigData.getAllowedHeaders());
          regexCorsConfiguration.setAllowedMethods(corsConfigData.getAllowedMethods());

          source.registerCorsConfiguration("/**", regexCorsConfiguration);
          return new CorsWebFilter(source);
          }





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53412178%2fenable-wildcard-in-cors-spring-security-webflux%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            I think, as indicated in responses to this question, the CORS specification doesn't allow for wildcarding a subdomain. Specifically see https://www.w3.org/TR/cors/#access-control-allow-origin-response-header



            You could follow their advice on that answer and move the processing into some middleware layer like NGINX or Apache which could set the CORS header dynamically based on the domain in the request, or specify all the the subdomains you'd want in the spring boot config if that doesn't total into an unmanageable amount.



            Although, in the first part of your question you state that you accept requests from http://localhost:4200., this shouldn't be a problem if you don't need subdomains then you can just explicitly whitelist that one domain, or did I misunderstand?






            share|improve this answer


























            • Basically, all our other services accept sub-domains, so this is why I'm trying to find a solution for this new service. Yep so I need something like something.localhost:4200 to be accepted. There are some solution like CrossOriginFilter from org.eclipse.jetty.servlets, but we are not any more into a Servlet stack. We started this new service with spring WebFlux so we are in a reactive stack and that solution doesn't work anymore..

              – brebDev
              Nov 21 '18 at 13:46











            • I see, I think the main point is that you can't use a header value of http://*.localhost:4200. You can achieve your end goal, but you'd either have to explicitly tell spring all of the permitted subdomains or implement some more custom solution to intercept the request, determine the origin header value, decide whether it's permitted for CORS and if so append the relevant header to the response. You might be able to write your own interceptor for this rather than using the spring cors features. I'm not aware of any built in feature of spring to allow that out of the box.

              – David Goate
              Nov 21 '18 at 14:02













            • I think I managed to find out a solution. Please take a look above.

              – brebDev
              Nov 22 '18 at 14:55
















            2














            I think, as indicated in responses to this question, the CORS specification doesn't allow for wildcarding a subdomain. Specifically see https://www.w3.org/TR/cors/#access-control-allow-origin-response-header



            You could follow their advice on that answer and move the processing into some middleware layer like NGINX or Apache which could set the CORS header dynamically based on the domain in the request, or specify all the the subdomains you'd want in the spring boot config if that doesn't total into an unmanageable amount.



            Although, in the first part of your question you state that you accept requests from http://localhost:4200., this shouldn't be a problem if you don't need subdomains then you can just explicitly whitelist that one domain, or did I misunderstand?






            share|improve this answer


























            • Basically, all our other services accept sub-domains, so this is why I'm trying to find a solution for this new service. Yep so I need something like something.localhost:4200 to be accepted. There are some solution like CrossOriginFilter from org.eclipse.jetty.servlets, but we are not any more into a Servlet stack. We started this new service with spring WebFlux so we are in a reactive stack and that solution doesn't work anymore..

              – brebDev
              Nov 21 '18 at 13:46











            • I see, I think the main point is that you can't use a header value of http://*.localhost:4200. You can achieve your end goal, but you'd either have to explicitly tell spring all of the permitted subdomains or implement some more custom solution to intercept the request, determine the origin header value, decide whether it's permitted for CORS and if so append the relevant header to the response. You might be able to write your own interceptor for this rather than using the spring cors features. I'm not aware of any built in feature of spring to allow that out of the box.

              – David Goate
              Nov 21 '18 at 14:02













            • I think I managed to find out a solution. Please take a look above.

              – brebDev
              Nov 22 '18 at 14:55














            2












            2








            2







            I think, as indicated in responses to this question, the CORS specification doesn't allow for wildcarding a subdomain. Specifically see https://www.w3.org/TR/cors/#access-control-allow-origin-response-header



            You could follow their advice on that answer and move the processing into some middleware layer like NGINX or Apache which could set the CORS header dynamically based on the domain in the request, or specify all the the subdomains you'd want in the spring boot config if that doesn't total into an unmanageable amount.



            Although, in the first part of your question you state that you accept requests from http://localhost:4200., this shouldn't be a problem if you don't need subdomains then you can just explicitly whitelist that one domain, or did I misunderstand?






            share|improve this answer















            I think, as indicated in responses to this question, the CORS specification doesn't allow for wildcarding a subdomain. Specifically see https://www.w3.org/TR/cors/#access-control-allow-origin-response-header



            You could follow their advice on that answer and move the processing into some middleware layer like NGINX or Apache which could set the CORS header dynamically based on the domain in the request, or specify all the the subdomains you'd want in the spring boot config if that doesn't total into an unmanageable amount.



            Although, in the first part of your question you state that you accept requests from http://localhost:4200., this shouldn't be a problem if you don't need subdomains then you can just explicitly whitelist that one domain, or did I misunderstand?







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 21 '18 at 13:45

























            answered Nov 21 '18 at 13:37









            David GoateDavid Goate

            1,16721537




            1,16721537













            • Basically, all our other services accept sub-domains, so this is why I'm trying to find a solution for this new service. Yep so I need something like something.localhost:4200 to be accepted. There are some solution like CrossOriginFilter from org.eclipse.jetty.servlets, but we are not any more into a Servlet stack. We started this new service with spring WebFlux so we are in a reactive stack and that solution doesn't work anymore..

              – brebDev
              Nov 21 '18 at 13:46











            • I see, I think the main point is that you can't use a header value of http://*.localhost:4200. You can achieve your end goal, but you'd either have to explicitly tell spring all of the permitted subdomains or implement some more custom solution to intercept the request, determine the origin header value, decide whether it's permitted for CORS and if so append the relevant header to the response. You might be able to write your own interceptor for this rather than using the spring cors features. I'm not aware of any built in feature of spring to allow that out of the box.

              – David Goate
              Nov 21 '18 at 14:02













            • I think I managed to find out a solution. Please take a look above.

              – brebDev
              Nov 22 '18 at 14:55



















            • Basically, all our other services accept sub-domains, so this is why I'm trying to find a solution for this new service. Yep so I need something like something.localhost:4200 to be accepted. There are some solution like CrossOriginFilter from org.eclipse.jetty.servlets, but we are not any more into a Servlet stack. We started this new service with spring WebFlux so we are in a reactive stack and that solution doesn't work anymore..

              – brebDev
              Nov 21 '18 at 13:46











            • I see, I think the main point is that you can't use a header value of http://*.localhost:4200. You can achieve your end goal, but you'd either have to explicitly tell spring all of the permitted subdomains or implement some more custom solution to intercept the request, determine the origin header value, decide whether it's permitted for CORS and if so append the relevant header to the response. You might be able to write your own interceptor for this rather than using the spring cors features. I'm not aware of any built in feature of spring to allow that out of the box.

              – David Goate
              Nov 21 '18 at 14:02













            • I think I managed to find out a solution. Please take a look above.

              – brebDev
              Nov 22 '18 at 14:55

















            Basically, all our other services accept sub-domains, so this is why I'm trying to find a solution for this new service. Yep so I need something like something.localhost:4200 to be accepted. There are some solution like CrossOriginFilter from org.eclipse.jetty.servlets, but we are not any more into a Servlet stack. We started this new service with spring WebFlux so we are in a reactive stack and that solution doesn't work anymore..

            – brebDev
            Nov 21 '18 at 13:46





            Basically, all our other services accept sub-domains, so this is why I'm trying to find a solution for this new service. Yep so I need something like something.localhost:4200 to be accepted. There are some solution like CrossOriginFilter from org.eclipse.jetty.servlets, but we are not any more into a Servlet stack. We started this new service with spring WebFlux so we are in a reactive stack and that solution doesn't work anymore..

            – brebDev
            Nov 21 '18 at 13:46













            I see, I think the main point is that you can't use a header value of http://*.localhost:4200. You can achieve your end goal, but you'd either have to explicitly tell spring all of the permitted subdomains or implement some more custom solution to intercept the request, determine the origin header value, decide whether it's permitted for CORS and if so append the relevant header to the response. You might be able to write your own interceptor for this rather than using the spring cors features. I'm not aware of any built in feature of spring to allow that out of the box.

            – David Goate
            Nov 21 '18 at 14:02







            I see, I think the main point is that you can't use a header value of http://*.localhost:4200. You can achieve your end goal, but you'd either have to explicitly tell spring all of the permitted subdomains or implement some more custom solution to intercept the request, determine the origin header value, decide whether it's permitted for CORS and if so append the relevant header to the response. You might be able to write your own interceptor for this rather than using the spring cors features. I'm not aware of any built in feature of spring to allow that out of the box.

            – David Goate
            Nov 21 '18 at 14:02















            I think I managed to find out a solution. Please take a look above.

            – brebDev
            Nov 22 '18 at 14:55





            I think I managed to find out a solution. Please take a look above.

            – brebDev
            Nov 22 '18 at 14:55













            0














            I think I found a solution that works. That simply means creating a custom CorsConfiguration, overriding the checkOrigin method and create a custom matcher that will interpret http://*.localhost:4200 correctly. The code looks like this:



            public class RegexCorsConfiguration extends CorsConfiguration {

            private List<String> allowedOriginsRegexes = new ArrayList<>();

            /**
            * Check the origin of the request against the configured allowed origins.
            * @param requestOrigin the origin to check
            * @return the origin to use for the response, possibly {@code null} which
            * means the request origin is not allowed
            */
            public String checkOrigin(String requestOrigin) {
            if (!StringUtils.hasText(requestOrigin)) {
            return null;
            }

            if (this.allowedOriginsRegexes.isEmpty()) {
            return null;
            }

            if (this.allowedOriginsRegexes.contains(ALL)) {
            if (getAllowCredentials() != Boolean.TRUE) {
            return ALL;
            } else {
            return requestOrigin;
            }
            }

            for (String allowedOriginRegex : this.allowedOriginsRegexes) {
            if (createMatcher(requestOrigin, allowedOriginRegex).matches()) {
            return requestOrigin;
            }
            }

            return null;
            }

            public void setAllowedOriginRegex(List<String> allowedOriginsRegexes) {
            this.allowedOriginsRegexes = allowedOriginsRegexes;
            }

            private Matcher createMatcher(String origin, String allowedOrigin) {
            String regex = this.parseAllowedWildcardOriginToRegex(allowedOrigin);
            Pattern pattern = Pattern.compile(regex);
            return pattern.matcher(origin);
            }

            private String parseAllowedWildcardOriginToRegex(String allowedOrigin) {
            String regex = allowedOrigin.replace(".", "\.");
            return regex.replace("*", ".*");
            }}


            and of course, inject corsConfig from configuration classes like this:



                @Bean
            @Order(Ordered.HIGHEST_PRECEDENCE)
            public CorsWebFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            RegexCorsConfiguration regexCorsConfiguration = new RegexCorsConfiguration();
            regexCorsConfiguration.setAllowCredentials(true);

            regexCorsConfiguration.setAllowedOriginRegex(corsConfigData.getAllowedOrigins());
            regexCorsConfiguration.setAllowedHeaders(corsConfigData.getAllowedHeaders());
            regexCorsConfiguration.setAllowedMethods(corsConfigData.getAllowedMethods());

            source.registerCorsConfiguration("/**", regexCorsConfiguration);
            return new CorsWebFilter(source);
            }





            share|improve this answer




























              0














              I think I found a solution that works. That simply means creating a custom CorsConfiguration, overriding the checkOrigin method and create a custom matcher that will interpret http://*.localhost:4200 correctly. The code looks like this:



              public class RegexCorsConfiguration extends CorsConfiguration {

              private List<String> allowedOriginsRegexes = new ArrayList<>();

              /**
              * Check the origin of the request against the configured allowed origins.
              * @param requestOrigin the origin to check
              * @return the origin to use for the response, possibly {@code null} which
              * means the request origin is not allowed
              */
              public String checkOrigin(String requestOrigin) {
              if (!StringUtils.hasText(requestOrigin)) {
              return null;
              }

              if (this.allowedOriginsRegexes.isEmpty()) {
              return null;
              }

              if (this.allowedOriginsRegexes.contains(ALL)) {
              if (getAllowCredentials() != Boolean.TRUE) {
              return ALL;
              } else {
              return requestOrigin;
              }
              }

              for (String allowedOriginRegex : this.allowedOriginsRegexes) {
              if (createMatcher(requestOrigin, allowedOriginRegex).matches()) {
              return requestOrigin;
              }
              }

              return null;
              }

              public void setAllowedOriginRegex(List<String> allowedOriginsRegexes) {
              this.allowedOriginsRegexes = allowedOriginsRegexes;
              }

              private Matcher createMatcher(String origin, String allowedOrigin) {
              String regex = this.parseAllowedWildcardOriginToRegex(allowedOrigin);
              Pattern pattern = Pattern.compile(regex);
              return pattern.matcher(origin);
              }

              private String parseAllowedWildcardOriginToRegex(String allowedOrigin) {
              String regex = allowedOrigin.replace(".", "\.");
              return regex.replace("*", ".*");
              }}


              and of course, inject corsConfig from configuration classes like this:



                  @Bean
              @Order(Ordered.HIGHEST_PRECEDENCE)
              public CorsWebFilter corsFilter() {
              UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
              RegexCorsConfiguration regexCorsConfiguration = new RegexCorsConfiguration();
              regexCorsConfiguration.setAllowCredentials(true);

              regexCorsConfiguration.setAllowedOriginRegex(corsConfigData.getAllowedOrigins());
              regexCorsConfiguration.setAllowedHeaders(corsConfigData.getAllowedHeaders());
              regexCorsConfiguration.setAllowedMethods(corsConfigData.getAllowedMethods());

              source.registerCorsConfiguration("/**", regexCorsConfiguration);
              return new CorsWebFilter(source);
              }





              share|improve this answer


























                0












                0








                0







                I think I found a solution that works. That simply means creating a custom CorsConfiguration, overriding the checkOrigin method and create a custom matcher that will interpret http://*.localhost:4200 correctly. The code looks like this:



                public class RegexCorsConfiguration extends CorsConfiguration {

                private List<String> allowedOriginsRegexes = new ArrayList<>();

                /**
                * Check the origin of the request against the configured allowed origins.
                * @param requestOrigin the origin to check
                * @return the origin to use for the response, possibly {@code null} which
                * means the request origin is not allowed
                */
                public String checkOrigin(String requestOrigin) {
                if (!StringUtils.hasText(requestOrigin)) {
                return null;
                }

                if (this.allowedOriginsRegexes.isEmpty()) {
                return null;
                }

                if (this.allowedOriginsRegexes.contains(ALL)) {
                if (getAllowCredentials() != Boolean.TRUE) {
                return ALL;
                } else {
                return requestOrigin;
                }
                }

                for (String allowedOriginRegex : this.allowedOriginsRegexes) {
                if (createMatcher(requestOrigin, allowedOriginRegex).matches()) {
                return requestOrigin;
                }
                }

                return null;
                }

                public void setAllowedOriginRegex(List<String> allowedOriginsRegexes) {
                this.allowedOriginsRegexes = allowedOriginsRegexes;
                }

                private Matcher createMatcher(String origin, String allowedOrigin) {
                String regex = this.parseAllowedWildcardOriginToRegex(allowedOrigin);
                Pattern pattern = Pattern.compile(regex);
                return pattern.matcher(origin);
                }

                private String parseAllowedWildcardOriginToRegex(String allowedOrigin) {
                String regex = allowedOrigin.replace(".", "\.");
                return regex.replace("*", ".*");
                }}


                and of course, inject corsConfig from configuration classes like this:



                    @Bean
                @Order(Ordered.HIGHEST_PRECEDENCE)
                public CorsWebFilter corsFilter() {
                UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
                RegexCorsConfiguration regexCorsConfiguration = new RegexCorsConfiguration();
                regexCorsConfiguration.setAllowCredentials(true);

                regexCorsConfiguration.setAllowedOriginRegex(corsConfigData.getAllowedOrigins());
                regexCorsConfiguration.setAllowedHeaders(corsConfigData.getAllowedHeaders());
                regexCorsConfiguration.setAllowedMethods(corsConfigData.getAllowedMethods());

                source.registerCorsConfiguration("/**", regexCorsConfiguration);
                return new CorsWebFilter(source);
                }





                share|improve this answer













                I think I found a solution that works. That simply means creating a custom CorsConfiguration, overriding the checkOrigin method and create a custom matcher that will interpret http://*.localhost:4200 correctly. The code looks like this:



                public class RegexCorsConfiguration extends CorsConfiguration {

                private List<String> allowedOriginsRegexes = new ArrayList<>();

                /**
                * Check the origin of the request against the configured allowed origins.
                * @param requestOrigin the origin to check
                * @return the origin to use for the response, possibly {@code null} which
                * means the request origin is not allowed
                */
                public String checkOrigin(String requestOrigin) {
                if (!StringUtils.hasText(requestOrigin)) {
                return null;
                }

                if (this.allowedOriginsRegexes.isEmpty()) {
                return null;
                }

                if (this.allowedOriginsRegexes.contains(ALL)) {
                if (getAllowCredentials() != Boolean.TRUE) {
                return ALL;
                } else {
                return requestOrigin;
                }
                }

                for (String allowedOriginRegex : this.allowedOriginsRegexes) {
                if (createMatcher(requestOrigin, allowedOriginRegex).matches()) {
                return requestOrigin;
                }
                }

                return null;
                }

                public void setAllowedOriginRegex(List<String> allowedOriginsRegexes) {
                this.allowedOriginsRegexes = allowedOriginsRegexes;
                }

                private Matcher createMatcher(String origin, String allowedOrigin) {
                String regex = this.parseAllowedWildcardOriginToRegex(allowedOrigin);
                Pattern pattern = Pattern.compile(regex);
                return pattern.matcher(origin);
                }

                private String parseAllowedWildcardOriginToRegex(String allowedOrigin) {
                String regex = allowedOrigin.replace(".", "\.");
                return regex.replace("*", ".*");
                }}


                and of course, inject corsConfig from configuration classes like this:



                    @Bean
                @Order(Ordered.HIGHEST_PRECEDENCE)
                public CorsWebFilter corsFilter() {
                UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
                RegexCorsConfiguration regexCorsConfiguration = new RegexCorsConfiguration();
                regexCorsConfiguration.setAllowCredentials(true);

                regexCorsConfiguration.setAllowedOriginRegex(corsConfigData.getAllowedOrigins());
                regexCorsConfiguration.setAllowedHeaders(corsConfigData.getAllowedHeaders());
                regexCorsConfiguration.setAllowedMethods(corsConfigData.getAllowedMethods());

                source.registerCorsConfiguration("/**", regexCorsConfiguration);
                return new CorsWebFilter(source);
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 22 '18 at 14:54









                brebDevbrebDev

                13210




                13210






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53412178%2fenable-wildcard-in-cors-spring-security-webflux%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                    Alcedinidae

                    RAC Tourist Trophy