【发布时间】:2020-03-04 03:36:35
【问题描述】:
我们创建了一个 ASP.net Core 网站并向其中添加了一个我们需要从守护进程访问的 API。该网站由 Azure AD 保护,守护程序通过 Azure 进行身份验证。在守护进程中,我使用站点用于获取令牌的相同应用程序凭据,但是当我尝试使用令牌访问网站 API 时,我被重定向到 Microsoft 登录页面。我不确定我错过了什么。我正在获取访问令牌。
在使用下面的 HttpClient 代码之前,我还尝试按照 https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-daemon-app-configuration?tabs=dotnet 的说明进行操作。
using (var _client = new HttpClient())
{
var Content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", ClientID),
new KeyValuePair<string, string>("client_secret", ClientSecret)
});
var Response = await
_client.PostAsync($"https://login.microsoftonline.com/[tenantUUID]/oauth2/token", Content);
if (Response.IsSuccessStatusCode)
{
var Token = JsonConvert.DeserializeObject<Data.Token>(await Response.Content.ReadAsStringAsync());
Console.WriteLine("AccessToken: " + Token.access_token);
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token.access_token);
Response = await _client.GetAsync("https://localhost:44318/api/notify");
Console.Write(await Response.Content.ReadAsStringAsync());
}
}
【问题讨论】:
-
你拿到token成功了吗?
-
是的。我可以在控制台上显示它。
-
@JimXu 我想我有,但会再看看
标签: c# asp.net-core azure-active-directory