Amazon Cognito 자격 증명 공급자를 사용하는 예제 AWS SDK for .NET - AWS SDK for .NET

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Amazon Cognito 자격 증명 공급자를 사용하는 예제 AWS SDK for .NET

다음 코드 예제는 Amazon Cognito ID AWS SDK for .NET 공급자와 함께 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 호출하는 방법을 보여 주며 관련 시나리오와 교차 서비스 예시에서 컨텍스트에 맞는 작업을 볼 수 있습니다.

시나리오는 동일한 서비스 내에서 여러 함수를 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예시입니다.

각 예제에는 컨텍스트에서 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있는 링크가 포함되어 있습니다. GitHub

작업

다음 코드 예시에서는 AdminGetUser을 사용하는 방법을 보여 줍니다.

AWS SDK for .NET
참고

자세한 내용은 여기를 참조하십시오 GitHub. 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; }
  • API 세부 정보는 AWS SDK for .NET API AdminGetUser참조를 참조하십시오.

다음 코드 예시에서는 AdminInitiateAuth을 사용하는 방법을 보여 줍니다.

AWS SDK for .NET
참고

자세한 내용은 다음과 같습니다 GitHub. 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; }
  • API 세부 정보는 AWS SDK for .NET API AdminInitiateAuth참조를 참조하십시오.

다음 코드 예시에서는 AdminRespondToAuthChallenge을 사용하는 방법을 보여 줍니다.

AWS SDK for .NET
참고

자세한 내용은 다음과 같습니다 GitHub. 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; }

다음 코드 예시에서는 AssociateSoftwareToken을 사용하는 방법을 보여 줍니다.

AWS SDK for .NET
참고

자세한 내용은 다음과 같습니다 GitHub. 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; }

다음 코드 예시에서는 ConfirmDevice을 사용하는 방법을 보여 줍니다.

AWS SDK for .NET
참고

자세한 내용은 다음과 같습니다 GitHub. 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; }
  • API 세부 정보는 AWS SDK for .NET API ConfirmDevice참조를 참조하십시오.

다음 코드 예시에서는 ConfirmSignUp을 사용하는 방법을 보여 줍니다.

AWS SDK for .NET
참고

자세한 내용은 다음과 같습니다 GitHub. 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; }
  • API 세부 정보는 AWS SDK for .NET API ConfirmSignUp참조를 참조하십시오.

다음 코드 예시에서는 InitiateAuth을 사용하는 방법을 보여 줍니다.

AWS SDK for .NET
참고

자세한 내용은 다음과 같습니다 GitHub. 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; }
  • API 세부 정보는 AWS SDK for .NET API InitiateAuth참조를 참조하십시오.

다음 코드 예시에서는 ListUserPools을 사용하는 방법을 보여 줍니다.

AWS SDK for .NET
참고

자세한 내용은 다음과 같습니다 GitHub. 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; }
  • API 세부 정보는 AWS SDK for .NET API ListUserPools참조를 참조하십시오.

다음 코드 예시에서는 ListUsers을 사용하는 방법을 보여 줍니다.

AWS SDK for .NET
참고

자세한 내용은 다음과 같습니다 GitHub. 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; }
  • API 세부 정보는 AWS SDK for .NET API ListUsers참조를 참조하십시오.

다음 코드 예시에서는 ResendConfirmationCode을 사용하는 방법을 보여 줍니다.

AWS SDK for .NET
참고

자세한 내용은 다음과 같습니다 GitHub. 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; }

다음 코드 예시에서는 SignUp을 사용하는 방법을 보여 줍니다.

AWS SDK for .NET
참고

자세한 내용은 다음과 같습니다 GitHub. 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; }
  • API 세부 정보는 AWS SDK for .NET API SignUp참조를 참조하십시오.

다음 코드 예시에서는 VerifySoftwareToken을 사용하는 방법을 보여 줍니다.

AWS SDK for .NET
참고

자세한 내용은 다음과 같습니다 GitHub. 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; }

시나리오

다음 코드 예제에서는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • 사용자 이름, 암호 및 이메일 주소로 사용자를 가입시키고 확인합니다.

  • MFA 애플리케이션을 사용자와 연결하여 다중 인증을 설정합니다.

  • 암호와 MFA 코드를 사용하여 로그인합니다.

AWS SDK for .NET
참고

자세한 내용은 다음과 같습니다 GitHub. 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; } }