You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular请求.NET Core 8时如何获取Windows用户?

解决方案:获取Windows用户并解决身份验证问题

一、Kestrel启用Windows身份验证

Kestrel支持Windows身份验证,只是默认未启用,需在Program.cs中添加配置:

var builder = WebApplication.CreateBuilder(args);

// 注册Windows身份验证服务
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
    .AddNegotiate();

builder.Services.AddControllers();
builder.Services.AddHttpContextAccessor();
// ...其他服务配置

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.Run();

同时修改launchSettings.json的http profile,强制启用Windows身份验证并关闭匿名访问:

"http": {
  "commandName": "Project",
  "dotnetRunMessages": true,
  "launchBrowser": true,
  "applicationUrl": "http://localhost:5015",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development",
    "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
  },
  "windowsAuthentication": true,
  "anonymousAuthentication": false
}

关闭匿名认证可避免默认匿名访问导致isAuthenticated = false

二、修复IIS Express的500错误

  1. 确认launchSettings.json中IIS Express的身份验证配置:
    "iisSettings": {
      "windowsAuthentication": true,
      "anonymousAuthentication": false,
      // ...其他配置
    }
    
  2. 控制器方法添加[Authorize]特性,确保触发身份验证流程:
    [Authorize]
    [HttpGet]
    public List<string> GetMyApi()
    {
        // 获取Windows用户信息
        var windowsUserName = httpContextAccessor.HttpContext.User.Identity.Name;
        var isAuthenticated = httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
        // ...业务逻辑
    }
    
  3. 检查IIS Express应用池设置:确保应用池使用集成模式,身份设置为ApplicationPoolIdentity或当前登录用户。

三、Angular代理与请求配置优化

  1. 更新proxy.config.js,添加changeOrigin和withCredentials确保凭据传递:
    const PROXY_CONFIG = [
      {
        context: [
          "/api/MyApi",
        ],
        target,
        secure: false,
        changeOrigin: true,
        withCredentials: true,
        onProxyRes: proxyRes => {
          const key = "www-authenticate";
          proxyRes.headers[key] = proxyRes.headers[key] &&
            proxyRes.headers[key].split(",");
        }
      }
    ]
    
  2. 确认Angular请求的withCredentials配置正确:
    this.http.get<string[]>('/api/MyApi', { withCredentials: true })
    

四、排查技巧

  • 检查浏览器是否弹出Windows身份验证对话框,未弹出则说明身份验证配置未生效
  • 在控制器中打印用户凭据详情,定位问题:
    var user = httpContextAccessor.HttpContext.User;
    foreach (var claim in user.Claims)
    {
        Console.WriteLine($"{claim.Type}: {claim.Value}");
    }
    
  • 确保客户端与服务器同源(开发环境localhost属于同源范围)

内容的提问来源于stack exchange,提问作者user6009865

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 04:47:16