刷新 client_credentials microsoft 令牌

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

我有从微软获取令牌的功能。

import { ConfidentialClientApplication } from '@azure/msal-node'
import { ConfigurationService } from './configuration/configuration.class.js'

export class TokenService {
  constructor(app) {
    this.app = app
    this.msalApplication = null
    this.accessToken = null
  }

  async initialize(configData) {
    try {
      // Find the values you need in the response data
      const clientId = configData.find((item) => item.setting === 'clientId')?.value
      const tenantId = configData.find((item) => item.setting === 'tenantId')?.value
      const clientSecret = configData.find((item) => item.setting === 'clientSecret')?.value

      // Check if all required values are present
      if (!clientId || !tenantId || !clientSecret) {
        throw new Error('Missing configuration values')
      }

      // Configure the MSAL application with the fetched values
      this.msalApplication = new ConfidentialClientApplication({
        auth: {
          clientId,
          authority: `https://login.microsoftonline.com/${tenantId}`,
          clientSecret,
          grant_type: 'client_credentials'
        }
      })
    } catch (error) {
      console.error('Error initializing TokenService:', error)
      throw error
    }
  }

  async getToken() {
    if (!this.msalApplication) {
      // Fetch the configuration values from the database using your ConfigurationService
      const configService = new ConfigurationService({
        Model: this.app.get('mssqlClient'),
        name: 'application_config' // Make sure this matches your FeathersJS database configuration
      })
      const configData = await configService.find()

      await this.initialize(configData)
    }

    // Pokud nemáme žádný platný token nebo je blízko k expiraci, získejte nový token
    if (!this.accessToken) {
      try {
        const tokenResponse = await this.msalApplication.acquireTokenByClientCredential({
          scopes: ['https://graph.microsoft.com/.default']
        })

        this.accessToken = tokenResponse.accessToken

        return this.accessToken
      } catch (error) {
        console.error('Error acquiring token:', error)
        this.accessToken = null

        throw error
      }
    }

    return this.accessToken
  }
}

它按预期工作,但我需要在令牌过期前 5 分钟刷新该令牌......我尝试了所有方法,但没有任何效果。当我定期刷新它时,我总是得到旧的令牌。请问你们有什么解决这个问题的建议吗?

javascript oauth-2.0 microsoft-graph-api access-token
1个回答
0
投票

scopes: ['https://graph.microsoft.com/.default']
用于客户端凭证,客户端凭证流生成的令牌是无法刷新的,当我们要刷新访问令牌时,我们需要刷新令牌和访问令牌,只有授权码流可以当您生成访问令牌时,为您提供刷新令牌。查看文档中的身份验证代码流程客户端凭证流程

如您所见,当您在范围中添加

offline_access
来生成访问令牌时,可以返回刷新令牌。但是凭证流的范围只能是
xxx/.default
,我们不能将
offline_access
添加到客户端凭证流的范围中。

注意:仅在请求offline_access范围时提供。

© www.soinside.com 2019 - 2024. All rights reserved.