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

自定义AuthenticationHandler的ChallengeAsync未获取失败属性的原因

问题原因

当HandleAuthenticateAsync返回AuthenticateResult.Fail(..., properties)时,ASP.NET Core认证中间件不会自动将失败结果里的Properties传递到后续的HandleChallengeAsync方法中。默认情况下,HandleChallengeAsync接收的properties是独立初始化的空集合,因此你自定义的Items不会被自动带入。

解决方案

在自定义的PasetoBearerHandler中重写HandleChallengeAsync方法,从认证上下文的AuthenticateResult中提取失败时设置的属性,并合并到当前的properties里:

protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
    // 获取认证失败的结果对象
    if (Context.AuthenticateResult is AuthenticateResult.Failed failedResult)
    {
        // 将失败结果中的自定义Items合并到当前properties
        foreach (var (key, value) in failedResult.Properties?.Items ?? Enumerable.Empty<KeyValuePair<string, string>>())
        {
            properties.Items.TryAdd(key, value);
        }
    }

    // 执行基类的Challenge逻辑,或添加自定义处理逻辑
    await base.HandleChallengeAsync(properties);
}
额外说明

你的中间件顺序配置是正确的(UseRouting → UseAuthentication → UseAuthorization),这不是导致问题的原因。关键在于认证失败结果的属性不会自动流转到Challenge流程中,需要手动关联。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:55:02