Bob
Bob

Reputation: 415

C# Lambda Cognito: Missing required parameter USERNAME

I am new to C#.

I am trying to create a Lambda that takes a Username and Password which is checked against a Cognito User Pool and then returns an auth token.

Here is the code:

namespace CognitoUser.AuthenticateProfile;

using System.Collections.Generic;
using System.Net;

using Amazon.Lambda.APIGatewayEvents;
using System.Threading.Tasks;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
using Amazon.Lambda.Core;
using Users.Models;


public class Function
{
    private readonly AmazonCognitoIdentityProviderClient _client = new();

    private const string ClientId = "123"; // ConfigurationManager.AppSettings["CLIENT_ID"];

    public async Task<APIGatewayHttpApiV2ProxyResponse> Function(CognitoUser input, ILambdaContext context)
    {
        LambdaLogger.Log($"Calling function name: {context.FunctionName}\n");
        {
            LambdaLogger.Log($"Attempting to get token for {input.UserName}\n");
            String token = await GetToken(input.UserName, input.Password);
            APIGatewayHttpApiV2ProxyResponse response = new()
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body = token,
                Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } }
            };
            return response;
        }
    }
    private async Task<string>  GetToken (string userName, string password) { 
        InitiateAuthRequest authReq = new ()
        {
            ClientId = ClientId,
            AuthFlow = AuthFlowType.USER_PASSWORD_AUTH
        };
        authReq.AuthParameters.Add("USERNAME", userName);
        authReq.AuthParameters.Add("PASSWORD", password);
        InitiateAuthResponse authResp = await _client.InitiateAuthAsync(authReq);
        // Look into exceptions etc 
        return authResp.AuthenticationResult.AccessToken;
    }
}

When I use the below payload in the Lambda console it works as expected, but when I try to make a POST request from the API Gateway Console I get the following:

Thu Mar 24 19:00:50 UTC 2022 : Endpoint response body before transformations: {
  "errorType": "InvalidParameterException",
  "errorMessage": "Missing required parameter USERNAME",
  "stackTrace": [
    "at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleExceptionStream(IRequestContext requestContext, IWebResponseData httpErrorResponse, HttpErrorResponseException exception, Stream responseStream)",
    "at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleExceptionAsync(IExecutionContext executionContext, HttpErrorResponseException exception)",
    "at Amazon.Runtime.Internal.ExceptionHandler`1.HandleAsync(IExecutionContext executionContext, Exception exception)",
    "at Amazon.Runtime.Internal.ErrorHandler.ProcessExceptionAsync(IExecutionContext executionContext, Exception exception)",
    "at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext)",
    "at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)",
    "at Amazon.Runtime.Inte [TRUNCATED]
Thu Mar 24 19:00:50 UTC 2022 : Lambda execution failed with status 200 due to customer function error: Missing required parameter USERNAME. Lambda request id: fb739e08-aa93-4283-a8e3-c6bc68d730c2
Thu Mar 24 19:00:50 UTC 2022 : Method completed with status: 502

Upvotes: 1

Views: 788

Answers (1)

MD. RAKIB HASAN
MD. RAKIB HASAN

Reputation: 3956

USER_PASSWORD_AUTH: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly. If a user migration Lambda trigger is set, this flow will invoke the user migration Lambda if it doesn't find the USERNAME in the user pool.

InitiateAuthRequest authReq = new ()
{
    UserPoolId = ConfigurationManager.AppSettings["USERPOOL_ID"],
    ClientId = ClientId,
    AuthFlow = AuthFlowType.USER_PASSWORD_AUTH
};

The user pool ID set up in the prerequisites section and your have to pass this user pool ID in above request.

Reference: https://aws.amazon.com/blogs/mobile/use-csharp-to-register-and-authenticate-with-amazon-cognito-user-pools/

Upvotes: 1

Related Questions