【问题标题】:How do I pass the windows authentication token on a web request to an api?如何将 Web 请求中的 Windows 身份验证令牌传递给 api?
【发布时间】:2022-01-09 23:44:49
【问题描述】:

在 ASP.NET Core 5 中,我是否可以使用 Windows 身份验证(允许 IIS 对用户进行身份验证)并以某种方式获取该令牌,然后使用它来调用也通过 Windows 身份验证进行身份验证的 Web API 应用程序?换句话说,我们希望 API 应用程序中的安全上下文与我们在 UI 应用程序中的安全上下文相同。这可能吗?

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(IISDefaults.AuthenticationScheme);
    var commonApiSettings = Configuration.GetSection("CommonApiSettings").Get<CommonApiSettings>(); 
    services.AddHttpClient("CommonApi",
                    client =>
                    {
                        client.BaseAddress = new Uri(commonApiSettings.BaseAddress);
                        client.DefaultRequestHeaders.Add("Accept", "application/json");
                        client.DefaultRequestHeaders.Add("User-Agent", "AspNetCore-Demo");
                    });
    services.AddControllersWithViews();
}

然后在我的控制器中我想调用一个 web api。每次我得到 401 Unauthorized.

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly IHttpClientFactory _clientFactory;

    public HomeController(ILogger<HomeController> logger, IHttpClientFactory httpClient)
    {
        _logger = logger;
        _clientFactory = httpClient;
    }

    public async Task<IActionResult> Index()
    {

        IEnumerable<Confection> inventory;

        try
        {
            var user = (WindowsIdentity)User.Identity!;

            await WindowsIdentity.RunImpersonatedAsync(user.AccessToken, async () =>
            {

                var impersonatedUser = WindowsIdentity.GetCurrent();
                var message =
                    $"User: {impersonatedUser.Name}\t" +
                    $"State: {impersonatedUser.ImpersonationLevel}";

                var bytes = Encoding.UTF8.GetBytes(message);
          
                var httpClient = _clientFactory.CreateClient("CommonApi");
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", impersonatedUser.AccessToken.ToString());
                var request = new HttpRequestMessage(HttpMethod.Get, "");

                var httpResponseMessage = await httpClient.SendAsync(request);

                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    using var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync();
                    inventory = await JsonSerializer.DeserializeAsync<IEnumerable<Confection>>(contentStream);
                }
            });
        }
        catch (Exception e)
        {
            //await context.Response.WriteAsync(e.ToString());
        }

        return View();
    }

【问题讨论】:

    标签: c# asp.net-core asp.net-core-webapi windows-authentication


    【解决方案1】:

    要发送 Windows 凭据,您需要设置 HttpClient 使用的 HttpClientHandlerUseDefaultCredentials 属性。在the documentation 中有一个如何使用IHttpClientFactory 执行此操作的示例。

    在你的情况下,它应该是这样的:

    services.AddHttpClient("CommonApi",
                    client =>
                    {
                        client.BaseAddress = new Uri(commonApiSettings.BaseAddress);
                        client.DefaultRequestHeaders.Add("Accept", "application/json");
                        client.DefaultRequestHeaders.Add("User-Agent", "AspNetCore-Demo");
                    })
                .ConfigurePrimaryHttpMessageHandler(() =>
                    new HttpClientHandler
                    {
                        UseDefaultCredentials = true
                    });
    

    【讨论】:

      猜你喜欢
      • 2019-09-01
      • 2021-04-13
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 2015-02-24
      • 2019-06-16
      • 1970-01-01
      相关资源
      最近更新 更多