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

IdentityServer4+Blazor部署Azure后频繁出现无效授权码问题求助

问题:IdentityServer4 搭配 Blazor 部署至 Azure 后间歇性出现「Invalid authorization code」错误

本地环境下身份验证流程正常,但部署到Azure后,原本正常的流程现在突然报错,页面卡在https://websiteurl.com/signin-oidc。查看Identity Server日志,发现如下错误:

IdentityServer4.Validation.TokenRequestValidator: Invalid authorization code

该问题为间歇性触发,出现概率超过50%。我尝试通过以下代码生成自定义codeVerifier,并在重定向到Identity Server前添加相关参数:

if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
{
    // 生成 code_verifier
    var codeVerifier = CryptoRandom.CreateUniqueId(32);

    // 存储 codeVerifier 后续使用
    context.Properties.Items.Remove(CODE_VERIFIER_KEY);
    context.Properties.Items.Add(CODE_VERIFIER_KEY, codeVerifier);

    Logger.Log(LogLevel.Information, CODE_VERIFIER_KEY + ": " + codeVerifier);

    // 创建 code_challenge
    string codeChallenge;
    using (var sha256 = SHA256.Create())
    {
        var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
        codeChallenge = Base64Url.Encode(challengeBytes);
    }

    // 向请求中添加 code_challenge 和 code_challenge_method
    context.ProtocolMessage.Parameters.Remove(CODE_CHALLENGE_KEY);
    context.ProtocolMessage.Parameters.Remove(CODE_CHALLENGE_METHOD_KEY);
    Logger.Log(LogLevel.Information, CODE_CHALLENGE_KEY + ": " + codeChallenge);
    context.ProtocolMessage.Parameters.Add(CODE_CHALLENGE_KEY, codeChallenge);
    context.ProtocolMessage.Parameters.Add(CODE_CHALLENGE_METHOD_KEY, "S256");
}

同时配置了OnAuthorizationCodeReceived事件处理:

OnAuthorizationCodeReceived = (context) =>
{
    Logger.Log(LogLevel.Information, "OnAuthorizationCodeReceived - " + context.TokenEndpointRequest.Parameters);

    if (context.TokenEndpointRequest?.GrantType == OpenIdConnectGrantTypes.AuthorizationCode)
    {
        // 获取存储的 code_verifier,此条件从未触发
        if (context.Properties.Items.TryGetValue(CODE_VERIFIER_KEY, out var codeVerifier))
        {
            // 将 code_verifier 添加到令牌请求
            context.TokenEndpointRequest.Parameters.Add(CODE_VERIFIER_KEY, codeVerifier);
        }
    }

    return Task.CompletedTask;
},

但实际运行中,OnAuthorizationCodeReceived里获取存储的codeVerifier的条件从未执行,问题仍未解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:15:19