使用Oauth通过Azure活动目录保护WebAPI

时间:2017-05-24 18:23:46

标签: azure azure-active-directory asp.net-core-webapi

我浏览了有关使用Oauth在线保护Azure Active Directory中的WebAPI的所有教程。但不幸的是,它们都无法发挥作用。

我正在使用VS 2017,我的项目是.net核心。

到目前为止,我所尝试的是:

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"
  }

我已经注册了这个" webapiservice" (链接是:http://webapiservice.azurewebsites.net)在我的AAD上。

另外,为了访问这个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收到正确的结果。但我总是收到&#34;出错了&#34;。

我在这里遗漏了什么吗?

2 个答案:

答案 0 :(得分:0)

要调用受azure广告保护的网络API,您应使用承载方案在授权标头中传递此获取的访问令牌:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

答案 1 :(得分:0)

您需要Azure AD中的访问令牌

GitHub上有很多很好的示例应用程序,这里有一个用于守护进程的应用程序:https://github.com/Azure-Samples/active-directory-dotnet-daemon/blob/master/TodoListDaemon/Program.cs#L96

AuthenticationResult authResult = await authContext.AcquireTokenAsync(todoListResourceId, clientCredential);

此应用程序使用其客户端ID和API的客户端密钥获取访问令牌。在您的情况下,您可以采用类似的方法。您可以将todoListResourceId替换为{ADA Graph API的"https://graph.windows.net/",或者将"https://graph.microsoft.com/"替换为Microsoft Graph API。这是您想要令牌的API的标识符。

这是它在AAD中的工作方式。您想要访问API,您要求AAD访问该API。在成功的响应中,您将获得一个访问令牌,您必须将其作为标题附加到HTTP调用:

Authorization: Bearer accesstokengoeshere......

现在,如果您正在构建Web应用程序,您可能希望以不同的方式执行此操作,因为您现在正在访问API作为客户端应用程序,而不是用户。如果您想拨打委托电话,则需要使用例如授权代码流程,您向用户显示浏览器,将其重定向到正确的地址,然后将其发送回您的应用程序以进行登录。