0

I'm developing a spring boot application with jhipster V4.5.6. But unable to configure CORS.

Here is my application-dev.yml file:

 # CORS is only enabled by default with the "dev" profile, so BrowserSync can access the API
cors:
    allowed-origins: "http://localhost:9000"
    allowed-methods: GET, PUT, POST, DELETE, OPTIONS
    allowed-headers: "*"
    exposed-headers:
    allow-credentials: true
    max-age: 1800

The WebConfigurer.java is as below:

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = jHipsterProperties.getCors();
    if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
        log.debug("Registering CORS filter");
        source.registerCorsConfiguration("/api/**", config);
        source.registerCorsConfiguration("/v2/api-docs", config);
    }
    return new CorsFilter(source);
}

And SecurityConfiguration.java file is as follows:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
        .antMatchers(HttpMethod.OPTIONS, "/**")
        .antMatchers("/test/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    .and()
        .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
        .exceptionHandling()
        .authenticationEntryPoint(http401UnauthorizedEntryPoint())
    .and()
        .authorizeRequests()
        ... //Some project specific configuration
}

Now, I'm able to work with GET request. But when I use POST as below:

private demoCors(restUrl: string, input: any): Observable<Result> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(restUrl, JSON.stringify(input), options)
    .map(this.extractData)
    .catch(this.handleError);
}

I'm getting the following error:

POST http://localhost:8080/api/dth 403 (Forbidden)

XMLHttpRequest cannot load http://localhost:8080/api/dth. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 403.

Can anyone suggest how to fix it?

Arif Rabbani
  • 131
  • 1
  • 2
  • 12
  • You need to set a CORS Filter to allow your localhost to connect, please check this. [link](https://stackoverflow.com/questions/37516755/spring-boot-rest-service-options-401-on-oauth-token/37517389#37517389) – Paulo Galdo Sandoval Jul 07 '17 at 05:38
  • It's already been set. `@Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); }` – Arif Rabbani Jul 07 '17 at 05:43
  • You do not have the Access-Control-Allow-Origin and Access-Control-Allow-Methods headers – jorrin Jul 07 '17 at 07:12
  • @jorrin, Access-Control-Allow-Origin and Access-Control-Allow-Methods headers are there in the response. I'm getting the response for OPTION request as follows: `Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:content-type, x-xsrf-token Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS Access-Control-Allow-Origin:http://localhost:9000 Access-Control-Max-Age:1800 Connection:keep-alive Content-Length:0 Date:Fri, 07 Jul 2017 08:13:57 GMT Vary:Origin` – Arif Rabbani Jul 07 '17 at 08:19
  • Sorry but I cannot see where the Access-Control-Allow-Origin header is – jorrin Jul 07 '17 at 08:24
  • @jorrin, `Access-Control-Allow-Origin:http://localhost:9000 Access-Control-Max-Age:1800` – Arif Rabbani Jul 07 '17 at 08:25
  • @jorrin, I'm new to cors. I may have miss something – Arif Rabbani Jul 07 '17 at 08:26
  • I have fixed the problem.. Thanks everyone for your suggestions – Arif Rabbani Jul 07 '17 at 19:49

1 Answers1

-1

Can you try this.

# CORS is only enabled by default with the "dev" profile, so BrowserSync can access the API
cors:
    allowed-origins: "*"
    allowed-methods: GET, PUT, POST, DELETE, OPTIONS
    allowed-headers: "*"
    exposed-headers:
    allow-credentials: true
    max-age: 1800
Sumit Vairagar
  • 486
  • 3
  • 12