Request to an Apigee API from angular 6 throwing 401 (Unauthorized) error

Below is the response I'm getting when I checked in network:

{"fault":{"faultstring":"Invalid access token","detail":{"errorcode":"oauth.v2.InvalidAccessToken"}}}
This is the error displayed in console.

OPTIONS [API] 401 (Unauthorized)
Access to XMLHttpRequest at [API] 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.

I have done following changes in Apigee :

<?xml version="1.0" encoding="UTF-8"
standalone="yes"?><AssignMessage async="false"
continueOnError="false" enabled="true"
name="Add-CORS">  <DisplayName>Add CORS</DisplayName>  <FaultRules/>  <Properties/>  <Set>  <Headers> 
<Header name="Access-Control-Allow-Origin">*</Header> 
<Header
name="Access-Control-Allow-Credentials">true</Header> 
<Header name="Access-Control-Max-Age">3628800</Header> 
<Header name="Access-Control-Allow-Headers">authorization,
origin, x-requested-with, accept, content-type, user-agent,
apikey</Header> 
<Header name="Access-Control-Allow-Methods">GET, PUT, POST,
DELETE, OPTIONS</Header>  </Headers>  </Set> 
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>  <AssignTo createNew="false"
transport="http" type="response"/></AssignMessage>
<RouteRule name="NoRoute"> 
<Condition>request.verb == "OPTIONS"</Condition>  </RouteRule>

I'm using angular 6 httpInterceptor to attach headers as follows:

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const headersConfig = {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    };
      return this.authenticationService.AuthToken(req.url).pipe(
      switchMap((token)=>{
        if (token)
        {
          headersConfig['Authorization'] = `Bearer ${token}`;   
        }
           const request = req.clone({ setHeaders: headersConfig });
          return next.handle(request);
      }));
  }

Please let me know if I'm missing something.

@Siddharth_Barahalikar

0 12 2,273
12 REPLIES 12

sidd-harth
Participant V

Hi @Maskiri PL, since the error is about Preflight, try to follow these steps,

https://docs.apigee.com/api-platform/develop/adding-cors-support-api-proxy#handlingcorspreflightrequ...

Create a new flow and add cors policy to it as seen in above doc,

<Flow name="OptionsPreFlight">
            <Request/>
            <Response>
                <Step>
                    <Name>add-cors</Name>
                </Step>
            </Response>
        <Condition>request.verb == "OPTIONS" AND request.header.origin != null AND request.header.Access-Control-Request-Method != null</Condition> 
        </Flow>

For NoRoute and a couple of more conditions,

<RouteRule name="NoRoute">
        <Condition>request.verb == "OPTIONS" AND request.header.origin != null AND request.header.Access-Control-Request-Method != null</Condition>
    </RouteRule>

Use default Cors policy,

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="add-cors">
    <DisplayName>Add CORS</DisplayName>
    <FaultRules/>
    <Properties/>
    <Add>
        <Headers>
            <Header name="Access-Control-Allow-Origin">*</Header>
            <Header name="Access-Control-Allow-Headers">origin, x-requested-with, accept</Header>
            <Header name="Access-Control-Max-Age">3628800</Header>
            <Header name="Access-Control-Allow-Methods">GET, PUT, POST, DELETE</Header>
        </Headers>
    </Add>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="response"/>
</AssignMessage>

Hi @Siddharth Barahalikar, I have done above changes this is giving get request 401 error.

 GET [API] 401 (Unauthorized)


Please post complete error.

Are you seeing any CORS error?

What do you see in Trace, post a couple of images of error shown in Trace.

7974-cors.png

this is the error I'm getting in browser's console. Now there is no CORS error.

Image of Trace shown below

7977-cors1.png

I guess the preflight issue is resolved, and now the error is regarding the token.

Create a new question and post these images along with the content(XML) on the two policies shown in the above Trace image.

BTW are you passing user credentials in queryparams?

If yes, then it is not recommended to send credentials in queryparams.

no we are not passing credentials in queryparams

In request header token is present. Cn you please tell me is this is somethig that to be handled through Apigee code?

So it seems most of these solutions simply set the CORS headers to "*" allowing any, possibly malicious, user to access them. I see the logic in that these are simply error messages so the concern is lowered, but it feels like a possible security flaw. Any thoughts? And is there an alternative?

siddheshnaik
Participant II

From what I have understood, You need to add CORS policy in error (fault rule or default fault rule)flow also from where the error is thrown.

<DefaultFaultRule name="PlatformFaults"> <AlwaysEnforce>false</AlwaysEnforce> <Step> <Name>AM-AddCORS</Name> </Step></DefaultFaultRule>

Just check if this works.

Hi @Siddhesh Naik, why do you think it should be added to FaultRules?

As you said, we have to create a separate resource to handle preflight requests.

Also if in case of error state if CORS headers are not getting added in request headers from preflow(Sometimes developers keeps CORS policy in response), then we have to add cors in error flow.

Siddharth Barahalika

I have this in Agigee