'Add authentication to OPTIONS request
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.
Solution 1:[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
Solution 2:[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:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Leopoldo Varela |
| Solution 2 | RMorrisey |
