虽然花了一些功夫,但毕竟不是太难。 Azure 周围有很多库,但它们基本上都只是一堆 HTTP 请求和响应。即使在控制台应用程序中...
我首先创建一个 PublicClientApplicationBuilder:
var options = new PublicClientApplicationOptions()
{
ClientId = <**clientid**>,
TenantId = <**tenantid**>,
AzureCloudInstance = AzureCloudInstance.AzurePublic,
};
var client = PublicClientApplicationBuilder.CreateWithApplicationOptions(options).Build();
我还可以创建一个 ConfidentialClientApplication,但这允许我在需要时以交互方式登录。
接下来,设置范围:
var scopes = new List<string>() { "https://graph.microsoft.com/.default" };
因为我想使用用户名和密码登录,所以我必须使用:
var token = await client.AcquireTokenInteractive(scopes).ExecuteAsync();
但如果我想使用代码登录,我也可以使用这个:
var password = new SecureString();
foreach (var c in <**password**>) { password.AppendChar(c); }
var token = await client.AcquireTokenByUsernamePassword(scopes, <**account**>, password).ExecuteAsync();
此时,我已被授权为指定用户。所以,现在我需要的就是获取 JSON 字符串中我喜欢的任何数据......
public static async Task<string> ExecCmd(string name, string url, string token)
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
string result = await GetHttpContentWithToken(url, token);
JObject json = JsonConvert.DeserializeObject(result) as JObject;
File.WriteAllText(name, json.ToString());
return result;
}
由于我只想将数据作为文本文件读取,因此我只需使用特定的操作执行操作并将其作为格式化的 JSON 写入文件。因此,通过这个简单的方法,我现在可以使用这个:
await ExecCmd("Profile.txt", "https://graph.microsoft.com/v1.0/me/", token.AccessToken);
await ExecCmd("Groups.txt", "https://graph.microsoft.com/v1.0/groups", token.AccessToken);
await ExecCmd("Users.txt", "https://graph.microsoft.com/v1.0/users", token.AccessToken);
这些将为我提供 (1) 当前用户的个人资料、(2) AD 组和 (3) AD 用户。或许还有一点...
如果我愿意,我可以使用此 ExecCmd 检索更多数据。但还有一点要记住!为了使这一切正常工作,您还需要配置 Azure 应用程序并确保分配并批准所有访问权限!
因此,在Azure AD中,你必须添加一个“应用程序注册”并摆弄设置......(Azure专家现在非常震惊,但是当你想学习时,你只需要尝试并失败,直到你成功...)
还将注册应用程序的“默认客户端类型”设置为“公共客户端”。
在Azure中,使用注册的应用程序,您还需要设置适当的API权限!否则,您将无权访问。由于我想要访问 Active Directory,我需要添加对“Azure Active Directory Graph”的权限。我可以在 Azure 中执行此操作,也可以在调用 AcquireTokenInteractive() 时使用范围来执行此操作。例如,通过使用“https://graph.windows.net/Directory.Read.All https://graph.windows.net/Directory.Read.All“ 代替 ”https://graph.windows.net/.default https://graph.windows.net/.default”。
以交互方式访问令牌后,您还可以使用 client.AcquireTokenSilent() 获取更多令牌。从这里开始就有点棘手了,特别是如果你想访问很多不同的项目。幸运的是,Active Directory 主要是目录本身、组、用户和成员。
就我个人而言,我更喜欢从 Azure 网站授予访问权限,但这非常有趣。
无论如何,我想使用 Azure 对用户进行身份验证现在我知道该怎么做了。它还留下了很多问题,但这一切基本上都回答了我的问题......
我将用它作为答案,因为其他人可能会发现它有用......