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

.NET Core 2.0 API同时启用双验证时如何获取Windows用户名?

解决.NET Core 2.0同时启用Windows与匿名验证时无法获取用户名的问题

我之前也碰到过一模一样的问题!当同时打开Windows和匿名验证时,.NET Core 默认不会自动触发Windows身份验证流程——毕竟匿名是“默认”选项,除非你明确指定哪些端点需要强制Windows认证,或者在需要的时候手动触发认证。下面是我当时的解决步骤,亲测有效:

1. 先搞定基础配置

首先确保项目的验证开关都开对:

  • 在launchSettings.json里,找到iisSettings节点,把windowsAuthentication和anonymousAuthentication都设为true:
"iisSettings": {
  "windowsAuthentication": true,
  "anonymousAuthentication": true,
  "iisExpress": {
    "applicationUrl": "http://localhost:xxxx",
    "sslPort": 0
  }
}
  • 如果是部署到IIS服务器,记得在站点的“身份验证”功能里,同时启用“Windows身份验证”和“匿名身份验证”,别漏了!

2. 配置Startup.cs的认证与授权

在Startup.cs的ConfigureServices方法里,注册Windows认证服务,并创建一个专门的授权策略来区分需要Windows认证的端点:

using Microsoft.AspNetCore.Authentication.IIS;
using Microsoft.AspNetCore.Authorization;

public void ConfigureServices(IServiceCollection services)
{
    // 注册Windows认证服务
    services.AddAuthentication(IISDefaults.AuthenticationScheme);
    
    // 配置授权策略:指定需要Windows认证的规则
    services.AddAuthorization(options =>
    {
        options.AddPolicy("RequireWindowsAuth", policy =>
        {
            policy.RequireAuthenticatedUser();
            policy.AddAuthenticationSchemes(IISDefaults.AuthenticationScheme);
        });
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_0);
}

然后在Configure方法里,一定要把UseAuthentication()放在UseMvc()之前,这很关键:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // 启用认证中间件
    app.UseAuthentication();

    app.UseMvc();
}

3. 给端点标记授权规则

现在你可以灵活控制每个端点的访问权限了:

  • 对于完全允许匿名的端点,加上[AllowAnonymous]属性:
[AllowAnonymous]
[HttpGet("public-data")]
public IActionResult GetPublicData()
{
    return Ok("这是公开数据,任何人都能访问");
}
  • 对于必须Windows认证的端点,用我们刚才定义的策略标记:
[Authorize(Policy = "RequireWindowsAuth")]
[HttpGet("user-info")]
public IActionResult GetUserInfo()
{
    // 这里可以安全获取用户名,因为已经过认证
    var userName = User.Identity.Name;
    return Ok($"当前Windows用户:{userName}");
}

4. 处理“混合模式”端点(既允许匿名,又能获取登录用户信息)

如果有些端点需要同时支持匿名访问和已认证用户的信息获取(比如匿名用户看到默认内容,登录用户看到个性化内容),你可以手动触发Windows认证,而不是依赖自动流程:

[AllowAnonymous]
[HttpGet("mixed-content")]
public async Task<IActionResult> GetMixedContent()
{
    // 手动尝试Windows认证
    var authResult = await HttpContext.AuthenticateAsync(IISDefaults.AuthenticationScheme);
    
    if (authResult.Succeeded)
    {
        // 认证成功,获取用户名
        var userName = authResult.Principal.Identity.Name;
        return Ok($"欢迎你,{userName}!这是个性化内容");
    }
    else
    {
        // 匿名用户逻辑
        return Ok("欢迎匿名用户!这是通用内容");
    }
}

5. 解决代码异常的问题

你提到启用匿名后出现异常,大概率是因为你在未认证的情况下直接访问User.Identity.Name——这时候User.Identity可能是null,自然会抛出NullReferenceException。解决方法很简单:
在访问Identity相关属性前,先判断是否已认证:

// 错误写法:直接访问可能抛异常
// var userName = User.Identity.Name;

// 正确写法:先检查
if (User.Identity != null && User.Identity.IsAuthenticated)
{
    var userName = User.Identity.Name;
    // 处理逻辑
}
else
{
    // 匿名处理
}

按照上面的步骤来,应该就能同时满足匿名访问和Windows认证的需求,也能正常获取到Windows用户名了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:36:05