使用 Oauth 使用 Azure Active Directory 保护 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"
}

我已经在我的 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收到正确的结果。 但我总是收到"出事"。

我在这里错过了什么吗?

需要来自 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替换为 Azure AD 图形 API 的"https://graph.windows.net/",或Microsoft图形 API 的"https://graph.microsoft.com/"。这是要为其提供令牌的 API 的标识符。

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

Authorization: Bearer accesstokengoeshere......

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

若要调用受 Azure AD 保护的 Web API,应使用持有者方案在授权标头中传递此获取的访问令牌:

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

最新更新