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

.NET 6迁移后Azure App Service Easy Auth无法获取用户身份及声明求助

解决方案

针对你的.NET 6迁移后无法通过Easy Auth获取用户声明的问题,以下是具体的配置步骤和排查点:

1. 使用正确的App Services认证中间件配置

放弃直接使用OpenIdConnect的配置(这会绕过App Service的Easy Auth层,与你保留原有/.auth端点的需求冲突),改用AppServicesAuthentication并补充必要的选项:

builder.Services.AddAuthentication(AppServicesAuthenticationDefaults.AuthenticationScheme)
    .AddAppServicesAuthentication(options =>
    {
        // 确保认证方案被正确转发
        options.ForwardDefaultAuthenticateScheme = AppServicesAuthenticationDefaults.AuthenticationScheme;
        options.ForwardDefaultChallengeScheme = AppServicesAuthenticationDefaults.AuthenticationScheme;
        // 可选:手动补充声明(如果默认读取的信息不全)
        options.Events = new AppServicesAuthenticationEvents
        {
            OnCreatingTicket = context =>
            {
                var email = context.Request.Headers["X-MS-CLIENT-PRINCIPAL-NAME"].FirstOrDefault();
                if (!string.IsNullOrEmpty(email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, email));
                }
                return Task.CompletedTask;
            }
        };
    });

2. 确保中间件顺序正确

在Program.cs中,认证中间件必须在授权中间件之前,且位于路由中间件之后:

var app = builder.Build();

// 基础中间件(如HTTPS重定向、静态文件)
app.UseHttpsRedirection();
app.UseStaticFiles();

// 路由中间件
app.UseRouting();

// 认证、授权中间件顺序不能颠倒
app.UseAuthentication();
app.UseAuthorization();

// 映射API和页面端点
app.MapControllers();

// 配置允许匿名访问的路径(首页、客户端下载)
app.MapGet("/", () => Results.Content("首页内容", "text/html"))
   .AllowAnonymous();
app.MapGet("/client-download", () => Results.File("path/to/your/client-installer", "application/octet-stream"))
   .AllowAnonymous();

app.Run();

3. 检查App Service层面的Easy Auth配置

  • 确认App Service应用设置中WEBSITE_AUTH_ENABLED的值为true。
  • 验证"Action to take when request is not authenticated"设置为Allow anonymous requests (no action),匹配你允许首页/下载匿名访问的需求。
  • 确保AAD和Google身份提供者的配置未被修改,且/.auth/login/aad等端点可正常跳转认证。

4. 验证用户声明读取

在需要认证的控制器方法中,直接读取User.Identity信息,示例:

[Authorize]
[ApiController]
[Route("api/user")]
public class UserController : ControllerBase
{
    [HttpGet("profile")]
    public IActionResult GetUserProfile()
    {
        if (User.Identity?.IsAuthenticated != true)
        {
            return Unauthorized();
        }
        
        var email = User.FindFirstValue(ClaimTypes.Email);
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        
        return Ok(new { Email = email, UserId = userId });
    }
}

关键说明

Easy Auth是App Service层面的代理认证,它会将用户信息通过请求头(如X-MS-CLIENT-PRINCIPAL-NAME、X-MS-CLAIMS)传递给后端应用。AppServicesAuthentication中间件的核心作用就是解析这些头信息,自动生成ClaimsIdentity并赋值给User.Identity。之前的配置失效大概率是因为中间件顺序错误,或未正确设置转发方案导致认证上下文未被初始化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:55:18