Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Cloud - Zuul Proxy is producing a No 'Access-Control-Allow-Origin' ajax response

Startup Appplication:

@SpringBootApplication
@EnableZuulProxy
public class ZuulServer {

     public static void main(String[] args) {
         new SpringApplicationBuilder(ZuulServer.class).web(true).run(args);
     }
 }

My YAML file is like this:

server:
   port:8080

spring:
   application:
      name: zuul

eureka:
client:
  enabled: true
    serviceUrl:
       defaultZone: http://localhost:8761/eureka/



zuul:
    proxy:
       route:
         springapp: /springapp

I have a microservice application (on port 8081) called springapp and has some rest services. Below is my client UI app:

    <html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="text/javascript" src="js/libs/jquery/jquery.min.js" ></script>
    </head>
    <body>
        <script type="text/javascript">
            $.ajax({
                url: 'http://localhost:8080/zuul/springapp/departments',
                type: 'GET'
            }).done(function (data) {
                consoe.log(data);
                document.write(data);
            });
        </script>        

    </body>
</html>

But I get a

XMLHttpRequest cannot load http://localhost:8080/zuul/springapp/departments. No
    'Access-Control-Allow-Origin' header is present on the requested
    resource. Origin 'http://localhost:8383' is therefore not allowed access.

This UI HTML5 app is on http://localhost:8383/SimpleAPp/index.html. CORS, CORS, CORS... Please help. BTW the http://localhost:8080/zuul/springapp/departments returns a json list as supposed to when on the browser address bar. The spring.io blog here says that there is no need for a filter because the zuulproxy takes care of that but I don't know why it is not working for me.

like image 576
Given Avatar asked Feb 23 '15 09:02

Given


People also ask

How do I enable Zuul proxy?

Creating Zuul Server ApplicationAdd the @EnableZuulProxy annotation on your main Spring Boot application. The @EnableZuulProxy annotation is used to make your Spring Boot application act as a Zuul Proxy server. You will have to add the Spring Cloud Starter Zuul dependency in our build configuration file.

Can Zuul work without Eureka?

GitHub - rishabhverma17/microservice-zuul-without-eureka: This service can be used to create microservice architecture with Gateway/Reverse Proxy using Zuul without using Eureka. This service can be used to create microservice architecture with Gateway/Reverse Proxy using Zuul without using Eureka.

Is Zuul supported by spring cloud?

Zuul is built on servlet 2.5 (works with 3. x), using blocking APIs. It doesn't support any long lived connections, like websockets. Gateway is built on Spring Framework 5, Project Reactor and Spring Boot 2 using non-blocking APIs.

What can I use instead of Zuul?

Apigee, Eureka, Kong, HAProxy, and Istio are the most popular alternatives and competitors to Zuul.


2 Answers

Adding this piece of code to your class annotated with @EnableZuulProxy should do the trick.

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("OPTIONS");
    config.addAllowedMethod("HEAD");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("DELETE");
    config.addAllowedMethod("PATCH");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}
like image 126
Grinish Nepal Avatar answered Oct 23 '22 03:10

Grinish Nepal


I had a similar problem, with Angular Web app consuming RESTful services implemented by Spring Boot with Zuul and Spring Security.

None of the above solutions worked. I realized that the problem was NOT in Zuul, but in Spring Security.

As the official documentation (CORS with Spring Security) states, when using Spring Security, CORS must be configured prior to Spring Security.

Finally, I was able to integrate Grinish Nepal's (see prior answers) solution into a solution that works.

Without further ado, here is the code that enables CORS with Spring Security and Zuul:


    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        //irrelevant for this problem
        @Autowired
        private MyBasicAuthenticationEntryPoint authenticationEntryPoint;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    //configure CORS -- uses a Bean by the name of     corsConfigurationSource (see method below)
                    //CORS must be configured prior to Spring Security
                    .cors().and()
                    //configuring security - irrelevant for this problem
                    .authorizeRequests()
                        .anyRequest().authenticated()
                        .and()
                    .httpBasic()
                    .authenticationEntryPoint(authenticationEntryPoint);

            //irrelevant for this problem
            http.addFilterAfter(new CustomFilter(),
                    BasicAuthenticationFilter.class);
        }

        //The CORS filter bean - Configures allowed CORS any (source) to any 
        //(api route and method) endpoint
        @Bean
        CorsConfigurationSource corsConfigurationSource() {
            final UrlBasedCorsConfigurationSource source = new     UrlBasedCorsConfigurationSource();
            final CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.addAllowedOrigin(CorsConfiguration.ALL);
            config.addAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL));
            config.addAllowedMethod("OPTIONS");
            config.addAllowedMethod("HEAD");
            config.addAllowedMethod("GET");
            config.addAllowedMethod("PUT");
            config.addAllowedMethod("POST");
            config.addAllowedMethod("DELETE");
            config.addAllowedMethod("PATCH");
            source.registerCorsConfiguration("/**", config);
            return source;
        }

        //configuring BA usernames and passwords - irrelevant for this problem
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws     Exception {
           ...
        }
    }
like image 6
Mate Šimović Avatar answered Oct 23 '22 04:10

Mate Šimović