CORS problem when accessing rest endpoint with angular client - cross origin is allowed

Viewed 379

So I have a strange situation. Some weeks ago I was accessing rest endpoints from my spring backend via angular It worked, after I added @CrossOrigin(origins = arrayOf("http://localhost:4200")) on top of the controller classes.

However, after adding some Spring security and some http interceptor on the client, it stopped working, saying

Access to XMLHttpRequest at 'http://localhost:8080/v1/backend/calculationtype/' from origin 'http://localhost:4200' has been blocked by CORS policy

I dont know how this could happen. After authorization I am getting a Bearer Token, which I add to the httpHeader via Interceptor. When using Postman, everything works fine. I am using OAuth2.

I will show some classes.

token.interceptor.ts:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.temp.getToken()}` //contains the Bearer token
      }
    });
    console.log(request);
    return next.handle(request);
}

I am using console.log to print the request which I am sending. The header of the request contains the key Authorization with the value Bearer e23........... Using those values in postman, it is working.

CalculationTypeController.kt (I am using kotlin instead of java):

@CrossOrigin(origins = arrayOf("http://localhost:4200")) //this line worked before
@RestController
@RequestMapping(value = ["v1/backend/calculationtype/"])
class CalculationTypeController() {

    @RequestMapping(method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE])
    fun addCalculationType(@RequestBody calcDTO: CalcDTO): CalcuDTO {
       
        some stuff happening...
    }
}

When using authentication, I had to add a proxy.conf.json but I didnt need it to get my data from the endpoints. However, here it is.

proxy.conf.json:

{
    "/oauth/*": {
        "target": "http://localhost:8080",
        "secure": false,
        "changeOrigin":true,
        "logLevel": "debug"
    },
    "/v1/*": {
        "target": "http://localhost:8080",
        "secure": false,
        "changeOrigin":true,
        "logLevel": "debug"
}
}

Who can give me some advice or tell me whats going on here? Thanks for every help!

3 Answers

I assume you added the proxy.config in the angular.json:

...
"serve": {
  "proxyConfig": "proxy.config.js"
}
...

proxy.config.js

const PROXY_CONFIG = [
  {
  "context": ['/oauth/*']
  "target": "http://localhost:8080",
  "secure": false,
  "changeOrigin":true,
  "logLevel": "debug"
  },
  {
  "context": ['/v1/backend']
  "target": "http://localhost:8080",
  "secure": false,
  "changeOrigin":true,
  "logLevel": "debug"
  },
]

Try enable CORS for your project, create this class in your Spring project:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

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

Or incase you got Spring Boot app:

@Configuration
public class CORSConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

Both classes are @Configuration so they will be running as part of the app server start

Related