CognitoのUserAttributesをC#から取得

Cognito C#言語から接続

Amazon Cognitoは、OpenID Connect などのエンタープライズ ID プロバイダーを通してサインインすることができるAWS内のサービスです。Cognitoのユーザープールにユーザーを追加すると、ユーザー内にUserAttributes情報を収納できます。そのCognito UserAttributesをC#言語を使ってユーザーにログインしUserAttributesを取得するコード例です。

パッケージインストール

Visual Studio C#で新規プロジェクトを作成し、下記のようにnugetからAWSSDKの必要なパッケージをインストールします

Install-Package AWSSDK.Core -Version 3.7.5.9
Install-Package AWSSDK.CognitoIdentity -Version 3.7.0.110 #←これは要らないかも
Install-Package AWSSDK.CognitoIdentityProvider -Version 3.7.1.82
Install-Package Amazon.Extensions.CognitoAuthentication -Version 2.2.2

AWSコンソール画面から[プールID]と[アプリクライアント ID]を用意

下のようにAWSコンソール画面(ブラウザ)などからユーザープールを選択し[プールID]と[アプリクライアントID]情報を取得します。

プールID取得方法
[ユーザープール]→[全般設定]→[プールID]
アプリクライアントID取得方法
[ユーザープール]→[アプリクライアント]→[アプリクライアントID]

コード例

usingで必要なのは下記の3行です

using Amazon;
using Amazon.CognitoIdentityProvider;
using Amazon.Extensions.CognitoAuthentication;
private void button1_Click(object sender, EventArgs e)
{
	string poolId = "ap-northeast-1_さきほど用意したプールID";
	string clientId = "さきほど用意したアプリクライアントID";
	string userId = textBox1.Text; //Cognitoでユーザー追加設定したユーザー名
	string passWd = textBox2.Text; //Cognitoでユーザー追加設定したパスワード
	AmazonCognitoIdentityProviderClient amazonCognitoIdentityProviderClient1 = new(new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.APNortheast1);
	CognitoUserPool cognitoUserPool1 = new(poolId, clientId, amazonCognitoIdentityProviderClient1);
	CognitoUser cognitoUser1 = new(userId, clientId, cognitoUserPool1,amazonCognitoIdentityProviderClient1);

	InitiateSrpAuthRequest initiateSrpAuthRequest1 = new()
	{
		Password = passWd
	};
	var authResponse = cognitoUser1.StartWithSrpAuthAsync(initiateSrpAuthRequest1).ConfigureAwait(true).GetAwaiter();        
	var _idToken = authResponse.GetResult().AuthenticationResult;
	var _getUserResponse = cognitoUser1.GetUserDetailsAsync().ConfigureAwait(false).GetAwaiter();
	var _userResponse = _getUserResponse.GetResult();
	textBox3.Clear();
	_userResponse.UserAttributes.ForEach(_v => {
		textBox3.Text += string.Format("{0}={1}\r\n", _v.Name, _v.Value);
	});
}

async / awaitは利用していませんが、非同期処理実装も可能です。AWSSDKの場合GetAwaiter() / GetResult()を使います。

Amazon Cognito ユーザーデータ取得画面
2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED