@ayuhato2001

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

AWSでMFA認証の検証をしたい

解決したいこと

AWSのCognitoからMFA認証の検証をやりたいが、usernameやpasswordで認証エラーが発生する
実際にAWSでは登録したパラメータをコードに打ち込んではいるが、エラーがはかれ続ける

発生している問題・エラー

C:\Users\25065702\Downloads\AWS\AwsTestApp\Program.cs(76,77): warning CS8600: Null リテラルまたは Null の可能性がある値を Null 非許容型に変換しています。
❌ 認証エラー: Incorrect username or password.

AWS CLI でユーザーの状態を確認、及び、AWS内でemail_verifiedが非活性だったため、CMDから有効化を試したところ以下のタイムアウトになってしまう

Connect timeout on endpoint URL: "https://cognito-idp.ap-northeast-1.amazonaws.com/"

ソースコード

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Amazon;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
using Amazon.Runtime;

class Program
{
    static async Task Main(string[] args)
    {
        var authService = new CognitoAuthService();

        // ユーザー情報(実際の値に置き換えてください)
        string username = "〇〇";
        string password = "〇〇"; // 仮パスワードまたは現在のパスワード
        string newPassword = "〇〇"; // 初回ログイン時に設定する新しいパスワード
        string mfaCode = "〇〇"; // Authenticatorアプリで表示された6桁コード(30秒以内)

        await authService.AuthenticateWithMfaAsync(username, password, newPassword, mfaCode);
    }
}

public class CognitoAuthService
{
    private readonly AmazonCognitoIdentityProviderClient cognitoClient;

    // 必要な情報をここに設定
    private readonly string clientId = "〇〇";
    private readonly string clientSecret = "〇〇";
    private readonly string userPoolId = "〇〇";

    public CognitoAuthService()
    {
        var credentials = new BasicAWSCredentials("〇〇", "〇〇");
        cognitoClient = new AmazonCognitoIdentityProviderClient(credentials, RegionEndpoint.APNortheast1); // 東京リージョン
    }

    private string GenerateSecretHash(string username)
    {
        var message = username + clientId;
        var key = Encoding.UTF8.GetBytes(clientSecret);
        using (var hmac = new HMACSHA256(key))
        {
            var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
            return Convert.ToBase64String(hash);
        }
    }

    public async Task AuthenticateWithMfaAsync(string username, string password, string newPassword, string mfaCode)
    {
        try
        {
            string secretHash = GenerateSecretHash(username);

            // ステップ1:パスワード認証
            var authRequest = new AdminInitiateAuthRequest
            {
                UserPoolId = userPoolId,
                ClientId = clientId,
                AuthFlow = AuthFlowType.ADMIN_USER_PASSWORD_AUTH,
                AuthParameters = new Dictionary<string, string>
                {
                    { "USERNAME", username },
                    { "PASSWORD", password },
                    { "SECRET_HASH", secretHash }
                }
            };

            var authResponse = await cognitoClient.AdminInitiateAuthAsync(authRequest);

            // ステップ2:初回ログイン時のパスワード変更
            AdminRespondToAuthChallengeResponse passwordChallengeResponse = null;
            if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
            {
                var newPasswordRequest = new AdminRespondToAuthChallengeRequest
                {
                    ChallengeName = ChallengeNameType.NEW_PASSWORD_REQUIRED,
                    ClientId = clientId,
                    UserPoolId = userPoolId,
                    Session = authResponse.Session,
                    ChallengeResponses = new Dictionary<string, string>
                    {
                        { "USERNAME", username },
                        { "NEW_PASSWORD", newPassword },
                        { "SECRET_HASH", secretHash }
                    }
                };

                passwordChallengeResponse = await cognitoClient.AdminRespondToAuthChallengeAsync(newPasswordRequest);
            }

            // ステップ3:MFAチャレンジ応答
            if (passwordChallengeResponse != null && passwordChallengeResponse.ChallengeName == ChallengeNameType.SOFTWARE_TOKEN_MFA)
            {
                var mfaRequest = new AdminRespondToAuthChallengeRequest
                {
                    ChallengeName = ChallengeNameType.SOFTWARE_TOKEN_MFA,
                    ClientId = clientId,
                    UserPoolId = userPoolId,
                    Session = passwordChallengeResponse.Session,
                    ChallengeResponses = new Dictionary<string, string>
                    {
                        { "USERNAME", username },
                        { "SOFTWARE_TOKEN_MFA_CODE", mfaCode },
                        { "SECRET_HASH", secretHash }
                    }
                };

                var finalResponse = await cognitoClient.AdminRespondToAuthChallengeAsync(mfaRequest);

                Console.WriteLine("✅ 認証成功!(MFAあり)");
                Console.WriteLine("ID Token: " + finalResponse.AuthenticationResult.IdToken);
            }
            else if (authResponse.ChallengeName == ChallengeNameType.SOFTWARE_TOKEN_MFA)
            {
                var mfaRequest = new AdminRespondToAuthChallengeRequest
                {
                    ChallengeName = ChallengeNameType.SOFTWARE_TOKEN_MFA,
                    ClientId = clientId,
                    UserPoolId = userPoolId,
                    Session = authResponse.Session,
                    ChallengeResponses = new Dictionary<string, string>
                    {
                        { "USERNAME", username },
                        { "SOFTWARE_TOKEN_MFA_CODE", mfaCode },
                        { "SECRET_HASH", secretHash }
                    }
                };

                var finalResponse = await cognitoClient.AdminRespondToAuthChallengeAsync(mfaRequest);

                Console.WriteLine("✅ 認証成功!(MFAあり)");
                Console.WriteLine("ID Token: " + finalResponse.AuthenticationResult.IdToken);
            }
            else if (authResponse.AuthenticationResult != null)
            {
                Console.WriteLine("✅ 認証成功!(MFAなし)");
                Console.WriteLine("ID Token: " + authResponse.AuthenticationResult.IdToken);
            }
            else
            {
                Console.WriteLine("⚠️ 予期しないチャレンジ: " + authResponse.ChallengeName);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("❌ 認証エラー: " + ex.Message);
        }
    }
}

自分で試したこと

・AWS内でのユーザプール設定の見直し
・IAM>ユーザ>許可ポリシーでAmazonCognitoPowerUserをアタッチ
・ユーザのMFA認証有効化
・パスワードポリシーの要件確認

0 likes

No Answers yet.

Your answer might help someone💌