LoginSignup
0
0

Graph API 二つの認証方法:passwordとclientSecret

Last updated at Posted at 2023-03-10

Graph APIのアクセストークンを取得するには、二つ方法よく使うので、メモーします。
・mail&password
・clientSecret
microsoftのドキュメントを見ると、mail&passwordの認証で推奨ではないと書いています。截屏2023-03-10 15.50.16.png

clientSecretでの認証(アプリケーション認証、ユーザなし)

截屏2023-03-10 15.54.05.png

        var scopes = new string[] { "https://graph.microsoft.com/.default" };
        var tenantId = テナントID;

        // Configure the MSAL client as a confidential client
        var confidentialClient = ConfidentialClientApplicationBuilder
                        .Create(クライアントID)
         .WithAuthority($"https://login.microsoftonline.com/{テナントID}/v2.0")
                        .WithClientSecret(TeamsConstants.ClientSecretValue)
                        .Build();

            // Retrieve an access token for Microsoft Graph 
            var authResult = await confidentialClient
                     .AcquireTokenForClient(scopes)
                     .ExecuteAsync();
         //認証
        var authProvider = new DelegateAuthenticationProvider(request =>
        {
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
            return Task.CompletedTask;
        });

        var graphClient = new GraphServiceClient(authProvider);

mail&passwordでの認証(委任認証、ユーザあり)

截屏2023-03-10 16.00.00.png

static async Task GetATokenForGraph()
{
 string authority = "https://login.microsoftonline.com/contoso.com";
 string[] scopes = new string[] { "user.read" };
 IPublicClientApplication app;
 app = PublicClientApplicationBuilder.Create(clientId)
       .WithAuthority(authority)
       .Build();
 var accounts = await app.GetAccountsAsync();

 AuthenticationResult result = null;
 if (accounts.Any())
 {
  result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                    .ExecuteAsync();
 }
 else
 {
  try
  {
   //新しいメソッドは、「SecureString」を使わなくなった。
   //var securePassword = new SecureString();
   //foreach (char c in "dummy")        // you should fetch the password
   //securePassword.AppendChar(c);  // keystroke by keystroke

   result = await app.AcquireTokenByUsernamePassword(scopes,
                                                    "joe@contoso.com",
                                                     “password”)
                      .ExecuteAsync();
  }
  catch(MsalException)
  {
   // See details below
  }
 }
 Console.WriteLine(result.Account.Username);
}

参考サイト:

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0