0
votes

I have an angulat http interceptor that is trying to add Authorization headers to a request but when the code run the resulting request is not what I expect, the method is changed from POST to OPTIONS and I get an error like this :

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

@Injectable()
export class DlkmInterceptor implements HttpInterceptor {

 constructor() {
 }

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

   if (request.url === authConfig.tokenEndpoint && request.method === 'POST') {
     let authData = window.btoa(authConfig.clientId + ':' + authConfig.dummyClientSecret);
     request = request.clone({
       setHeaders: {
         'Content-Type': 'application/x-www-form-urlencoded',
         'Authorization': 'Basic ' + authData
       }
     });
     return next.handle(request);

   } else {
     request = request.clone({});
     return next.handle(request)
   }

 }
}
1

1 Answers

1
votes

This is expected behavior. It is due to the Cross Origin Policy of browser.

Since you are requesting a resource from the domain other the one on which you Angular Application is hosted, so browser will follow the Cross Origin Policy

When you request a resource from a different origin, the browser first checks to see that you can actually request that resource or not by sending OPTIONS request also known as preflight request

You need to allow the headers in your backend server in order for preflight request to be successful, when the preflight request is successful, you browser will make the actually request.

You can learn more about this topic here