HttpClient调用Azure AD保护的站点

时间:2016-12-21 12:01:05

标签: c# azure cookies asp.net-core dotnet-httpclient

根据一些微软的样本,我得到了这一点:

ASP.NET核心设置:

app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = Configuration["Authentication:AzureAD:ClientId"],
    Authority = Configuration["Authentication:AzureAd:Authority"],
    ResponseType = OpenIdConnectResponseType.IdToken,
    AutomaticAuthenticate = true,
    TokenValidationParameters = new TokenValidationParameters()
});

AuthorizationTest端点:

[HttpGet]
[Authorize]
public IActionResult Get()
{
    return Ok("SAMPLE TEXT - if you can read this then call it a day :)");
}

客户端:

try
{
   var result = await authContext.AcquireTokenAsync(WebApiResourceId, WebApiClientId, WebApiRedirectUri, new PlatformParameters(PromptBehavior.Auto));
   authorizedClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

   var authorizedMessage = await authorizedClient.GetAsync("/AuthorizationTest");
   var statusCode = authorizedMessage.StatusCode.ToString();
   var message = await authorizedMessage.Content.ReadAsStringAsync();
   webBrowser.NavigateToString(message);
 }

authorizedClient启动为:

private static HttpClientHandler handler = new HttpClientHandler
{
    AllowAutoRedirect = true,
    CookieContainer = new CookieContainer(),
    UseCookies = true
 };
 private static HttpClient authorizedClient = new HttpClient(handler, false) { BaseAddress = WebApiBaseUri };

我以前只使用BaseAddress初始化它,后来在So上面的答案后面添加了处理程序。

问题:
即使我正确地从AAD获取令牌,来自WEB API端点的响应是HTML(在自动重定向之后),即MS登录页面,其中包含错误“Your browser is set to block cookies.....

我应该更改什么才能使HttpClient工作?或者我可以将WebApi配置更改为不使用cookie吗?对于后一种选择,我找不到任何其他选择。

2 个答案:

答案 0 :(得分:3)

正如评论中所讨论的,您需要使用包Microsoft.AspNetCore.Authentication.JwtBearer中的JWT承载令牌中间件。

Open ID Connect中间件旨在将用户重定向到登录页面,而不是用于验证访问令牌。可以在此处找到JWT承载令牌中间件的示例用法:https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore/blob/master/TodoListService/Startup.cs

答案 1 :(得分:0)

看一下这个帖子:https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/514 - 它显示了你想要实现的场景。