0

Getting below error when running the Angular+Spring boot application in localhost by disabling csrf() and enabling OPTION requests

Error- Access to XMLHttpRequest at 'http://localhost:8080/hello/variable/paraan' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

GET http://localhost:8080/hello/variable/user net::ERR_FAILED zone-evergreen.js:2845

Angular welcome-data.service.ts

executeHelloWorldBeanServicePathVarible(name)
  {
    let basicAuthHeaderString=this.createBasicAuthenticationHttpHeader();
    let headers=new HttpHeaders({
      Authorization:basicAuthHeaderString
    })
   
    return this.http.get<helloWorldBean>
    (`http://localhost:8080/hello/variable/${name}`,
    {headers});
  }

  createBasicAuthenticationHttpHeader(){
    let username='user'
    let password='dummy'
    
    let basicAuthHeaderString='Basic' + window.btoa(username + ':' + password);
    
    return basicAuthHeaderString;
    
      } 

SpringSecurityConfigurationBasicAuth.java

package com.practice.rest.webservices.restfulwebservices.basic.auth;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.bind.annotation.CrossOrigin;

@Configuration
@EnableWebSecurity 
  public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{
  
  @Override
  protected void configure(HttpSecurity http) throws Exception {
  
  http
  .csrf().disable()
  .authorizeRequests()
  .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
  .anyRequest().authenticated() 
  .and() 
  //.formLogin().and() 
  .httpBasic(); 
  }
  
  }
 

Edited the SpringSecurityConfigurationBasicAuth.java

package com.practice.rest.webservices.restfulwebservices.basic.auth;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .csrf().disable()   
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .anyRequest().authenticated()
                .and()
            //.formLogin().and()
            .httpBasic();
    }
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin(CorsConfiguration.ALL);
        config.addAllowedHeader("*");
        config.addExposedHeader("Authorization");
        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);
    }
}
Harry
  • 65
  • 1
  • 2
  • 9
  • Added the code in SpringSecurityConfigurationBasicAuth class and also updated the cross origin as @CrossOrigin(origins="*") but still getting the error – Harry Sep 12 '20 at 16:36
  • OPTIONS API is getting pass with 200 status code but getting one more request-Request URL: http://localhost:8080/hello/variable/paraan Referrer Policy: no-referrer-when-downgrade – Harry Sep 12 '20 at 16:39
  • for Referrer Policy , look at [this](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy) it might help – Thakur Amit Sep 12 '20 at 16:44
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/221384/discussion-between-thakur-amit-and-harry). – Thakur Amit Sep 12 '20 at 16:52
  • still getting cors error not working – Harry Sep 12 '20 at 16:54
  • Now zone-evergreen.js:2845 GET http://localhost:8080 /hello/variable/paraan net::ERR_CONNECTION_REFUSED is coming after adding SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) in SpringSecurityConfigurationBasicAuth.java – Harry Sep 12 '20 at 17:16
  • `.and().headers().referrerPolicy(ReferrerPolicy.NO_REFERRER);` add this into configure and remove the earlier code. import from `org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy` – Thakur Amit Sep 12 '20 at 17:37
  • I added the .cors() in SpringSecurityConfigurationBasicAuth.java. Now I am not getting Access-Control-Allow-Origin error but getting core.js:4197 ERROR TypeError: Cannot read property 'message' of null error – Harry Sep 13 '20 at 08:53
  • Code is working fine and there is no CORS or ERR_Failed error coming but OPTIONS API is not getting called only GET API is called. If there is spring security then OPTION should be called then GET API. Please correct me if my understanding is wrong? – Harry Sep 13 '20 at 11:44

3 Answers3

0

You have to enable CORS support with CrossOrigin annotation or with Java config.

For more information visit this link:

CORS support in Spring Framework

You can add to your @RequestMapping annotated handler method a @CrossOrigin annotation in order to enable CORS on it (by default @CrossOrigin allows all origins and the HTTP methods specified in the @RequestMapping annotation):

@RestController
@RequestMapping("/account")
public class AccountController {

    @CrossOrigin
    @GetMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

It is also possible to enable CORS for the whole controller:

@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

    @GetMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}
ng-hobby
  • 2,077
  • 2
  • 13
  • 26
  • I had already enable it in my RestController class but still getting error-@CrossOrigin(origins="http://localhost:4200") – Harry Sep 12 '20 at 16:21
  • You error is because of the CORS. Try this: change it to `@CrossOrigin(origins="*")` – ng-hobby Sep 12 '20 at 16:26
0

Just add the CorsFilter bean

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin(CorsConfiguration.ALL);
        config.addAllowedHeader("*");
        config.addExposedHeader("Authorization");
        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);
    }
Thakur Amit
  • 357
  • 1
  • 4
  • 12
0

add this into your code.

@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http.headers()
        .referrerPolicy(ReferrerPolicy.NO_REFERRER);
    return http.build();
}
Thakur Amit
  • 357
  • 1
  • 4
  • 12