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

使用Azure WsFederation认证EF Core实现时授权失败求助

问题:WsFederation授权失败,提示需要已认证用户

错误信息

Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user. <s:Microsoft.AspNetCore.Authorization.DefaultAuthorizationService>

联合服务配置代码

if (!iis && !httpSys)
{
    // Information - DEBUG
    Serilog.Log.Information("Using Kestrel");

    // Environment uses Kestrel and WsFederation
    services.AddAuthentication(WsFederationDefaults.AuthenticationScheme)
        .AddWsFederation(WsFederationDefaults.AuthenticationScheme, options => 
        { 
            options.Wtrealm = config.GetValue<string>("Authentication:Microsoft:WsFederation:Wtrealm");
            options.MetadataAddress = config.GetValue<string>("Authentication:Microsoft:WsFederation:MetadataAddress");
            options.RequireHttpsMetadata = true;
            options.Events = new WsFederationEvents
            {
                OnRedirectToIdentityProvider = context =>
                {
                    context.ProtocolMessage.Whr = "Authentication:Microsoft:WsFederation:Whr";
                    return Task.CompletedTask;
                }
            };
            options.Wreply = config.GetValue<string>("Authentication:Microsoft:WsFederation:Wreply");
        }
    );
    
    // Configure authorization policies
    services.AddAuthorization(options =>
    {
        options.AddPolicy("WsfPolicy", builder =>
            {
                builder.RequireAuthenticatedUser();
                builder.AuthenticationSchemes = new[] { WsFederationDefaults.AuthenticationScheme };
            }
        );
    });
}

控制器代码

[Authorize(Policy = "WsfPolicy")]
[HttpGet]
[Route("lkMeasures")]
[Produces("application/json")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ICollection<LkMeasure>))]
[ProducesErrorResponseType(typeof(void))]
public async Task<IActionResult> AllItems()
{
    var allItems = await _lookupsService.AllMeasures();
    return Ok(allItems);
}

排查解决方案

  • 检查中间件顺序:在Configure方法中,必须先调用app.UseAuthentication(),再调用app.UseAuthorization(),否则授权逻辑无法读取已认证用户的信息。
  • 修正Whr配置:当前代码直接把配置键名赋值给了Whr,应该从配置中读取实际值,替换为:
    context.ProtocolMessage.Whr = config.GetValue<string>("Authentication:Microsoft:WsFederation:Whr");
    
    错误的Whr值会导致身份提供商无法正确处理认证请求,进而无法生成有效的用户身份。
  • 验证核心配置参数:确认Wtrealm、MetadataAddress、Wreply的配置值与身份提供商(如ADFS、Azure AD)的设置完全一致,尤其是Wtrealm必须是信赖方的唯一标识符。
  • 确保HTTPS环境:因为配置中开启了RequireHttpsMetadata = true,如果本地开发未启用HTTPS,会导致元数据加载失败,认证流程无法启动。可以在启动项目时启用HTTPS,或者临时将该值设为false进行测试(生产环境必须保持true)。
  • 设置默认认证方案:在AddAuthentication时显式指定默认认证和挑战方案,确保授权策略能正确触发认证跳转:
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = WsFederationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
    })
    .AddWsFederation(WsFederationDefaults.AuthenticationScheme, options => 
    {
        // 原配置内容
    });
    
  • 测试认证跳转:访问lkMeasures接口时,检查是否自动跳转到身份提供商的登录页面。如果没有跳转,说明认证中间件未正确触发,需重新核对中间件顺序和默认方案配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:35:04