using Microsoft.Graph;
using Microsoft.Identity.Client;
var scopes = new[] { "User.Read" };
var tenantId = "3a6831ab-6304-4c72-8d08-3afe544555dd";
var clientId = "87700721-9a44-4470-9099-d079aab1c3d6";
var pca = PublicClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithRedirectUri("http://localhost")
.Build();
身份认证和访问资源的流程
构建 authProvider,有四种方式
交互式
Windows集成
用户名和密码
设备代码
构建 GraphServiceClient, 使用SDK进行编程方式
使用交互式身份验证
最为推荐的方式 : pca.AcquireTokenInteractive
var authProvider = new DelegateAuthenticationProvider(async (request) =>
{
var result = await pca.AcquireTokenInteractive(scopes)
.ExecuteAsync();
request.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});
var graphClient = new GraphServiceClient(authProvider);
var me = await graphClient.Me.Request().GetAsync();
Console.WriteLine(me.DisplayName);
使用Windows集成验证
自动读取当前Windows身份。限制较多:要求用域账号登录,并且跟AAD做了同步。
var authProvider = new DelegateAuthenticationProvider(async (request) =>
{
var result = await pca.AcquireTokenByIntegratedWindowsAuth(scopes).ExecuteAsync();
request.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});
var graphClient = new GraphServiceClient(authProvider);
var me = await graphClient.Me.Request().GetAsync();
Console.WriteLine(me.DisplayName);
使用用户名和密码
某些情况下好用,不需要弹出任何界面。
Console.WriteLine("请输入用户名");
var username = Console.ReadLine();
SecureString securePwd = new SecureString();
ConsoleKeyInfo key;
Console.WriteLine("请输入密码");
do{
key = Console.ReadKey(true);
securePwd.AppendChar(key.KeyChar);
Console.Write("*");
} while (key.Key != ConsoleKey.Enter);
var authProvider = new DelegateAuthenticationProvider(async (request) =>
{
var result = await pca.AcquireTokenByUsernamePassword(scopes, username, securePwd).ExecuteAsync();
request.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});
var graphClient = new GraphServiceClient(authProvider);
var me = await graphClient.Me.Request().GetAsync();
Console.WriteLine(me.DisplayName);
使用设备代码
var authProvider = new DelegateAuthenticationProvider(async (request) =>
{
var result = await pca.AcquireTokenWithDeviceCode(scopes, r =>
{
return Task.FromResult(0);
}).ExecuteAsync();
request.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});
var graphClient = new GraphServiceClient(authProvider);
var me = await graphClient.Me.Request().GetAsync();
Console.WriteLine(me.DisplayName);