AWS SDK for .NET を使用する Amazon Cognito ID プロバイダーの例 - AWS SDK コードサンプル

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

AWS SDK for .NET を使用する Amazon Cognito ID プロバイダーの例

次のコード例は、Amazon Cognito ID プロバイダーで AWS SDK for .NET を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、関連するシナリオやサービス間の例ではアクションのコンテキストが確認できます。

「シナリオ」は、同じサービス内で複数の関数を呼び出して、特定のタスクを実行する方法を示すコード例です。

各例には、 へのリンクが含まれています。このリンクには GitHub、コンテキスト内でコードをセットアップして実行する方法の手順が記載されています。

アクション

次のコード例は、Amazon Cognito ユーザーを確認する方法を示しています。

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 の詳細については、「 API リファレンスConfirmSignUp」の「」を参照してください。 AWS SDK for .NET

次のコード例は、Amazon Cognito により追跡する MFA デバイスを確認する方法を示しています。

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 の詳細については、「 API リファレンスConfirmDevice」の「」を参照してください。 AWS SDK for .NET

次のコード例は、MFA アプリケーションを Amazon Cognito ユーザーに関連付けるトークンを取得する方法を示しています。

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; }
  • API の詳細については、「 API リファレンスAssociateSoftwareToken」の「」を参照してください。 AWS SDK for .NET

次のコード例は、Amazon Cognito ユーザーに関する情報を取得する方法を示しています。

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 の詳細については、「 API リファレンスAdminGetUser」の「」を参照してください。 AWS SDK for .NET

次のコード例は、Amazon Cognito ユーザープールを一覧表示する方法を示しています。

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 の詳細については、「 API リファレンスListUserPools」の「」を参照してください。 AWS SDK for .NET

次のコード例は、Amazon Cognito ユーザーを一覧表示する方法を示しています。

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 の詳細については、「 API リファレンスListUsers」の「」を参照してください。 AWS SDK for .NET

次のコード例は、Amazon Cognito 確認コードを再送信する方法を示しています。

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; }
  • API の詳細については、「 API リファレンスResendConfirmationCode」の「」を参照してください。 AWS SDK for .NET

次のコード例は、Amazon Cognito 認証チャレンジに応答する方法を示しています。

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; }
  • API の詳細については、「 API リファレンスAdminRespondToAuthChallenge」の「」を参照してください。 AWS SDK for .NET

次のコード例は、ユーザーを Amazon Cognito にサインアップする方法を示しています。

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 の詳細については、「 API リファレンスSignUp」の「」を参照してください。 AWS SDK for .NET

次のコード例は、Amazon Cognito を使用して認証を開始する方法を示しています。

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 の詳細については、「 API リファレンスInitiateAuth」の「」を参照してください。 AWS SDK for .NET

次のコード例は、Amazon Cognito と管理者認証情報を使用して認証を開始する方法を示しています。

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 の詳細については、「 API リファレンスAdminInitiateAuth」の「」を参照してください。 AWS SDK for .NET

次のコード例は、Amazon Cognito ユーザーで MFA アプリケーションを検証する方法を示しています。

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; }
  • API の詳細については、「 API リファレンスVerifySoftwareToken」の「」を参照してください。 AWS SDK for .NET

シナリオ

次のコードサンプルは、以下の操作方法を示しています。

  • ユーザー名、パスワード、E メールアドレスでサインアップしてユーザーを確認します。

  • 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; } }