Make a Serverless API which can work with or without Authentication

Hi,
I have a usecase where I want to give varying responses if the user is not authenticated / not authenticated . I am using cognito for authentication .

getProfile:
** handler: profileController.getProfileDetails**
** events:**
** - http:**
** path: profile/{profileName}**
** method: get**
** cors: true**
** authorizer:**
** arn: COGNITO ARN GOES HERE**

if I call this API without passing and Authorization Header, I am getting a response stating

{
** “message”: “Unauthorized”**
}

and the control doesn’t even go to my lambda function . What I want is something like this
export async function getProfileDetails(event,context){

if(!event.requestContext.authorizer){
** // go to unauthorized flow**
}else{
** // go to authorized flow**
}
}

Please let me know if it is possible to do the same with serverless, API Gateway , lambda and cognito .

Thanks in Advance

I noticed there hasn’t been a reply yet so i figured i’d ask a question (i’m also looking for a solution to this): What about switching to a custom authorizer that redirects to a separate lambda method when authentication fails? Would that be a worthwhile approach?

1 Like