Graph APIのアクセストークンを取得するには、二つ方法よく使うので、メモーします。
・mail&password
・clientSecret
microsoftのドキュメントを見ると、mail&passwordの認証で推奨ではないと書いています。
clientSecretでの認証(アプリケーション認証、ユーザなし)
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での認証(委任認証、ユーザあり)
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);
}
参考サイト: