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

部署为Azure Web App时OnTokenValidated事件不触发,本地运行正常

问题说明

需要在运行时从数据库为Azure AD登录的用户添加自定义声明,本地VS 2019运行时逻辑完全正常,但发布为Azure Web App后OnTokenValidated事件始终未触发。

本地正常执行流程

  • Azure AD登录
  • 触发OnTokenValidated事件
  • 跳转至首页

Azure部署后异常执行流程

  • Azure AD登录
  • 直接跳转至首页,事件内的未处理除零异常也未触发报错

核心代码

services
.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
    Configuration.Bind("AzureAd", options);
    options.Events ??= new OpenIdConnectEvents();
    var onTokenValidated = options.Events.OnTokenValidated;
    options.Events.OnTokenValidated = ctx =>
    {
        onTokenValidated?.Invoke(ctx);

        var userId = "";
        if (ctx.Principal.FindFirstValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier") != null)
        {
            userId = ctx.Principal.FindFirstValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier");
        }
        else if (ctx.Principal.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier") != null)
        {
            userId = ctx.Principal.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier");
        }

        ResponseClass userConfig = AccountDataAccess.GetUserConfig(
            UserId: userId
        );

        if (userConfig.Success)
        {
            newClaims.Add(new Claim("SessionId", userConfig.SessionId));
            newClaims.Add(new Claim("Permission1", userConfig.Permission1));                          
        }

        var appIdentity = new ClaimsIdentity(newClaims);
        ctx.Principal.AddIdentity(appIdentity);
        return Task.CompletedTask;
    };
});

排查方案

  1. 关闭Azure Web App平台层面的身份验证配置
    登录Azure Portal,进入对应Web App的「身份验证」面板,确认没有额外配置Azure AD登录规则。如果开启了平台内置的身份验证(Easy Auth),身份验证流程会在网关层面完成,请求不会传递到应用代码,自然不会触发OnTokenValidated事件,关闭该配置即可。
  2. 修正异步调用逻辑
    当前代码对原有OnTokenValidated委托的调用是同步的,容易出现异步任务未完成就提前返回、异常被吞的问题,修改代码如下:
    options.Events.OnTokenValidated = async ctx =>
    {
        if (onTokenValidated != null)
        {
            await onTokenValidated(ctx);
        }
        // 剩余自定义逻辑保持不变
    };
    
  3. 核对部署环境配置
    确认发布后的配置中:
    • AzureAd节点的CallbackPath和Azure AD应用注册中配置的回调地址完全一致
    • 数据库连接字符串配置正确,没有权限访问、网络隔离等导致AccountDataAccess.GetUserConfig调用失败的问题
  4. 排除缓存影响
    测试时使用全新隐身窗口,关闭Azure Web App的会话亲和性,避免复用之前缓存的身份信息跳过事件触发逻辑。
  5. 开启应用日志排查
    在Azure Web App的「应用服务日志」面板开启应用程序日志,登录后查看日志是否有未捕获的异常导致流程中断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:06:08