HttpClient 调用受 Azure AD 保护的站点

SO *_*ood 2 c# cookies azure dotnet-httpclient asp.net-core

根据一些 Microsoft 示例,我得到了这一点:

ASP.NET Core 设置:

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()
});
Run Code Online (Sandbox Code Playgroud)

授权测试端点:

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

客户:

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);
 }
Run Code Online (Sandbox Code Playgroud)

authorizedClient启动方式为:

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

我过去只使用 BaseAddress 来初始化它,后来按照 So 上的答案添加了处理程序。

问题:
即使我正确地从 AAD 获取令牌,WEB API端点的响应也是一个 HTML(自动重定向后),即带有错误“ Your browser is set to block cookies.....”的 MS 登录页面

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

juu*_*nas 5

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

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