Exemples d'utilisation du fournisseur d'identité Amazon Cognito AWS SDK for .NET - AWS SDK for .NET

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Exemples d'utilisation du fournisseur d'identité Amazon Cognito AWS SDK for .NET

Les exemples de code suivants vous montrent comment effectuer des actions et implémenter des scénarios courants à l'aide du fournisseur AWS SDK for .NET d'identité Amazon Cognito.

Les actions sont des extraits de code de programmes plus larges et doivent être exécutées dans leur contexte. Alors que les actions vous indiquent comment appeler des fonctions de service individuelles, vous pouvez les voir en contexte dans leurs scénarios associés et dans des exemples interservices.

Les Scénarios sont des exemples de code qui vous montrent comment accomplir une tâche spécifique en appelant plusieurs fonctions au sein d’un même service.

Chaque exemple inclut un lien vers GitHub, où vous pouvez trouver des instructions sur la façon de configurer et d'exécuter le code en contexte.

Actions

L'exemple de code suivant montre comment utiliserAdminGetUser.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// Get the specified user from an Amazon Cognito user pool with administrator access. /// </summary> /// <param name="userName">The name of the user.</param> /// <param name="poolId">The Id of the Amazon Cognito user pool.</param> /// <returns>Async task.</returns> public async Task<UserStatusType> GetAdminUserAsync(string userName, string poolId) { AdminGetUserRequest userRequest = new AdminGetUserRequest { Username = userName, UserPoolId = poolId, }; var response = await _cognitoService.AdminGetUserAsync(userRequest); Console.WriteLine($"User status {response.UserStatus}"); return response.UserStatus; }
  • Pour plus de détails sur l'API, reportez-vous AdminGetUserà la section Référence des AWS SDK for .NET API.

L'exemple de code suivant montre comment utiliserAdminInitiateAuth.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// Initiate an admin auth request. /// </summary> /// <param name="clientId">The client ID to use.</param> /// <param name="userPoolId">The ID of the user pool.</param> /// <param name="userName">The username to authenticate.</param> /// <param name="password">The user's password.</param> /// <returns>The session to use in challenge-response.</returns> public async Task<string> AdminInitiateAuthAsync(string clientId, string userPoolId, string userName, string password) { var authParameters = new Dictionary<string, string>(); authParameters.Add("USERNAME", userName); authParameters.Add("PASSWORD", password); var request = new AdminInitiateAuthRequest { ClientId = clientId, UserPoolId = userPoolId, AuthParameters = authParameters, AuthFlow = AuthFlowType.ADMIN_USER_PASSWORD_AUTH, }; var response = await _cognitoService.AdminInitiateAuthAsync(request); return response.Session; }
  • Pour plus de détails sur l'API, reportez-vous AdminInitiateAuthà la section Référence des AWS SDK for .NET API.

L'exemple de code suivant montre comment utiliserAdminRespondToAuthChallenge.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// Respond to an admin authentication challenge. /// </summary> /// <param name="userName">The name of the user.</param> /// <param name="clientId">The client ID.</param> /// <param name="mfaCode">The multi-factor authentication code.</param> /// <param name="session">The current application session.</param> /// <param name="clientId">The user pool ID.</param> /// <returns>The result of the authentication response.</returns> public async Task<AuthenticationResultType> AdminRespondToAuthChallengeAsync( string userName, string clientId, string mfaCode, string session, string userPoolId) { Console.WriteLine("SOFTWARE_TOKEN_MFA challenge is generated"); var challengeResponses = new Dictionary<string, string>(); challengeResponses.Add("USERNAME", userName); challengeResponses.Add("SOFTWARE_TOKEN_MFA_CODE", mfaCode); var respondToAuthChallengeRequest = new AdminRespondToAuthChallengeRequest { ChallengeName = ChallengeNameType.SOFTWARE_TOKEN_MFA, ClientId = clientId, ChallengeResponses = challengeResponses, Session = session, UserPoolId = userPoolId, }; var response = await _cognitoService.AdminRespondToAuthChallengeAsync(respondToAuthChallengeRequest); Console.WriteLine($"Response to Authentication {response.AuthenticationResult.TokenType}"); return response.AuthenticationResult; }

L'exemple de code suivant montre comment utiliserAssociateSoftwareToken.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// Get an MFA token to authenticate the user with the authenticator. /// </summary> /// <param name="session">The session name.</param> /// <returns>The session name.</returns> public async Task<string> AssociateSoftwareTokenAsync(string session) { var softwareTokenRequest = new AssociateSoftwareTokenRequest { Session = session, }; var tokenResponse = await _cognitoService.AssociateSoftwareTokenAsync(softwareTokenRequest); var secretCode = tokenResponse.SecretCode; Console.WriteLine($"Use the following secret code to set up the authenticator: {secretCode}"); return tokenResponse.Session; }
  • Pour plus de détails sur l'API, reportez-vous AssociateSoftwareTokenà la section Référence des AWS SDK for .NET API.

L'exemple de code suivant montre comment utiliserConfirmDevice.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// Initiates and confirms tracking of the device. /// </summary> /// <param name="accessToken">The user's access token.</param> /// <param name="deviceKey">The key of the device from Amazon Cognito.</param> /// <param name="deviceName">The device name.</param> /// <returns></returns> public async Task<bool> ConfirmDeviceAsync(string accessToken, string deviceKey, string deviceName) { var request = new ConfirmDeviceRequest { AccessToken = accessToken, DeviceKey = deviceKey, DeviceName = deviceName }; var response = await _cognitoService.ConfirmDeviceAsync(request); return response.UserConfirmationNecessary; }
  • Pour plus de détails sur l'API, reportez-vous ConfirmDeviceà la section Référence des AWS SDK for .NET API.

L'exemple de code suivant montre comment utiliserConfirmSignUp.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// Confirm that the user has signed up. /// </summary> /// <param name="clientId">The Id of this application.</param> /// <param name="code">The confirmation code sent to the user.</param> /// <param name="userName">The username.</param> /// <returns>True if successful.</returns> public async Task<bool> ConfirmSignupAsync(string clientId, string code, string userName) { var signUpRequest = new ConfirmSignUpRequest { ClientId = clientId, ConfirmationCode = code, Username = userName, }; var response = await _cognitoService.ConfirmSignUpAsync(signUpRequest); if (response.HttpStatusCode == HttpStatusCode.OK) { Console.WriteLine($"{userName} was confirmed"); return true; } return false; }
  • Pour plus de détails sur l'API, reportez-vous ConfirmSignUpà la section Référence des AWS SDK for .NET API.

L'exemple de code suivant montre comment utiliserInitiateAuth.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// Initiate authorization. /// </summary> /// <param name="clientId">The client Id of the application.</param> /// <param name="userName">The name of the user who is authenticating.</param> /// <param name="password">The password for the user who is authenticating.</param> /// <returns>The response from the initiate auth request.</returns> public async Task<InitiateAuthResponse> InitiateAuthAsync(string clientId, string userName, string password) { var authParameters = new Dictionary<string, string>(); authParameters.Add("USERNAME", userName); authParameters.Add("PASSWORD", password); var authRequest = new InitiateAuthRequest { ClientId = clientId, AuthParameters = authParameters, AuthFlow = AuthFlowType.USER_PASSWORD_AUTH, }; var response = await _cognitoService.InitiateAuthAsync(authRequest); Console.WriteLine($"Result Challenge is : {response.ChallengeName}"); return response; }
  • Pour plus de détails sur l'API, reportez-vous InitiateAuthà la section Référence des AWS SDK for .NET API.

L'exemple de code suivant montre comment utiliserListUserPools.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// List the Amazon Cognito user pools for an account. /// </summary> /// <returns>A list of UserPoolDescriptionType objects.</returns> public async Task<List<UserPoolDescriptionType>> ListUserPoolsAsync() { var userPools = new List<UserPoolDescriptionType>(); var userPoolsPaginator = _cognitoService.Paginators.ListUserPools(new ListUserPoolsRequest()); await foreach (var response in userPoolsPaginator.Responses) { userPools.AddRange(response.UserPools); } return userPools; }
  • Pour plus de détails sur l'API, reportez-vous ListUserPoolsà la section Référence des AWS SDK for .NET API.

L'exemple de code suivant montre comment utiliserListUsers.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// Get a list of users for the Amazon Cognito user pool. /// </summary> /// <param name="userPoolId">The user pool ID.</param> /// <returns>A list of users.</returns> public async Task<List<UserType>> ListUsersAsync(string userPoolId) { var request = new ListUsersRequest { UserPoolId = userPoolId }; var users = new List<UserType>(); var usersPaginator = _cognitoService.Paginators.ListUsers(request); await foreach (var response in usersPaginator.Responses) { users.AddRange(response.Users); } return users; }
  • Pour plus de détails sur l'API, reportez-vous ListUsersà la section Référence des AWS SDK for .NET API.

L'exemple de code suivant montre comment utiliserResendConfirmationCode.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// Send a new confirmation code to a user. /// </summary> /// <param name="clientId">The Id of the client application.</param> /// <param name="userName">The username of user who will receive the code.</param> /// <returns>The delivery details.</returns> public async Task<CodeDeliveryDetailsType> ResendConfirmationCodeAsync(string clientId, string userName) { var codeRequest = new ResendConfirmationCodeRequest { ClientId = clientId, Username = userName, }; var response = await _cognitoService.ResendConfirmationCodeAsync(codeRequest); Console.WriteLine($"Method of delivery is {response.CodeDeliveryDetails.DeliveryMedium}"); return response.CodeDeliveryDetails; }
  • Pour plus de détails sur l'API, reportez-vous ResendConfirmationCodeà la section Référence des AWS SDK for .NET API.

L'exemple de code suivant montre comment utiliserSignUp.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// Sign up a new user. /// </summary> /// <param name="clientId">The client Id of the application.</param> /// <param name="userName">The username to use.</param> /// <param name="password">The user's password.</param> /// <param name="email">The email address of the user.</param> /// <returns>A Boolean value indicating whether the user was confirmed.</returns> public async Task<bool> SignUpAsync(string clientId, string userName, string password, string email) { var userAttrs = new AttributeType { Name = "email", Value = email, }; var userAttrsList = new List<AttributeType>(); userAttrsList.Add(userAttrs); var signUpRequest = new SignUpRequest { UserAttributes = userAttrsList, Username = userName, ClientId = clientId, Password = password }; var response = await _cognitoService.SignUpAsync(signUpRequest); return response.HttpStatusCode == HttpStatusCode.OK; }
  • Pour plus de détails sur l'API, reportez-vous SignUpà la section Référence des AWS SDK for .NET API.

L'exemple de code suivant montre comment utiliserVerifySoftwareToken.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

/// <summary> /// Verify the TOTP and register for MFA. /// </summary> /// <param name="session">The name of the session.</param> /// <param name="code">The MFA code.</param> /// <returns>The status of the software token.</returns> public async Task<VerifySoftwareTokenResponseType> VerifySoftwareTokenAsync(string session, string code) { var tokenRequest = new VerifySoftwareTokenRequest { UserCode = code, Session = session, }; var verifyResponse = await _cognitoService.VerifySoftwareTokenAsync(tokenRequest); return verifyResponse.Status; }
  • Pour plus de détails sur l'API, reportez-vous VerifySoftwareTokenà la section Référence des AWS SDK for .NET API.

Scénarios

L’exemple de code suivant illustre comment :

  • Inscrivez et confirmez un utilisateur avec un nom d’utilisateur, un mot de passe et une adresse e-mail.

  • Configurez l’authentification multifactorielle en associant une application MFA à l’utilisateur.

  • Connectez-vous à l’aide d’un mot de passe et d’un code MFA.

AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

namespace CognitoBasics; public class CognitoBasics { private static ILogger logger = null!; static async Task Main(string[] args) { // Set up dependency injection for Amazon Cognito. using var host = Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => logging.AddFilter("System", LogLevel.Debug) .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace)) .ConfigureServices((_, services) => services.AddAWSService<IAmazonCognitoIdentityProvider>() .AddTransient<CognitoWrapper>() ) .Build(); logger = LoggerFactory.Create(builder => { builder.AddConsole(); }) .CreateLogger<CognitoBasics>(); var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("settings.json") // Load settings from .json file. .AddJsonFile("settings.local.json", true) // Optionally load local settings. .Build(); var cognitoWrapper = host.Services.GetRequiredService<CognitoWrapper>(); Console.WriteLine(new string('-', 80)); UiMethods.DisplayOverview(); Console.WriteLine(new string('-', 80)); // clientId - The app client Id value that you get from the AWS CDK script. var clientId = configuration["ClientId"]; // "*** REPLACE WITH CLIENT ID VALUE FROM CDK SCRIPT"; // poolId - The pool Id that you get from the AWS CDK script. var poolId = configuration["PoolId"]!; // "*** REPLACE WITH POOL ID VALUE FROM CDK SCRIPT"; var userName = configuration["UserName"]; var password = configuration["Password"]; var email = configuration["Email"]; // If the username wasn't set in the configuration file, // get it from the user now. if (userName is null) { do { Console.Write("Username: "); userName = Console.ReadLine(); } while (string.IsNullOrEmpty(userName)); } Console.WriteLine($"\nUsername: {userName}"); // If the password wasn't set in the configuration file, // get it from the user now. if (password is null) { do { Console.Write("Password: "); password = Console.ReadLine(); } while (string.IsNullOrEmpty(password)); } // If the email address wasn't set in the configuration file, // get it from the user now. if (email is null) { do { Console.Write("Email: "); email = Console.ReadLine(); } while (string.IsNullOrEmpty(email)); } // Now sign up the user. Console.WriteLine($"\nSigning up {userName} with email address: {email}"); await cognitoWrapper.SignUpAsync(clientId, userName, password, email); // Add the user to the user pool. Console.WriteLine($"Adding {userName} to the user pool"); await cognitoWrapper.GetAdminUserAsync(userName, poolId); UiMethods.DisplayTitle("Get confirmation code"); Console.WriteLine($"Conformation code sent to {userName}."); Console.Write("Would you like to send a new code? (Y/N) "); var answer = Console.ReadLine(); if (answer!.ToLower() == "y") { await cognitoWrapper.ResendConfirmationCodeAsync(clientId, userName); Console.WriteLine("Sending a new confirmation code"); } Console.Write("Enter confirmation code (from Email): "); var code = Console.ReadLine(); await cognitoWrapper.ConfirmSignupAsync(clientId, code, userName); UiMethods.DisplayTitle("Checking status"); Console.WriteLine($"Rechecking the status of {userName} in the user pool"); await cognitoWrapper.GetAdminUserAsync(userName, poolId); Console.WriteLine($"Setting up authenticator for {userName} in the user pool"); var setupResponse = await cognitoWrapper.InitiateAuthAsync(clientId, userName, password); var setupSession = await cognitoWrapper.AssociateSoftwareTokenAsync(setupResponse.Session); Console.Write("Enter the 6-digit code displayed in Google Authenticator: "); var setupCode = Console.ReadLine(); var setupResult = await cognitoWrapper.VerifySoftwareTokenAsync(setupSession, setupCode); Console.WriteLine($"Setup status: {setupResult}"); Console.WriteLine($"Now logging in {userName} in the user pool"); var authSession = await cognitoWrapper.AdminInitiateAuthAsync(clientId, poolId, userName, password); Console.Write("Enter a new 6-digit code displayed in Google Authenticator: "); var authCode = Console.ReadLine(); var authResult = await cognitoWrapper.AdminRespondToAuthChallengeAsync(userName, clientId, authCode, authSession, poolId); Console.WriteLine($"Authenticated and received access token: {authResult.AccessToken}"); Console.WriteLine(new string('-', 80)); Console.WriteLine("Cognito scenario is complete."); Console.WriteLine(new string('-', 80)); } } using System.Net; namespace CognitoActions; /// <summary> /// Methods to perform Amazon Cognito Identity Provider actions. /// </summary> public class CognitoWrapper { private readonly IAmazonCognitoIdentityProvider _cognitoService; /// <summary> /// Constructor for the wrapper class containing Amazon Cognito actions. /// </summary> /// <param name="cognitoService">The Amazon Cognito client object.</param> public CognitoWrapper(IAmazonCognitoIdentityProvider cognitoService) { _cognitoService = cognitoService; } /// <summary> /// List the Amazon Cognito user pools for an account. /// </summary> /// <returns>A list of UserPoolDescriptionType objects.</returns> public async Task<List<UserPoolDescriptionType>> ListUserPoolsAsync() { var userPools = new List<UserPoolDescriptionType>(); var userPoolsPaginator = _cognitoService.Paginators.ListUserPools(new ListUserPoolsRequest()); await foreach (var response in userPoolsPaginator.Responses) { userPools.AddRange(response.UserPools); } return userPools; } /// <summary> /// Get a list of users for the Amazon Cognito user pool. /// </summary> /// <param name="userPoolId">The user pool ID.</param> /// <returns>A list of users.</returns> public async Task<List<UserType>> ListUsersAsync(string userPoolId) { var request = new ListUsersRequest { UserPoolId = userPoolId }; var users = new List<UserType>(); var usersPaginator = _cognitoService.Paginators.ListUsers(request); await foreach (var response in usersPaginator.Responses) { users.AddRange(response.Users); } return users; } /// <summary> /// Respond to an admin authentication challenge. /// </summary> /// <param name="userName">The name of the user.</param> /// <param name="clientId">The client ID.</param> /// <param name="mfaCode">The multi-factor authentication code.</param> /// <param name="session">The current application session.</param> /// <param name="clientId">The user pool ID.</param> /// <returns>The result of the authentication response.</returns> public async Task<AuthenticationResultType> AdminRespondToAuthChallengeAsync( string userName, string clientId, string mfaCode, string session, string userPoolId) { Console.WriteLine("SOFTWARE_TOKEN_MFA challenge is generated"); var challengeResponses = new Dictionary<string, string>(); challengeResponses.Add("USERNAME", userName); challengeResponses.Add("SOFTWARE_TOKEN_MFA_CODE", mfaCode); var respondToAuthChallengeRequest = new AdminRespondToAuthChallengeRequest { ChallengeName = ChallengeNameType.SOFTWARE_TOKEN_MFA, ClientId = clientId, ChallengeResponses = challengeResponses, Session = session, UserPoolId = userPoolId, }; var response = await _cognitoService.AdminRespondToAuthChallengeAsync(respondToAuthChallengeRequest); Console.WriteLine($"Response to Authentication {response.AuthenticationResult.TokenType}"); return response.AuthenticationResult; } /// <summary> /// Verify the TOTP and register for MFA. /// </summary> /// <param name="session">The name of the session.</param> /// <param name="code">The MFA code.</param> /// <returns>The status of the software token.</returns> public async Task<VerifySoftwareTokenResponseType> VerifySoftwareTokenAsync(string session, string code) { var tokenRequest = new VerifySoftwareTokenRequest { UserCode = code, Session = session, }; var verifyResponse = await _cognitoService.VerifySoftwareTokenAsync(tokenRequest); return verifyResponse.Status; } /// <summary> /// Get an MFA token to authenticate the user with the authenticator. /// </summary> /// <param name="session">The session name.</param> /// <returns>The session name.</returns> public async Task<string> AssociateSoftwareTokenAsync(string session) { var softwareTokenRequest = new AssociateSoftwareTokenRequest { Session = session, }; var tokenResponse = await _cognitoService.AssociateSoftwareTokenAsync(softwareTokenRequest); var secretCode = tokenResponse.SecretCode; Console.WriteLine($"Use the following secret code to set up the authenticator: {secretCode}"); return tokenResponse.Session; } /// <summary> /// Initiate an admin auth request. /// </summary> /// <param name="clientId">The client ID to use.</param> /// <param name="userPoolId">The ID of the user pool.</param> /// <param name="userName">The username to authenticate.</param> /// <param name="password">The user's password.</param> /// <returns>The session to use in challenge-response.</returns> public async Task<string> AdminInitiateAuthAsync(string clientId, string userPoolId, string userName, string password) { var authParameters = new Dictionary<string, string>(); authParameters.Add("USERNAME", userName); authParameters.Add("PASSWORD", password); var request = new AdminInitiateAuthRequest { ClientId = clientId, UserPoolId = userPoolId, AuthParameters = authParameters, AuthFlow = AuthFlowType.ADMIN_USER_PASSWORD_AUTH, }; var response = await _cognitoService.AdminInitiateAuthAsync(request); return response.Session; } /// <summary> /// Initiate authorization. /// </summary> /// <param name="clientId">The client Id of the application.</param> /// <param name="userName">The name of the user who is authenticating.</param> /// <param name="password">The password for the user who is authenticating.</param> /// <returns>The response from the initiate auth request.</returns> public async Task<InitiateAuthResponse> InitiateAuthAsync(string clientId, string userName, string password) { var authParameters = new Dictionary<string, string>(); authParameters.Add("USERNAME", userName); authParameters.Add("PASSWORD", password); var authRequest = new InitiateAuthRequest { ClientId = clientId, AuthParameters = authParameters, AuthFlow = AuthFlowType.USER_PASSWORD_AUTH, }; var response = await _cognitoService.InitiateAuthAsync(authRequest); Console.WriteLine($"Result Challenge is : {response.ChallengeName}"); return response; } /// <summary> /// Confirm that the user has signed up. /// </summary> /// <param name="clientId">The Id of this application.</param> /// <param name="code">The confirmation code sent to the user.</param> /// <param name="userName">The username.</param> /// <returns>True if successful.</returns> public async Task<bool> ConfirmSignupAsync(string clientId, string code, string userName) { var signUpRequest = new ConfirmSignUpRequest { ClientId = clientId, ConfirmationCode = code, Username = userName, }; var response = await _cognitoService.ConfirmSignUpAsync(signUpRequest); if (response.HttpStatusCode == HttpStatusCode.OK) { Console.WriteLine($"{userName} was confirmed"); return true; } return false; } /// <summary> /// Initiates and confirms tracking of the device. /// </summary> /// <param name="accessToken">The user's access token.</param> /// <param name="deviceKey">The key of the device from Amazon Cognito.</param> /// <param name="deviceName">The device name.</param> /// <returns></returns> public async Task<bool> ConfirmDeviceAsync(string accessToken, string deviceKey, string deviceName) { var request = new ConfirmDeviceRequest { AccessToken = accessToken, DeviceKey = deviceKey, DeviceName = deviceName }; var response = await _cognitoService.ConfirmDeviceAsync(request); return response.UserConfirmationNecessary; } /// <summary> /// Send a new confirmation code to a user. /// </summary> /// <param name="clientId">The Id of the client application.</param> /// <param name="userName">The username of user who will receive the code.</param> /// <returns>The delivery details.</returns> public async Task<CodeDeliveryDetailsType> ResendConfirmationCodeAsync(string clientId, string userName) { var codeRequest = new ResendConfirmationCodeRequest { ClientId = clientId, Username = userName, }; var response = await _cognitoService.ResendConfirmationCodeAsync(codeRequest); Console.WriteLine($"Method of delivery is {response.CodeDeliveryDetails.DeliveryMedium}"); return response.CodeDeliveryDetails; } /// <summary> /// Get the specified user from an Amazon Cognito user pool with administrator access. /// </summary> /// <param name="userName">The name of the user.</param> /// <param name="poolId">The Id of the Amazon Cognito user pool.</param> /// <returns>Async task.</returns> public async Task<UserStatusType> GetAdminUserAsync(string userName, string poolId) { AdminGetUserRequest userRequest = new AdminGetUserRequest { Username = userName, UserPoolId = poolId, }; var response = await _cognitoService.AdminGetUserAsync(userRequest); Console.WriteLine($"User status {response.UserStatus}"); return response.UserStatus; } /// <summary> /// Sign up a new user. /// </summary> /// <param name="clientId">The client Id of the application.</param> /// <param name="userName">The username to use.</param> /// <param name="password">The user's password.</param> /// <param name="email">The email address of the user.</param> /// <returns>A Boolean value indicating whether the user was confirmed.</returns> public async Task<bool> SignUpAsync(string clientId, string userName, string password, string email) { var userAttrs = new AttributeType { Name = "email", Value = email, }; var userAttrsList = new List<AttributeType>(); userAttrsList.Add(userAttrs); var signUpRequest = new SignUpRequest { UserAttributes = userAttrsList, Username = userName, ClientId = clientId, Password = password }; var response = await _cognitoService.SignUpAsync(signUpRequest); return response.HttpStatusCode == HttpStatusCode.OK; } }