I have an Angular 8 app calling a .Net Core 3 backend API using:
this.http.get<User[]>('/users');
I am deliberately not passing a bearer token. The API expects an authorization bearer header and when the call above doesn't provide it, .Net correctly outputs in the log:
HTTP GET /users responded 401. AuthenticationScheme: Bearer was not authenticated
However the Angular debug console displays the following three entries for this, two of which are extraneous or plain wrong:
1) Failed to load resource: the server responded with a status of 401 () [https://localhost:5000/users]
2) Failed to load resource: the server responded with a status of 401 () [https://localhost:5000/users]
3) Access to XMLHttpRequest at 'https://localhost:5000/users' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. [http://localhost:4200/users]
My first problem is that item (2) above should not exist because there is no second http call or error returned.
My second problem is that item (3) above should not exist because I already have CORS setup however regardless .Net will not return a 'Access-Control-Allow-Origin' header if it is returning a 401.So why is Angular looking for one?
My third and most important problem is that in my httpinterceptor where I catch this error:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError((error: HttpErrorResponse) => {
the error object caught is:
error.status = 0 This should be 401, but its 0
error.message = "Unknown Error" This should be "Unauthorized" or some such
So it seems to me that the httpinterceptor is actually being passed error number (3) from the above list as opposed to error number (1) like it should be.
Has anyone seen this before or know how to get round it?
GETrequests not to require a preflight request:The only allowed values for the Content-Type header are: application/x-www-form-urlencoded; multipart/form-data; text/plain. And a status value of 0 is usually for CORS issues