【发布时间】:2019-04-06 03:54:43
【问题描述】:
我在控制台应用程序中成功地从 Azure Active Directory 检索了授权令牌。我想将此代码转换为 .Net Core MVC,但不确定如何在 Startup.cs 中干净地配置所有内容
我假设键/值对将被移动到 appsettings.json,但我如何在ConfigureServices() 下获取此令牌?
var client = new HttpClient();
var uri = "https://login.microsoftonline.com/<tenantid>/oauth2/token";
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("resource", "{resourceID}"),
new KeyValuePair<string, string>("client_id", "{clientID}"),
new KeyValuePair<string, string>("client_secret", "{clientSecret}"),
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("scope", "openid")
};
var content = new FormUrlEncodedContent(pairs);
var response = client.PostAsync(uri, content).Result;
string result = string.Empty;
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
JObject jObject = JObject.Parse(result);
string token = (string)jObject.SelectToken("access_token");
}
我应该使用以下方法之一来获取不记名令牌吗?我正在控制台应用程序中进行 POST,但这似乎不适用于启动配置。
services.AddAuthentication()
或
.AddJwtBearer()
【问题讨论】:
-
您正在编写 Web 应用程序吗?还是 Web API?如果您正在编写 Web 应用程序,我建议您查看以下示例:active-directory-aspnetcore-webapp-openidconnect-v2。它有 2 个部分: - 将用户登录到 Web 应用程序 - 为登录用户获取令牌以调用 API:在名为 [signInAndCallMsGraph ](github.com/Azure-Samples/…) 的分支中
-
另外,我不建议您像您一样获取访问令牌,尤其是您正在使用客户端凭据授予,这意味着有一个秘密(除非此控制台应用程序在具有非常受控访问)。 Auth 库将帮助您对所有类型的 scenarios 执行此操作,例如 MSAL.NET。看来你想做的是Acquiring a token for the app
-
好的,感谢您提供的示例,我让它运行并进行身份验证,但它不提供身份验证令牌。我正在尝试调用我在 Azure 中作为应用服务开发的现有 API
-
我正在查看 Jean-Marc 的其他示例流程,我会回复你@JoeyCai
标签: c# azure asp.net-core azure-active-directory azure-web-app-service