oauth2.0 正在刷新client_credentials Microsoft令牌

iaqfqrcu  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(164)

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

  1. import { ConfidentialClientApplication } from '@azure/msal-node'
  2. import { ConfigurationService } from './configuration/configuration.class.js'
  3. export class TokenService {
  4. constructor(app) {
  5. this.app = app
  6. this.msalApplication = null
  7. this.accessToken = null
  8. }
  9. async initialize(configData) {
  10. try {
  11. // Find the values you need in the response data
  12. const clientId = configData.find((item) => item.setting === 'clientId')?.value
  13. const tenantId = configData.find((item) => item.setting === 'tenantId')?.value
  14. const clientSecret = configData.find((item) => item.setting === 'clientSecret')?.value
  15. // Check if all required values are present
  16. if (!clientId || !tenantId || !clientSecret) {
  17. throw new Error('Missing configuration values')
  18. }
  19. // Configure the MSAL application with the fetched values
  20. this.msalApplication = new ConfidentialClientApplication({
  21. auth: {
  22. clientId,
  23. authority: `https://login.microsoftonline.com/${tenantId}`,
  24. clientSecret,
  25. grant_type: 'client_credentials'
  26. }
  27. })
  28. } catch (error) {
  29. console.error('Error initializing TokenService:', error)
  30. throw error
  31. }
  32. }
  33. async getToken() {
  34. if (!this.msalApplication) {
  35. // Fetch the configuration values from the database using your ConfigurationService
  36. const configService = new ConfigurationService({
  37. Model: this.app.get('mssqlClient'),
  38. name: 'application_config' // Make sure this matches your FeathersJS database configuration
  39. })
  40. const configData = await configService.find()
  41. await this.initialize(configData)
  42. }
  43. // Pokud nemáme žádný platný token nebo je blízko k expiraci, získejte nový token
  44. if (!this.accessToken) {
  45. try {
  46. const tokenResponse = await this.msalApplication.acquireTokenByClientCredential({
  47. scopes: ['https://graph.microsoft.com/.default']
  48. })
  49. this.accessToken = tokenResponse.accessToken
  50. return this.accessToken
  51. } catch (error) {
  52. console.error('Error acquiring token:', error)
  53. this.accessToken = null
  54. throw error
  55. }
  56. }
  57. return this.accessToken
  58. }
  59. }

它像预期的那样工作,但我需要在令牌到期前5分钟刷新它。我什么都试过了,但都不管用。当我在间隔中刷新它时,我总是得到旧的令牌。请问各位有没有解决这个问题的方法?

gopyfrb3

gopyfrb31#

scopes: ['https://graph.microsoft.com/.default']用于客户端凭证,客户端凭证流生成的token是不能刷新的,当我们想要刷新访问令牌时,需要一个刷新令牌和一个访问令牌,只有auth代码流在生成访问令牌时才能提供刷新令牌。查看auth code flowclient credential flow的文档。
如您所见,当您在作用域中添加offline_access以生成访问令牌时,可能会返回刷新令牌。但是凭证流的作用域只能是xxx/.default,我们不能将offline_access添加到客户端凭证流的作用域中。
注意:仅在请求offline_access作用域时提供。

相关问题