在 Azure(microsoft graph)委托流程中未获取刷新令牌

问题描述 投票:0回答:1

我正在开发一个项目,需要在用户的 Outlook 日历中创建事件。要求是将工作检查日期添加到相关用户的日历中。此外,用户应该能够在其日历上手动创建事件。

我做了什么:

  1. 我已经在azure上创建了应用程序。我已经添加了必要的权限。

  1. 我首先在虚拟项目上创建函数。在那个项目中我成功地...

这是代码

// Define routes
router.get('/login', getAuthCodeUrl);
router.get('/callback', handleCallback);

// In controller
const { ConfidentialClientApplication } = require('@azure/msal-node');

// TEST APP
const clientId = '945bf51b-xxxx-c5a83898b4b8';
const clientSecret = '9mV8Q~xxxx.zf9GqLGt95UUJ_bGdcp';

const msalConfig = {
  auth: {
    clientId: clientId,
    authority: `https://login.microsoftonline.com/common`,
    clientSecret: clientSecret,
  },
};

const redirectUri = 'http://localhost:3000/api/callback';

const scopes = [
  'User.Read',
  'Calendars.ReadWrite',
  'offline_access',
  'openid',
  'profile',
];

const cca = new ConfidentialClientApplication(msalConfig);

const getAuthCodeUrl = async (req, res) => {
  const authCodeUrlParameters = {
    scopes,
    redirectUri,
  };

  const authUrl = await cca.getAuthCodeUrl(authCodeUrlParameters);
  console.log('authUrl: ', authUrl);
  res.redirect(authUrl);
};

const handleCallback = async (req, res) => {  
  console.log('req.query: ', req.query);

  const tokenRequest = {
    scopes,
    code: req.query.code,
    redirectUri,
  };
  console.log('tokenRequest: ', tokenRequest);

  try {
    const authResult = await cca.acquireTokenByCode(tokenRequest);
    console.log('authResult: ', authResult);

    // Handle token result, store tokens, etc.
    res.send('Authentication successful. You can close this window.');
  } catch (error) {
    console.error('Error obtaining access token:', error);
    res.status(500).send('Error obtaining access token');
  }
};

当我访问

http://localhost:3000/api/login
时,我被重定向到 Microsoft 登录页面。登录后我就开始了
handleCallback

问题是我只获取访问令牌,响应中缺少刷新令牌

{
  authority: 'https://login.microsoftonline.com/common/',
  uniqueId: '00000000-xxxx-ddd3b41006de',
  tenantId: '9188040d-xxxx-36a304b66dad',
  scopes: [ 'User.Read', 'Calendars.ReadWrite', 'openid', 'profile' ],
  account: {
    homeAccountId: '00000000-0000-xxxx.9188040d-6c67-4c5b-b112-36a304b66dad',
    environment: 'login.windows.net',
    tenantId: '9188040d-xxxx-36a304b66dad',
    username: '[email protected]',
    localAccountId: '00000000-xxxx-ddd3b41006de',
    name: 'Nikhil',
    nativeAccountId: undefined,
    authorityType: 'MSSTS',
    tenantProfiles: Map(1) { '9188040d-xxxx-36a304b66dad' => [Object] },
    idTokenClaims: {
      ver: '2.0',
      iss: 'https://login.microsoftonline.com/9188040d-xxxx-36a304b66dad/v2.0',
      sub: 'AAAAAAAAAAAAXXXXoWCiSKHIxQiLR5lA',
      aud: '945bf51b-xxxx-c5a83898b4b8',
      exp: 1710826775,
      iat: 1710740075,
      nbf: 1710740075,
      name: 'Nikhil Mandaniya',
      preferred_username: '[email protected]',
      oid: '00000000-xxxx-ddd3b41006de',
      tid: '9188040d-xxxx-36a304b66dad',
      aio: 'Dv2WQYyaZYlVxxxxsgCzJieAfDrhNDIE6Drp'
    },
    idToken: 'eyJ0eXAiOiJKV1QiLCJhxxxxoQ'
  },
  idToken: 'eyJ0eXAiOiJKV1QiLCJhxxxxoQ',
  idTokenClaims: {
    ver: '2.0',
    iss: 'https://login.microsoftonline.com/9188040d-xxxx-36a304b66dad/v2.0',
    sub: 'AAAAAAAAAAAAAAAAAAAAAICmPO0oWCiSKHIxQiLR5lA',
    aud: '945bf51b-xxxx-c5a83898b4b8',
    exp: 1710826775,
    iat: 1710740075,
    nbf: 1710740075,
    name: 'Nikhil Mandaniya',
    preferred_username: '[email protected]',
    oid: '00000000-xxxx-ddd3b41006de',
    tid: '9188040d-xxxx-36a304b66dad',
    aio: 'Dv2WQYyaZYlV19mDrMstNPvJY*xxxxDrhNDIE6Drp'
  },
  accessToken: 'EwBwA8l6BAAUTTy6dbu0OLf3Lzl3RxxxxzaNAg==',
  fromCache: false,
  expiresOn: 2024-03-18T06:39:35.000Z,
  extExpiresOn: 2024-03-18T07:39:35.000Z,
  refreshOn: undefined,
  correlationId: '7a3447ce-xxxx-761ea0a35fde',
  requestId: '29ad5633-xxxx-9f42812f1700',
  familyId: '',
  tokenType: 'Bearer',
  state: '',
  cloudGraphHostName: '',
  msGraphHost: '',
  code: undefined,
  fromNativeBroker: false
}

我不确定我做错了什么。什么是 idToken,我需要在某个地方使用它吗? 根据我的要求,我计划使用刷新令牌获取新的访问令牌。 我愿意接受建议。

node.js azure azure-active-directory microsoft-graph-api azure-ad-msal
1个回答
0
投票

评论中的建议帮助我获得了刷新令牌。

为面临同样问题的人发布答案。

我们必须从令牌缓存中获取刷新令牌。我就是这样做的。

const handleCallback = async (req, res) => {
  const tokenRequest = {
    scopes,
    code: req.query.code,
    redirectUri,
    accessType: 'offline',
  };

  try {
    const authResult = await cca.acquireTokenByCode(tokenRequest);

    const accessToken = authResult.accessToken;

    const refreshToken = () => {
      const tokenCache = cca.getTokenCache().serialize();
      const refreshTokenObject = JSON.parse(tokenCache).RefreshToken;
      const refreshToken =
        refreshTokenObject[Object.keys(refreshTokenObject)[0]].secret;
      return refreshToken;
    };

    const tokens = {
      accessToken,
      refreshToken: refreshToken(),
    };

    console.log('tokens: ', tokens);

    // Handle token result, store tokens, etc.
    res.send('Authentication successful. You can close this window.');
  } catch (error) {
    console.error('Error obtaining access token:', error);
    res.status(500).send('Error obtaining access token');
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.