C#(.NET 6)でAWS Cognitoを使ったユーザー認証の実装方法

この記事は公開から2年以上経過しています。

AWS SDK for .NET を使い、AWS Cognitoでユーザーアカウントの作成、Eメール認証、作成したアカウントによるサインインまでの一連動作を試してみたので、その備忘録。


手順

AWS Cognitoの設定

ユーザープールの設定

file
全て既定値。

アプリクライアント設定

file
設定登録時にクライアントシークレットを生成のチェックボックスのチェックを外しておく。他は全て既定値。

IDプール設定

file
認証プロバイダーでCognitoを選択、ユーザープールIDとアプリクライアントIDを入力。


サンプルプログラム(C#)

AWSCognitoTestApp.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Amazon.Extensions.CognitoAuthentication" Version="2.2.2" />
    <PackageReference Include="AWSSDK.CognitoIdentity" Version="3.7.0.159" />
    <PackageReference Include="AWSSDK.CognitoIdentityProvider" Version="3.7.2.23" />
    <PackageReference Include="AWSSDK.Core" Version="3.7.11.3" />
  </ItemGroup>

</Project>

NuGetパッケージAWSSDK.CoreAWSSDK.CognitoIdentityProviderAWSSDK.CognitoIdentityAmazon.Extensions.CognitoAuthenticationを追加。

main.cs

using Amazon;
using Amazon.Runtime;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
using Amazon.Extensions.CognitoAuthentication;

// TestUserPoolのプールID
const string USER_POOL_ID = "region_xxxx";
// TestAppClientのアプリクライアントID
const string APP_CLIENT_ID = "xxxx";

// アカウントユーザ名
const string USER_NAME = "Foo";
// アカウントパスワード
const string PASSWORD = "P@ssw0rd";
// アカウントEメールアドレス
const string EMAIL = "mail@example.com";
// 確認コード
const string CONFIRMATION_CODE = "123456";

var cognitoIdClient = new AmazonCognitoIdentityProviderClient(
    new AnonymousAWSCredentials(),
    RegionEndpoint.APNortheast1);

// 1. 新しいアカウントのサインアップ
await SignUp(cognitoIdClient, APP_CLIENT_ID, USER_NAME, PASSWORD, EMAIL);

// 2. 確認コードによるEメールアドレスの確認
await Confirm(cognitoIdClient, USER_NAME, APP_CLIENT_ID, CONFIRMATION_CODE);

// 3. 新しいアカウントでサインイン
await SignIn(cognitoIdClient, USER_POOL_ID, APP_CLIENT_ID, USER_NAME, PASSWORD);

static async Task SignUp(AmazonCognitoIdentityProviderClient cognitoIdClient, string clientId, string userName, string password, string email)
{
    try
    {
        var regRequest = new SignUpRequest
        {
            ClientId = clientId,
            Username = userName,
            Password = password,
            UserAttributes = { new AttributeType { Name = "email", Value = email } }
        };

        var ret = await cognitoIdClient.SignUpAsync(regRequest);
    }
    catch (Exception e)
    {
        Console.WriteLine($"{e.Message}");
    }
}

static async Task Confirm(AmazonCognitoIdentityProviderClient cognitoIdClient, string userName, string clientId, string confirmationCode)
{
    try
    {
        var confirmSignUpRequest = new ConfirmSignUpRequest
        {
            Username = userName,
            ClientId = clientId,
            ConfirmationCode = confirmationCode,
        };

        var ret = await cognitoIdClient.ConfirmSignUpAsync(confirmSignUpRequest);
    }
    catch (Exception e)
    {
        Console.WriteLine($"{e.Message}");
    }
}

static async Task SignIn(AmazonCognitoIdentityProviderClient cognitoIdClient, string userPoolId, string clientId, string userName, string password)
{
    try
    {
        var cognitoUserPool = new CognitoUserPool(userPoolId, clientId, cognitoIdClient);
        var cognitoUser = new CognitoUser(userName, clientId, cognitoUserPool, cognitoIdClient);

        var ret = await cognitoUser.StartWithSrpAuthAsync(new InitiateSrpAuthRequest { Password = password });
    }
    catch (Exception e)
    {
        Console.WriteLine($"{e.Message}");
    }
}

GitHub Gist

処理の概要は以下のとおり。

  1. ユーザー名/パスワード/Eメールアドレスを指定して新しいユーザーアカウントを作成。
    (このとき、登録したEメールアドレスに確認コードが送信される。)

  2. ユーザー名とEメールで受信した確認コードを用いて、Eメールアドレスの確認を行う。

  3. ユーザー名/パスワードを用いてサインインを行う。
    (このとき、戻り値からIDトークン/アクセストークン/更新トークンが取得できる。)


以上です。

シェアする

  • このエントリーをはてなブックマークに追加

フォローする