简体   繁体   English

具有身份验证Angular2的CORS AWS API网关

[英]CORS AWS API-Gateway with Authentication Angular2

my AWS API-Gateway is configured as Lambda Proxy. 我的AWS API网关配置为Lambda代理。 In Lambda i added the following Headers: 在Lambda中,我添加了以下标题:

'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key'

First, everythink works fine with it. 首先,一切都可以。 Now i added an Authorizer with CognitoUserPool and i get the following Error: 现在,我使用CognitoUserPool添加了授权者,并且出现以下错误:

XMLHttpRequest cannot load https://xxx.eu-west-1.amazonaws.com/xxx/xxx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401.

I think the problem is, that with Authentication my Lambdafunction is not invoked and so no Headers were set. 我认为问题在于,通过身份验证不会调用我的Lambda函数,因此未设置任何标头。 I call the Endpoint from an Angular2 Application with 我从Angular2应用程序调用Endpoint

const headers = new Headers();
headers.append('Authorization', 'authtoken');
http.get('address...', headers);

But the headers were not set/append to the request because of any CORS-reasons i think. 但由于我认为存在任何CORS原因,因此未将标头设置/附加到请求。

Anyone an idea how can i solve this? 有人知道我该如何解决?

PS: I tried the "Enable Cors" feature of API-Gateway but that does not work. PS:我尝试了API-Gateway的“启用Cors”功能,但无法正常工作。

Edit: I also have a "OPTIONS" Method in Gateway with Authentication, that responds with the Headers above. 编辑:我在带有身份验证的网关中也有一个“ OPTIONS”方法,该方法以上述标题为响应。

Greetings 问候

Is your Lambda Proxy function mapping to the ANY HTTP method type? 您的Lambda代理功能是否映射到ANY HTTP方法类型? If so, it may be attempting to perform authentication on the pre-flight ( OPTIONS ) request. 如果是这样,它可能正在尝试对飞行前( OPTIONS )请求执行身份验证。 If this is the case, try mapping your proxy function to POST , GET , etc. specifically. 在这种情况下,请尝试将代理功能映射到POSTGET等。

I found the solution of the problem. 我找到了解决问题的方法。 It was not caused by API-Gateway. 这不是由API-Gateway引起的。 Problem was this code: 问题是此代码:

const headers = new Headers();
headers.append('Authorization', 'authtoken');
http.get('address...', headers);

The "get" needs a "RequestOptions"-object. “获取”需要一个“ RequestOptions”对象。 It has to be: 它一定要是:

const headers = new Headers();
headers.append('Authorization', 'authtoken');
const options = new RequestOptions({headers: headers});
http.get('address...', options);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM