Search code examples
javaangularspring-bootcorstoken

Cors Auth SpringBoot


i am working with springboot and angular. Try Login with JWT, when send the http with postman the request is ok but when Try send the same http with Angular i got the next error:

Access to XMLHttpRequest at 'http://localhost:8080/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.

and

zone-evergreen.js:2845 POST http://localhost:8080/login net::ERR_FAILED

when I send requests other than login they work fine I understand that need a cors so the code is the next:

@EnableGlobalMethodSecurity(securedEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated().and().csrf().disable().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().cors();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    org.springframework.web.cors.CorsConfiguration configuration = new org.springframework.web.cors.CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    configuration.setAllowedMethods(Arrays.asList("*"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

but the error is the same.


Solution

  • You can use proxy.conf.json in your angular app.

    This is the example proxy.conf.json

    {
      "/api/*": {
          "target": "http://localhost:8080",
          "secure": false,
          "logLevel": "debug",
          "pathRewrite": {
            "^/api" : ""
          }
      }
    }
    
    

    Then you can hit your BE using http://localhost:4200/api/path-be

    http://localhost:4200 is your angular app. /api if you make request to /api/* so the angular proxy config will redirect to BE that you define in proxy.conf.json

    Remember to add proxy.conf.json to your angular.json

    "serve": {
              "builder": "@angular-devkit/build-angular:dev-server",
              "options": {
                "browserTarget": "angular-hands-on:build",
                "proxyConfig": "proxy.conf.json"
              },
    

    Restart your angular app