I would like that when an authorizer denies access a more specific message instead of the default "User is not authorized to access this resource", I tried several ways to achieve that, the way that seems more feasible is this one https://stackoverflow.com/a/49806967 , but I didn't succeed in customizing the message, my authorizer already performs the main function of authorizing.
Has anyone here succeeded in customizing the authorizer message in any way?
here follows the serverless.yml example
service: serasa-score-backend
plugins:
- serverless-offline
- serverless-apigateway-plugin
- serverless-plugin-typescript
- serverless-stack-output
package:
patterns:
- 'src/config/serviceAccountKey.json'
provider:
name: aws
runtime: nodejs16.x
stage: 'local'
region: us-east-2
custom:
stage: 'local'
output:
file: .serverless/output.json
functions:
verify-token:
handler: src/functions/auth/controller.checkJwt
healthcheck:
handler: src/functions/healthcheck/controller.check
description: Healthcheck to ensure the service is up
events:
- http:
path: healthcheck
method: get
registerUser:
handler: src/functions/user/controller.register
description: Healthcheck to ensure the service is up
timeout: 30
events:
- http:
path: users
method: post
authorizer:
name: verify-token
resultTtlInSeconds: 30
identitySource: method.request.header.Authorization
type: token
login:
handler: src/functions/auth/controller.login
description: Healthcheck to ensure the service is up
timeout: 30
events:
- http:
path: auth
method: post
authorizer:
name: verify-token
resultTtlInSeconds: 30
identitySource: method.request.header.Authorization
type: TOKEN
enableSimpleResponses: false
export const checkJwt: APIGatewayTokenAuthorizerHandler = async (
event,
context,
) => {
context.callbackWaitsForEmptyEventLoop = false
console.log(event.authorizationToken)
const result = generatePolicy('user', 'Deny', event.methodArn)
console.log(result)
return result
}
export function generatePolicy(
principalId: string,
effect: 'Allow' | 'Deny',
resource: string
) {
const authResponse: any = {}
authResponse.principalId = principalId
if (effect && resource) {
const policyDocument: any = {}
policyDocument.Version = '2012-10-17'
policyDocument.Statement = []
const statementOne: any = {}
statementOne.Action = 'execute-api:Invoke'
statementOne.Effect = effect
statementOne.Resource = resource
policyDocument.Statement[0] = statementOne
authResponse.policyDocument = policyDocument
}
authResponse.context = {}
// Set a custom message for unauthorized requests
if (effect === 'Deny') {
authResponse.context.message =
'Sorry, you are not authorized to access this resource. Try later'
}
return authResponse
}