Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS issue with Spring Boot

I have a Spring Boot application running on port 8443, and an angular2 based front end on port 8080. I need my front end to make requests to my Spring server, but I'm getting CORS errors left and right. I have added the @CrossOrigin annotation to my RestController method, and I have added a CORSFilter to my project, and mapped it on web.xml, but on Firefox 46.0a2 I still get this error on the console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8443/allEquips. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

The relevant part of my controller:

@CrossOrigin
@RequestMapping("/allequips")
List<String> allequips(Model model) {
    List<String> codes = equipmentRepository.findAllEquipments();
    return codes;
}

The CORSFilter:

public class CORSFilter implements Filter{
     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            chain.doFilter(req, res);
        }
        public void init(FilterConfig filterConfig) {}
        public void destroy() {}
}

The mapping on web.xml:

  <filter>
  <filter-name>cors</filter-name>
  <filter-class>config.CORSFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>cors</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

And I don't know if this is important, but the Angular2 code that's making the http request:

@Injectable()
export class EquipService {
    equips: Array<Equip>;

    constructor(public http: Http) {
        console.log('Equip service created.', http);
    }

    getEquips() {
        return this.http.get(WebServiceEndPoint+'allEquips')
        .map((responseData) => {
            return responseData.json();
        }).map((equips: Array<any>) => {
            let result: Array<Equip> = [];
            if(equips) {
                equips.forEach((equip) => {
                    result.push(new Equip(equip.code));
                });
            }
            return result;
        }).subscribe( res => this.equips = res);
    }
}

Am I missing some configuration? Is my code wrong in any way?

EDIT: I gave up and restarted from a previous commit. After that, simply adding @Cross-Origin was enough.

like image 290
napstablook Avatar asked Mar 22 '16 19:03

napstablook


People also ask

How do you resolve CORS issue in Spring boot application?

To code to set the CORS configuration globally in main Spring Boot application is given below. Now, you can create a Spring Boot web application that runs on 8080 port and your RESTful web service application that can run on the 9090 port.

Is CORS enabled by default in Spring boot?

No. You need to add @CrossOrigin annotation by yourself to get CORS Support in Spring.

How do I fix the CORS error?

Short description. Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.

How do I enable Cors in Spring Boot?

You can find the spring-boot-angular-scaffolding project repository on GitHub. Add the DevCorsConfiguration class to your config directory: This configuration enables CORS requests from any origin to the api/ endpoint in the application.

Why do we need to implement Cors in spring?

This is required since browsers by default apply the same-origin policy for security . By implementing CORS in a web application, a webpage could request additional resources and load into the browser from other domains. This article will focus on the various ways in which CORS can be implemented in a Spring-based application.

What is the default Cors configuration for Spring MVC?

In addition (or as an alternative) to fine-grained annotation-based configuration, you can define some global CORS configuration as well. This is similar to using a Filter but can be declared within Spring MVC and combined with fine-grained @CrossOrigin configuration. By default, all origins and GET, HEAD, and POST methods are allowed.

Why Cors request is not allowed in modern browsers?

In modern browsers due to security reasons cross-origin HTTP request is not allowed. Whenever there is a CORS request browser will send a preflight request prior to sending the actual request to find out whether CORS request is valid or not.


1 Answers

First Approach:- If you are using spring boot then create a new class that extends WebMvcConfigurerAdapter

 @Configuration
 @ComponentScan
 @EnableWebMvc

 public class ApplicationConfig extends WebMvcConfigurerAdapter {

     @Override
   public void addCorsMappings(CorsRegistry registry) {
   // Can just allow `methods` that you need.
   registry.addMapping("/**").allowedMethods("PUT", "GET", "DELETE", "OPTIONS", "PATCH", "POST");
    }
}

Second Approach:- Also you can add this in the @SpringBootApplication annotated class. No xml needed. origin, headers, methods etc are all configurable based on your needs.

@Bean
     public CorsFilter corsFilter() {
         final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
         final CorsConfiguration config = new CorsConfiguration();
         config.setAllowCredentials(true);
         config.addAllowedOrigin("*"); // this allows all origin
         config.addAllowedHeader("*"); // this allows all headers
         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 169
Grinish Nepal Avatar answered Oct 19 '22 17:10

Grinish Nepal