【发布时间】:2017-10-25 05:55:11
【问题描述】:
我已经浏览了有关使用 Oauth 在线保护 Azure Active Directory 中的 WebAPI 的所有教程。但不幸的是,它们都不能工作。
我使用的是 VS 2017,我的项目是 .net core。
到目前为止,我尝试过的是:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
ervices.AddAuthentication(); // -----------> newly added
}
在“配置”中,我添加了:
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Authority = String.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAD:Tenant"]),
Audience = Configuration["AzureAd:Audience"],
});
这是我的配置:
"AzureAd": {
"AadInstance": "https://login.microsoftonline.com/{0}",
"Tenant": "tenantname.onmicrosoft.com",
"Audience": "https://tenantname.onmicrosoft.com/webapiservice"
}
我已经在我的 AAD 上注册了这个“webapiservice”(链接是:http://webapiservice.azurewebsites.net)。
另外,为了访问这个 web api 服务,我创建了一个 webapi 客户端“webapiclient”,它也是一个 web api,并且还在我的 AAD 上注册了它并请求访问“webapiservice”的权限。 webapi客户端链接为:http://webapiclient.azurewebsites.net
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://webapiservice.azurewebsites.net/");
//is this uri correct? should it be the link of webapi service or the one of webapi client?
HttpResponseMessage response = client.GetAsync("api/values").Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsAsync<IEnumerable<string>>().Result;
return result;
}
else
{
return new string[] { "Something wrong" };
}
所以理论上,我应该从 webapiservice 收到正确的结果。但我总是收到“有问题”。
我这里有什么遗漏吗?
【问题讨论】:
-
您没有将身份验证令牌添加到请求中?
-
什么意思?不是AAD管理的吗?
-
您的应用必须获取它。它可以使用各种方法来做到这一点,例如,它可以使用客户端 ID 和机密向 AAD 证明它是这个应用程序,并需要该 API 的令牌。然后,AAD 会给您一个令牌,您可以将其附加到请求中。
-
@juunas 那是我缺少的部分。如何从 AAD 检索访问令牌?你有一个例子来说明这一点吗?
标签: azure azure-active-directory asp.net-core-webapi