Search code examples
c#amazon-web-services.net-coreaws-lambdajwt

AWS Annotations Framework JWT Claims from API Gateway


I'm using the AWS Annotations Framework in dotnet, e.g.:

[LambdaFunction]
[HttpApi(LambdaHttpMethod.Get, "/add/{x}/{y}")]
public int Add(int x, int y, ILambdaContext context)
{
    return x + y;
}

but I've not idea how to retrieve JWT Claims (set by the API Gateway). I have searched the AWS documentation and the Github project discussions, but with no luck so far.

My guess would be to use the [FromHeader] attribute, but I can't find any documentation on how to use it to retrieve JWT Claims.

Before AWS Annotations, the code to retrieve the JWT Claims would be something like

public APIGatewayHttpApiV2ProxyResponse LambdaMathAdd(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context)
{
   var email = request.RequestContext.Authorizer.Jwt.Claims["EmailID"];
   ...

but now I'm not using APIGatewayHttpApiV2ProxyRequest, I'm not sure how to retrieve the claims.

Many thanks in advance,

Dan


Solution

  • It appears I'd missed a trick! I'm not in a position to deploy and test this at the moment, but by using dotPeek, I could look at the generated code.

    If I update my test function to accept the APIGatewayHttpApiV2ProxyRequest object, like so:

        [LambdaFunction]
        [HttpApi(LambdaHttpMethod.Get, "/add/{x}/{y}")]
        public int Add(int x, int y, ILambdaContext context, APIGatewayHttpApiV2ProxyRequest proxyRequest)
        {
            var emailClaim = proxyRequest.RequestContext.Authorizer.Jwt.Claims["emailID"];
    
            return x + y;
        }
    

    I can see that the source generated code is:

    public Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse Add(Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
    {
        //skip the irrelevant code ...
    
        var response = signUpFunction.Add(x, y, __context__, __request__);
    

    In other words, the APIGatewayHttpApiV2ProxyRequest object is passed to my Add function, and I can access all the bits I used to be able to 😄

    Many thanks, Dan