I’m trying to add a custom authorizer for the API gateway, I followed some guide to disabled the authorizer cache, and allow the wildcard matched resources *
, but it still gets the User is not authorized to access this resource
every time.
Code(only a default function and a simple authorizer function):
serverless.yml
functions:
hello:
handler: handler.hello
events:
- http:
path: hello
method: get
cors: true
authorizer:
type: TOKEN
name: authorizerFun
identitySource: method.request.header.Authorization
resultTtlInSeconds: 0
authorizerFun:
handler: authorizer.authorizerFun
authorizer.js
const generatePolicy = (user, effect, resource) => {
const authResponse = {
principalId: user.id || 'anonymous'
};
if (effect && resource) {
const policyDocument = {
Version: '2012-10-17',
Statement: [
{
Action: 'exectue-api:Invoke',
Effect: effect,
Resource: resource
}
]
};
authResponse.policyDocument = policyDocument;
}
authResponse.context = {
role: user.role
};
return authResponse; };
export const authorizerFun = (event, context) => {
const authorizationToken = event.authorizationToken;
console.log(authorizationToken);
switch (authorizationToken) {
case 'manager':
context.succeed(generatePolicy({ id: 1, role: 'MANAGER' }, 'Allow', '*'));
break;
case 'tenant':
context.succeed(generatePolicy({ id: 2, role: 'TENANT' }, 'Allow', '*'));
break;
default:
context.fail('error');
}
};
I tested the below cases:
- test the authorizer in API Gateway, which will get the correct policy, and the authorizer function got called.
- then I test through postman with the correct token, it will get
User is not authorized to access this resource
403 Forbidden error.