2

I'm using spring boot for the first time in a project with angular, everything was working fine until I added the spring security dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

Now I get this error in the client side:

Access to XMLHttpRequest at 'http://localhost:8080/api/v1/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I tried to change the config as the documentation suggest so I added class

src/main/java/com/example/securingweb/WebSecurityConfig.java

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer{

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

I also have this in my controller:

@CrossOrigin(origins = "http://localhost:4200")
Ali Khiti
  • 265
  • 4
  • 22

1 Answers1

2

As you have added Spring security dependency, so spring will enable Basic Auth which will validate your each and every request. And that enable CORS(Cross Origin Request Sharing) aswell. Though you have added CrossOrigin for every request that is not enough to disable the CORS.

More Details About CORS

So either you need to send the spring security generated token which will print on your console

or

you need to configure Spring security Configuration class which will validate your authetication or permit the specific url.

More about Spring Security here

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

@Configuration
public class CorsConfig {

   @Bean
   public CorsFilter corsFilter() {
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      CorsConfiguration config = new CorsConfiguration();
      config.setAllowCredentials(true);
      config.addAllowedOrigin("*");
      config.addAllowedHeader("*");
      config.setAllowedHeaders(Arrays.asList("*"));
      config.setAllowedOrigins(Arrays.asList("*"));
      config.setAllowedMethods(Arrays.asList("GET","POST"));

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

}


import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.filter.CorsFilter;


@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

   @Bean
   public PasswordEncoder passwordEncoder() {
      return new BCryptPasswordEncoder();
   }

   @Override
   public void configure(WebSecurity web) {
      web.ignoring()
         .antMatchers(
            "/*.html",
            "/favicon.ico",
            "/**/*.html",
            "/**/*.css",
            "/**/*.js",
            "/h2-console/**"
         );
   }

   @Override
   public void configure(HttpSecurity httpSecurity) throws Exception {
      httpSecurity
            .cors()
          .and()
            .csrf()
            .disable()
            .exceptionHandling()
             .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
         .and()
            .authorizeRequests()
            .antMatchers("/api/authenticate").permitAll()
              .antMatchers("/offerTransactionCall").permitAll()
            .anyRequest().authenticated();
   }
}

coderkali
  • 71
  • 4
  • Added these two classes now I just have a : POST http://localhost:8080/api/v1/login 403 Error. Without the CORS – Ali Khiti May 13 '20 at 00:51
  • The 403 Forbidden Error happens when the web page (or other resource) that you're trying to open in your web browser is a resource that you're not allowed to access. It's called a 403 error because that's the HTTP status code that the web server uses to describe that kind of error. – coderkali May 13 '20 at 01:14
  • As you have configured Spring security configuration now u need to define the roles while needs to be apply to specific endpoints. So you need to understand how the roles are gonna use here – coderkali May 13 '20 at 01:17
  • Have a look https://stackoverflow.com/questions/6357579/spring-security-with-roles-and-permissions – coderkali May 13 '20 at 01:17
  • I am still having the same issue and I am still getting error `Access to XMLHttpRequest at 'http://localhost:8080/api/v1/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.` – pixel Apr 07 '22 at 22:26