我有从微软获得令牌的功能。
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分钟刷新它。我什么都试过了,但都不管用。当我在间隔中刷新它时,我总是得到旧的令牌。请问各位有没有解决这个问题的方法?
1条答案
按热度按时间gopyfrb31#
scopes: ['https://graph.microsoft.com/.default']
用于客户端凭证,客户端凭证流生成的token是不能刷新的,当我们想要刷新访问令牌时,需要一个刷新令牌和一个访问令牌,只有auth代码流在生成访问令牌时才能提供刷新令牌。查看auth code flow和client credential flow的文档。如您所见,当您在作用域中添加
offline_access
以生成访问令牌时,可能会返回刷新令牌。但是凭证流的作用域只能是xxx/.default
,我们不能将offline_access
添加到客户端凭证流的作用域中。注意:仅在请求offline_access作用域时提供。