27

How can I add headers to the OPTIONS request made towards a cross-domain API?

The API I'm working against requires a JWT token set as Authorization header on all requests.

When I try to access to the API Angular first performs an OPTIONS request that doesn't care about my headers that I setup for the "real" request like this:

this._headers = new Headers({
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Bearer my-token-here'
});

return this._http
            .post(AppConfig.apiUrl + 'auth/logout', params, {headers: this._headers})
            ...
            ...

When no token is provided, the API returns HTTP status 401 and Angular thinks the OPTIONS request fails.

João Angelo
  • 56,552
  • 12
  • 145
  • 147
Glenn Utter
  • 2,313
  • 7
  • 32
  • 44

3 Answers3

57

According to the CORS specification when a preflight request is performed user credentials are excluded.

(...) using the method OPTIONS, and with the following additional constraints:

  • (...)
  • Exclude the author request headers.
  • Exclude user credentials.
  • (...)

(emphasis is mine)

With this in mind, the problem seems to be on the API side of things, which should be accepting OPTIONS requests without requiring authentication.

Adhyan
  • 63
  • 1
  • 6
João Angelo
  • 56,552
  • 12
  • 145
  • 147
  • The source is a living standard and no longer has the quoted text. Is this Answer still correct in 2021? – haz Nov 10 '21 at 04:31
  • 3
    At the present time, in section 3.2.5 (https://fetch.spec.whatwg.org/#cors-protocol-and-credentials) it's mentioned: _"Note that even so, a CORS-preflight request never includes credentials."_ – João Angelo Nov 19 '21 at 00:10
  • 1
    Thanks. I was searching for "user credentials" and was very confused. And also am not great at reading english, apparently. – haz Nov 22 '21 at 03:44
1

If you're using Cloudformation template, you have to declare AddDefaultAuthorizerToCorsPreflight as false like in this example:

MyApiGateway:
  Type: AWS::Serverless::Api
  Properties:
    StageName: !Ref Stage
    Auth:
      Authorizers:
        CognitoAuthorizer:
          UserPoolArn: !GetAtt UserPool.Arn
      DefaultAuthorizer: CognitoAuthorizer
      AddDefaultAuthorizerToCorsPreflight: false
    Cors:
      AllowMethods: "'POST,OPTIONS'"
      AllowHeaders: "'Access-Control-Allow-Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with,x-requested-for'"
      AllowOrigin: "'*'"

This will allow OPTIONS to accept requests without authorization headers

Leopoldo Varela
  • 257
  • 3
  • 9
-2

It's possible to provide authentication for CORS preflight requests using the withCredentials option:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor() {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      withCredentials: true
    });
    return next.handle(request);
  }
}

See also:

https://stackoverflow.com/a/38615675/166850

RMorrisey
  • 7,637
  • 9
  • 53
  • 71