0
votes

I have a rest api being deployed on aws with serverless framework.

Now, I have created a simple jwt token custom token authorizer in it to authorize my endpoints.

This is my routes definition in the serverless.yml -

loginUser:
  handler: src/controllers/auth.loginUser
  events:
    - http:
        path: auth/local/login
        method: POST
        cors: true

tokenVerifier:
  handler: ./src/helpers/tokenVerifier.auth

userProfile:
  handler: src/controllers/users.me
  events:
    - http:
        path: user/me
        method: GET
        authorizer: tokenVerifier
        cors: true

And this is my custom authorizer tokenVerifier function definition -

const jwt = require('jsonwebtoken'); 

// Policy helper function
const generatePolicy = (principalId, effect, resource) => {
    const authResponse = {};
    authResponse.principalId = principalId;
    if (effect && resource) {
        const policyDocument = {};
        policyDocument.Version = '2012-10-17';
        policyDocument.Statement = [];
        const statementOne = {};
        statementOne.Action = 'execute-api:Invoke';
        statementOne.Effect = effect;
        statementOne.Resource = resource;
        policyDocument.Statement[0] = statementOne;
        authResponse.policyDocument = policyDocument;
    }
    return authResponse;
};

const auth = (event, context, callback) => {

    // check header or url parameters or post parameters for token
    const token = event.authorizationToken;

    if (!token) return callback(null, 'Unauthorized');

    // verifies secret and checks exp
    jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
        if (err) return callback(null, 'Unauthorized');

        // if everything is good, save to request for use in other routes
        return callback(null, generatePolicy(decoded._id, 'Allow', event.methodArn));
    });

};

export {
    auth
};

Also I have created a response helper utility which I use everywhere to return response to users -

const responseHelper = (response, context, callback, status = 404) => {
    eventLogger(["----RESPONSE DATA----", response], context.functionName);
    callback(null, {
        statusCode: status,
        body: JSON.stringify(response),
        headers: {
            "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
            "Access-Control-Allow-Credentials" : true, // Required for cookies, authorization headers with HTTPS
            "Content-Type": "application/json"
        }
    });
};

So, as you can see I have added cors: true to the routes yml, and also added the cors headers to all my lambda responses. On google I came across this answer and I tried to add these to the default_4xx, default_5xx and expired token responses too api gw gateway response

But, still I am getting the same error -

Access to XMLHttpRequest at '<url>/dev/user/me' from origin '<site_url>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

So, am I missing something here ? or can anyone help find and fix this issue here ?

1

1 Answers

1
votes

Assuming you're following this example, you should add the resources part to your serverless.yml:

resources:
  Resources:
    # This response is needed for custom authorizer failures cors support ¯\_(ツ)_/¯
    GatewayResponse:
      Type: 'AWS::ApiGateway::GatewayResponse'
      Properties:
        ResponseParameters:
          gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
          gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
        ResponseType: EXPIRED_TOKEN
        RestApiId:
          Ref: 'ApiGatewayRestApi'
        StatusCode: '401'
    AuthFailureGatewayResponse:
      Type: 'AWS::ApiGateway::GatewayResponse'
      Properties:
        ResponseParameters:
          gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
          gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
        ResponseType: UNAUTHORIZED
        RestApiId:
          Ref: 'ApiGatewayRestApi'
        StatusCode: '401'

https://github.com/serverless/examples/blob/acfa06e6a93c1cb6e5d9306e65675d1acdec5eb3/aws-node-auth0-custom-authorizers-api/serverless.yml#L36

Also, I would first test the API in POSTMAN (or any other similar tool), to make sure everything works as expected before handling CORS.