Angular14 Service CORS and Authentication Header

Viewed 15

I have an Angular 14 app that I'm just starting out with that will be using Authorization headers to call a webapi (c#) in a different domain, so CORS is hitting me. What I can't figure out is how to get it accept the Authorization header and have everything still hit CORS.

My test service is simple:

export class AppComponent {
  title = 'ngtest';
  centers: any;

  constructor(private service: CentersService) {}

  ngOnInit() {
    this.service.getCenters().subscribe((data) => {
      this.centers = data;
    });
  }
}

I am using HttpInterceptor:

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

var authRequest = request.clone({
  headers: request.headers.set(
    'Authorization', 'Bearer <CutForBrevity>'
  ),
});

return next.handle(authRequest);

}

Here is what's in the console:

[Log] Angular is running in development mode. Call enableProdMode() to enable production mode. (vendor.js, line 41609)
[Info] [webpack-dev-server] Live Reloading enabled. (polyfills.js, line 1919)
[Error] Preflight response is not successful. Status code: 404
[Error] XMLHttpRequest cannot load https://..../centers due to access control checks.
[Error] Failed to load resource: Preflight response is not successful. Status code: 404 (centers, line 0)
[Error] ERROR – HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", …}
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "https://..../centers", ok: false, …}HttpErrorResponse

The thing is, I'm not even hitting the backend servers if I use Angular. Nothing in the IIS logs. But, I also have a simple C# Web App that works fine using the same browser, but different technology. That's telling me that the CORS handling on the server side appears to be working fine. (I see where CORS is being evaluated and returning the appropriate steps, etc).

I'm sure it's something simple, I just don't know what at this point.

Thanks for any guidance, Nick

1 Answers

The angular parts all seem to be correct. I made several changes to the back end API (C#) and managed to get it working.

Related