Salah
Salah

Reputation: 183

How to retrive a token from Cognito?

I have a simple Dotnet core API that gets value1,value2 and the method is [Authorize]. I am trying to retrieve token back from Cognito idp in order to access the result but the thing is I couldn't find a way to send the (username, pass, and email)to Cognito in order to get back a token.

I keep getting the following error:

Error in SAML response processing: Invalid user attributes: email: The attribute is required ', error_uri: 'error_uri is null' ¨ In startup.cs I configured it as the following:

services.Configure<OpenIdConnectOptions>(Configuration.GetSection("Authentication:Cognito"));
        var serviceProvider = services.BuildServiceProvider();
        var authOptions = serviceProvider.GetService<IOptions<OpenIdConnectOptions>>();

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddOpenIdConnect(options =>
        {
            options.ResponseType = authOptions.Value.ResponseType;

            options.MetadataAddress = authOptions.Value.MetadataAddress;
            options.ClientId = authOptions.Value.ClientId;
            options.ClientSecret = authOptions.Value.ClientSecret;
            options.SaveTokens = authOptions.Value.SaveTokens;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = authOptions.Value.TokenValidationParameters.ValidateIssuer
            };
         });

I am expecting to get the token back after sending (username, pass, and email) attributes to Cognito idp and provide it to postman in order to get the values.

Upvotes: 2

Views: 526

Answers (1)

Sandeep Chandran C
Sandeep Chandran C

Reputation: 181

Use the below code to retrieve the access token after successful sign up with username and password

 CognitoUserPool userPool=new CognitoUserPool(poolid,client_id,provider);
 CognitoUser user=new CognitoUser(username,client_id,userPool,provider);
            InitiateSrpAuthRequest authRequest=new InitiateSrpAuthRequest()
            {
                Password=password
            };
   Task<AuthFlowResponse> authFlowResponse=null;
   authFlowResponse=user.StartWithSrpAuthAsync(authRequest);
   string Token=authFlowResponse.Result.AuthenticationResult.AccessToken.ToString();

Upvotes: 1

Related Questions