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

Azure AD B2C授权码流(PKCE)下访问令牌过期自动登出实现问题

解决方案

MSAL库默认开启了访问令牌过期后静默使用刷新令牌换发新令牌的逻辑,你需要关闭该默认行为并配合事件监听、配置调整实现到期自动登出,具体操作步骤如下:

1. 关闭MSAL自动静默续约配置

初始化PublicClientApplication时,将automaticSilentRenew参数设置为false,禁用自动刷新令牌逻辑,参考配置如下:

const msalConfig = {
  auth: {
    clientId: "你的应用客户端ID",
    authority: "你的Azure AD B2C策略权威地址",
    knownAuthorities: ["你的B2C租户域名"],
    redirectUri: "你的应用重定向地址"
  },
  cache: {
    cacheLocation: "localStorage",
    storeAuthStateInCookie: false
  },
  // 核心配置:关闭自动静默续约
  automaticSilentRenew: false
};

2. 监听账号过期事件触发自动登出

注册MSAL全局事件回调,监听ACCOUNT_EXPIRED事件,触发时直接调用登出逻辑:

import { EventType } from "@azure/msal-browser";

msalInstance.addEventCallback((event) => {
  if (event.eventType === EventType.ACCOUNT_EXPIRED) {
    msalInstance.logoutRedirect({
      postLogoutRedirectUri: "你的应用登出后跳转地址"
    });
  }
});

3. 修复自定义策略刷新令牌配置不生效问题

你之前配置的刷新令牌超时未生效,是因为缺少配对配置:

  • 在自定义策略的RelyingParty节点中,需要同时配置RefreshTokenLifetimeInSeconds(单次刷新令牌有效期)和RollingRefreshTokenLifetimeInSeconds(刷新令牌最长总有效期),如果仅配置前者,后者默认会持续到用户密码变更才失效,自然看不到超时效果
  • 确认自定义策略的UserJourney节点没有重写令牌生命周期的相关配置

4. React层增加主动校验逻辑

配合@azure/msal-react的能力,在路由守卫或者接口请求前主动校验令牌有效性,无法获取有效令牌时直接登出:

import { useMsal } from "@azure/msal-react";
import { InteractionRequiredAuthError } from "@azure/msal-browser";

const useTokenValidCheck = () => {
  const { instance, accounts } = useMsal();

  const checkValid = async () => {
    try {
      await instance.acquireTokenSilent({
        scopes: ["你配置的接口权限范围"],
        account: accounts[0]
      });
      return true;
    } catch (e) {
      if (e instanceof InteractionRequiredAuthError) {
        await instance.logoutRedirect();
        return false;
      }
      throw e;
    }
  };
  return checkValid;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:36:04