Pratik Patel
Pratik Patel

Reputation: 31

Added claims from AWS custom lambda Authorizer, how to access those claims in ASP.NET Core 6 Web API?

I have created AWS custom lambda Authorizer, which is validating token and add claims in APIGatewayCustomAuthorizerResponse with Context property.

private APIGatewayCustomAuthorizerResponse AuthorizedResponse(TokenIntrospectionResponse result) // result with claims after validating token
    {
return new APIGatewayCustomAuthorizerResponse()
        {
            PrincipalID = "uniqueid",
            PolicyDocument = new APIGatewayCustomAuthorizerPolicy()
            {
                Statement = new List<APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>
                {
                    new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement()
                    {
                        Effect = "Allow",
                        Resource = new HashSet<string> { "*" },
                        Action = new HashSet<string> { "execute-api:Invoke" }
                    }
                }
            },
            Context = PrepareRequestContextFromClaims(result.Claims) //APIGatewayCustomAuthorizerContextOutput
        };
}

private APIGatewayCustomAuthorizerContextOutput PrepareRequestContextFromClaims(IEnumerable<System.Security.Claims.Claim> claims)
    {
        APIGatewayCustomAuthorizerContextOutput contextOutput = new APIGatewayCustomAuthorizerContextOutput();

        var claimsGroupsByType = claims.GroupBy(x => x.Type);
        foreach (var claimsGroup in claimsGroupsByType)
        {
            var type = claimsGroup.Key;
            var valuesList = claimsGroup.Select(x => x.Value); 
            var values = string.Join(',', valuesList);
            contextOutput[type] = values;
        }

        return contextOutput;
    }

Added this lambda authorizer with API GW method request.

For integration request, I have added HTTP Proxy request, which is an ASP.NET Core 6 Web API.

I am trying to access claims from the headers, that were added by authorizer in Web API routes, but not getting any claims.

_httpContext.HttpContext.Request.Headers
// not getting with headers

_httpContext.HttpContext.Items["LAMBDA_REQUEST_OBJECT"] as APIGatewayProxyRequest
// not getting with this as well

Is there any way to achieve this?

Upvotes: 2

Views: 800

Answers (1)

Pratik Patel
Pratik Patel

Reputation: 31

Needs to configure claim key value with API Gateway's Method & Integration request.

For example, if custom lambda authorizer validates token and add claim 'role' in Context of APIGatewayCustomAuthorizerResponse => we have to add optional role in headers with 'Method Request' and also need to add header with 'Integration request' as (Name : role, Mapped from : context.authorizer.role).

then after we will get 'role' from headers using _httpContext.HttpContext.Request.Headers['role'] with .Net Core 6 Web API.

Upvotes: 1

Related Questions