Cannot call aws API Gateway via ajax

烂漫一生 提交于 2020-01-07 04:24:09

问题


I am using aws APi gateway and api gateway custom authorizer. The code that I have for api gateway custom authorizer is as follows:

console.log('Loading function');

 exports.handler =  (event, context, callback) => {
var token = event.authorizationToken;
// Call oauth provider, crack jwt token, etc.
// In this example, the token is treated as the status for simplicity.

switch (token.toLowerCase()) {
    case 'allow':
        callback(null, generatePolicy('user', 'Allow', event.methodArn));
        break;
    case 'deny':
        callback(null, generatePolicy('user', 'Deny', event.methodArn));
        break;
    case 'unauthorized':
        callback("Unauthorized");   // Return a 401 Unauthorized response
        break;
    default:
        callback("Error: Invalid token"); 
}
};

var generatePolicy = function(principalId, effect, resource) {
var authResponse = {};

authResponse.principalId = principalId;
if (effect && resource) {
    var policyDocument = {};
    policyDocument.Version = '2012-10-17'; // default version
    policyDocument.Statement = [];
    var statementOne = {};
    statementOne.Action = 'execute-api:Invoke'; // default action
    statementOne.Effect = effect;
    statementOne.Resource = resource;
    policyDocument.Statement[0] = statementOne;
    authResponse.policyDocument = policyDocument;
}

// Can optionally return a context object of your choosing.
authResponse.context = {};
authResponse.context.stringKey = "stringval";
authResponse.context.numberKey = 123;
authResponse.context.booleanKey = true;
return authResponse;

as you can see it is just a simple mock up example provided in aws website. Then I configured my get method in API gateway using this authorizer. Also in method execution I added a custom hedear called authorizationToken which will be used by authorizer.

When I use the postman everything is good:

However when I try to call it via ajax as follows I get the following error:

XMLHttpRequest cannot load https://590vv3bkda.execute-api.us-east-1.amazonaws.com/hamedstg/tjresource/story. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 401.

Here is my ajax call:

$.ajax(
    'https://590vv3bkda.execute-api.us-east-1.amazonaws.com/xxxxxxx',
    {
        method : 'GET',
        headers : {                                                                         
                      'authorizationToken' : 'allow'
                },
        beforeSend : function(xhr) {
            xhr.setRequestHeader('authorizationToken', 'allow');
        }
}).then(function(data) {
    console.log(data);
});

Also it is noteworthy that I enabled CORS on the api in aws.

Can anyone help?


回答1:


Did you add any methods or resources since enabling CORS? If so, then run the CORS wizard again and redeploy to your stage.

Also, make sure that the OPTIONS method on your resource does not require/use the customer authorizer. OPTIONS needs to be open to all as the browser will call it on your behalf for pre-flight CORS checks in some cases.

There is also a known issue that when an API Gateway call fails for any reason, the CORS headers are not set and thus you'll get that "No 'Access-Control-Allow-Origin' header is present" error, when the root cause is something entirely different. Try turning on developer logging on your browser, get the exact request sent to the API (it may be an OPTIONS method) and try the same request as a test invoke from the API Gateway console. That will let you look at the output and the logs to determine if there is another issue.



来源:https://stackoverflow.com/questions/44073882/cannot-call-aws-api-gateway-via-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!