[azure] What to do after the refresh token of the spa of the office 365 mailbox auth2 authentication expires

Reference: https://learn.microsoft.com/zh-cn/azure/active-directory/develop/refresh-tokens

Official description of token and refresh token life cycle

insert image description here

How does an expired refresh token get a new token and refresh token

/**
 * office 365使用失效的刷新令牌和应用程序的相关信息来获取新的访问令牌和刷新令牌
 * @param oldRefreshToken 已过期的刷新令牌
 */
export const officeGetNewRefreshToken = async (oldRefreshToken) => {
    
    
  const tokenEndpoint = `https://login.microsoftonline.com/${
      
      off_tenant}/oauth2/v2.0/token`;

  const requestBody = {
    
    
    client_id: off_clientId,
    // client_secret: off_clientSecret,
    grant_type: 'refresh_token',
    refresh_token: oldRefreshToken,
    redirect_uri: off_redirectUri, // 请修改为适当的重定向 URI
  };

  try {
    
    
    const response = await axios.post(tokenEndpoint, qs.stringify(requestBody), {
    
    
      headers: {
    
     'vv-origin': 'http://localhost', 'Content-Type': 'application/x-www-form-urlencoded' },
    });

    const newAccessToken = response.data.access_token;
    const newRefreshToken = response.data.refresh_token;

    // 使用新的访问令牌和刷新令牌调用 API 或进行其他操作
    console.log('新的访问令牌:', newAccessToken);
    console.log('新的刷新令牌:', newRefreshToken);
  } catch (error) {
    
    
    console.error('获取新的令牌失败:', error.response.data);
  }
};

How to test whether the refresh token has expired, refer to the figure below, the easiest way is to modify the account password

insert image description here

Unexpired Refresh Token Get a new Access Token and Refresh Token

  const params = {
    
    
    client_id: off_clientId,
    scope: off_scopes.join(' '),
    refresh_token: refreshToken,
    grant_type: 'refresh_token',
  };

  axios
    .post(url, params, {
    
    
      headers: {
    
    
        'Content-Type': 'application/x-www-form-urlencoded',
        'vv-origin': 'http://localhost',
      },
    })
    .then((res) => {
    
    
      console.log('success===>', res);
      if (res && res.data) {
    
    
        const data = res.data;
        // 获得刷新后的token和refreshToken
        const opts = {
    
    
          serviceId,
          refreshToken: data.refresh_token,
          accessToken: data.access_token,
          expiresIn: data.expires_in,
          email,
        };
        console.log('使用刷新令牌从office获取新的访问令牌', data, opts);
        updateBindEmailInfo(opts);
      }
    });

Guess you like

Origin blog.csdn.net/hzxOnlineOk/article/details/131438539