MSALを利用してID、パスワードからアクセストークンを取得する - C#

C#でMSALを利用してID、パスワードからアクセストークンを取得するコードを紹介します。

概要

プログラムでアカウントのID、パスワードの情報からAPIにアクセスするためのアクセストークンを取得するコードを紹介します。

事前準備

アクセストークンを取得するためのプログラムを作成する前に、アプリケーションの登録や設定が必要です。

Azure Active Directory へのプログラム登録

Azure Active Directory にプログラムを登録します。 手順はこちらの記事を参照してください。

パブリック クライアント フローを有効にする

登録したアプリケーションのパブリック クライアント フローを有効にします。 手順はこちらの記事を参照してください。

APIのアクセス許可

アプリケーションのAPIのアクセス許可を与えます。 手順はこちらの記事を参照して下さい。

プロジェクトの作成

C#のアプリケーションプロジェクトを作成します。今回は .NET 5の Windows フォームアプリケーションを作成します。

Microsoft.Identity.Client ライブラリのインストール

作成したプロジェクトに Microsoft.Identity.Client パッケージをインストールします。 インストール手順はこちらの記事を参照してください。

プログラム

UI

下図のフォームを作成します。ボタンとMultilineプロパティをtrueに設定した、複数行テキストボックスを配置します。

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Identity.Client;

namespace SimpleMSAL
{
  public partial class FormMain : Form
  {
    public static IPublicClientApplication PublicClientApp;
    private string ClientId = "(クライアントID)";
    private string TenantId = "(テナントID)";

    public FormMain()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private async void button1_Click(object sender, EventArgs e)
    {
      PublicClientApplicationBuilder app = PublicClientApplicationBuilder.Create(ClientId);
      app = app.WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient");
      app = app.WithAuthority(AzureCloudInstance.AzurePublic, TenantId);
      PublicClientApp = app.Build();
      //
      string[] scopes = new string[] { "User.Read" };
      string password = "(パスワード)";
      System.Security.SecureString secpass = new System.Security.SecureString();

      foreach (char c in password) secpass.AppendChar(c);

      AcquireTokenByUsernamePasswordParameterBuilder builder = PublicClientApp.AcquireTokenByUsernamePassword(scopes, "(アカウント名)", secpass);
      AuthenticationResult authResult = await builder.ExecuteAsync();

      textBox1.Text += "Account UserName:" + authResult.Account.Username +"\r\n";
      textBox1.Text += "Account Environment:" + authResult.Account.Environment + "\r\n";
      textBox1.Text += "Account HomeAccountID:" + authResult.Account.HomeAccountId + "\r\n";
      textBox1.Text += "UniqueID:" + authResult.UniqueId + "\r\n";
      textBox1.Text += "AccessToken:" + authResult.AccessToken +"\r\n";
    }
  }
}

解説

クライアントIDとテナントIDは、Azure Active Directory にアプリケーション登録後、アプリケーションの詳細画面に表示されている値を利用します。
    private string ClientId = "(クライアントID)";
    private string TenantId = "(テナントID)";
次のコードがMSALの初期化のコードになります。PublicClientApplicationBuilder.Create() メソッドを呼び出し、ビルダオブジェクトを取得します。 ビルダオブジェクトの、WithRedirectUri() WithAuthority() メソッドを呼び出し設定をしたのち、Build() メソッドを呼び出し、IPublicClientApplication オブジェクトを作成します。
      PublicClientApplicationBuilder app = PublicClientApplicationBuilder.Create(ClientId);
      app = app.WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient");
      app = app.WithAuthority(AzureCloudInstance.AzurePublic, TenantId);
      PublicClientApp = app.Build();

スコープを設定します。APIのアクセス許可画面に表示されていた "User.Read" のアクセスをスコープに設定します。
      string[] scopes = new string[] { "User.Read" };

SecureString オブジェクトのパスワード文字列を準備します。SecureString は1文字づつ設定する必要があるため、foreach文を利用してパスワード文字列を設定します。
      string password = "(パスワード)";
      System.Security.SecureString secpass = new System.Security.SecureString();
      foreach (char c in password) secpass.AppendChar(c);

アクセストークンを取得します。先に作成した、IPublicClientApplication オブジェクトの AcquireTokenByUsernamePassword() メソッドを呼び出し、ビルダオブジェクトを 取得します。AcquireTokenByUsernamePassword メソッドの第一引数にスコープを与え、第二引数にアクセスするアカウント名、第三引数にアカウントのパスワードを与えます。
アクセスするアカウントは、Microsoft Azure Active Directoryのアカウントになります。
取得したビルダオブジェクトの ExecuteAsync() を呼び出すとアクセストークンの取得を実行します。
      AcquireTokenByUsernamePasswordParameterBuilder builder = PublicClientApp.AcquireTokenByUsernamePassword(scopes, "(アカウント名)", secpass);
      AuthenticationResult authResult = await builder.ExecuteAsync();

取得したアクセストークンの情報をテキストボックスに表示します。
      textBox1.Text += "Account UserName:" + authResult.Account.Username +"\r\n";
      textBox1.Text += "Account Environment:" + authResult.Account.Environment + "\r\n";
      textBox1.Text += "Account HomeAccountID:" + authResult.Account.HomeAccountId + "\r\n";
      textBox1.Text += "UniqueID:" + authResult.UniqueId + "\r\n";
      textBox1.Text += "AccessToken:" + authResult.AccessToken +"\r\n";

実行結果

プロジェクトを実行します。下図のウィドウが表示されます。


[button1]をクリックします。アクセストークンが取得でき、テキストボックスにアクセストークンや取得に利用したユーザー名が表示されます。


C#でプログラムからアクセストークンを取得できました。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2021-06-04
作成日: 2021-06-02
iPentec all rights reserverd.