我有从微软获取令牌的功能。
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 分钟刷新该令牌......我尝试了所有方法,但没有任何效果。当我定期刷新它时,我总是得到旧的令牌。请问你们有什么解决这个问题的建议吗?