bemo
bemo

Reputation: 479

How to get AWS Cognito access token with username and password in .NET Core 3.1?

I'm working on a C# client application using .NET Core 3.1 which needs to use AWS Cognito user pools for user authentication.

As this is a client application I can't use AdminInitiateAuth etc and only have access to: user pool ID, client ID and the user-provided username and password.

I'm porting code from an existing JavaScript client application that uses https://www.npmjs.com/package/amazon-cognito-identity-js but I'm struggling to find an equivalent way to do this in C# for a .NET Core application.

I did find something that looked perfect using the CognitoAuthentication extension library https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/cognito-authentication-extension.html but upon trying the example in that the program hangs indefinitely when creating the provider:

public static async void GetCredsAsync()
{
    AmazonCognitoIdentityProviderClient provider =
        new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials()); // << hangs here
    CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider);
    CognitoUser user = new CognitoUser("username", "clientID", userPool, provider);
    InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
    {
        Password = "userPassword"
    };

    AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
    accessToken = authResponse.AuthenticationResult.AccessToken;
}

I'm not sure if the example is relevant to .NET Core or not - the first sentence on the page says it is but there's a banner at the top saying it isn't! The banner points me to https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/welcome.html but I can't seem to find what I need there.

How can I obtain AWS Cognito access tokens in .Net Core using just user pool ID, client ID and user provided username and password?

(Or why is creating the AmazonCognitoIdentityProviderClient hanging in the example?)

Any help appreciated, thank you

Upvotes: 2

Views: 6211

Answers (1)

Scott
Scott

Reputation: 31

I ran into similar issue with the AmazonCognitoIdentityProviderClient hanging and resolved it by explicitly setting the region.

Amazon.CognitoIdentityProvider.AmazonCognitoIdentityProviderClient provider = new Amazon.CognitoIdentityProvider.AmazonCognitoIdentityProviderClient(
                new Amazon.Runtime.AnonymousAWSCredentials(), Amazon.RegionEndpoint.USEast1);

Upvotes: 3

Related Questions