为什么我使用vuejs 3从Azure B2C获得空访问令牌

发布于 2025-01-20 22:20:30 字数 2732 浏览 0 评论 0原文

我正在使用msal.js(@azure/msal-browser“:”^2.23.0“)的最后一个版本,我可以成功地authnenticat,但是访问令牌为空,我不知道为什么。 我希望在这里发布代码,希望有人可以帮助吗?

export const useAuthUserStore = defineStore("auth_user", {
state: () => ({
msalConfig: {
  auth: {
    clientId: "xxx",
    authority: xxxxxxxx,
    knownAuthorities: [xxxxxxx.onmicrosoft.com],
    redirectUri: http://localhost:8080/
  },
  cache: {
    cacheLocation: 'localStorage',
  },
},
accessToken: "",

isAuthenticated:false,
}),

获取访问方法:

   async getAccessToken(){
  let request = {
    scopes: [https://graph.microsoft.com/offline_access,https://graph.microsoft.com/openid],
   // scopes: ['openid',  'offline_access' ],
   extraScopesToConsent:['<tenant>.onmicrosoft.com/api/read']
  };
  const msalInstance = new PublicClientApplication(
   this.authStore.$state.msalConfig
  );
  try {
    let tokenResponse = await msalInstance.acquireTokenSilent({
      account: this.account ,
        scopes: [https://graph.microsoft.com/offline_access,https://graph.microsoft.com/openid]

    });
     console.log('tokenResponse :',tokenResponse)
    return tokenResponse
  } catch (error) {
      console.error( 'Silent token acquisition failed. Using interactive mode',error );
      let tokenResponse = await msalInstance.acquireTokenPopup(request);
      console.log(`Access token acquired via interactive auth ${tokenResponse.accessToken}`)
  }

},

handleResponse(response) {

  console.log('handleResponse.......')

  let accountId = "";

  const loginRequest = {

   scopes: [https://graph.microsoft.com/offline_access,https://graph.microsoft.com/openid],
     }

  console.log('handleResponse.......',response)

    if (response !== null) {
        accountId = response.account.homeAccountId;
        console.log(accountId)
        // Display signed-in user content, call API, etc.

    } else {

        // In case multiple accounts exist, you can select

        const currentAccounts = this.$msalInstance.getAllAccounts();
        if (currentAccounts.length === 0) {
            // no accounts signed-in, attempt to sign a user in
            this.$msalInstance.loginRedirect(loginRequest);
        } else if (currentAccounts.length > 1) {
         // console.log('handleResponse.......96')

            // Add choose account code here

        } else if (currentAccounts.length === 1) {

         // console.log('handleResponse.......23')

            accountId = currentAccounts[0].homeAccountId;

           // console.log('handleResponse 111.......',accountId)

        }

    }

}

结果: 在此处输入图像描述

您能帮忙吗?我必须添加任何丢失的代码吗?

I'm using the last version of MSAL.js (@azure/msal-browser": "^2.23.0"),I can successfully authnenticat but the access token is empty I dont know why.
I'm posting the code here I hope anyone could help please ?

export const useAuthUserStore = defineStore("auth_user", {
state: () => ({
msalConfig: {
  auth: {
    clientId: "xxx",
    authority: xxxxxxxx,
    knownAuthorities: [xxxxxxx.onmicrosoft.com],
    redirectUri: http://localhost:8080/
  },
  cache: {
    cacheLocation: 'localStorage',
  },
},
accessToken: "",

isAuthenticated:false,
}),

get the accesstoken method :

   async getAccessToken(){
  let request = {
    scopes: [https://graph.microsoft.com/offline_access,https://graph.microsoft.com/openid],
   // scopes: ['openid',  'offline_access' ],
   extraScopesToConsent:['<tenant>.onmicrosoft.com/api/read']
  };
  const msalInstance = new PublicClientApplication(
   this.authStore.$state.msalConfig
  );
  try {
    let tokenResponse = await msalInstance.acquireTokenSilent({
      account: this.account ,
        scopes: [https://graph.microsoft.com/offline_access,https://graph.microsoft.com/openid]

    });
     console.log('tokenResponse :',tokenResponse)
    return tokenResponse
  } catch (error) {
      console.error( 'Silent token acquisition failed. Using interactive mode',error );
      let tokenResponse = await msalInstance.acquireTokenPopup(request);
      console.log(`Access token acquired via interactive auth ${tokenResponse.accessToken}`)
  }

},

handleResponse(response) {

  console.log('handleResponse.......')

  let accountId = "";

  const loginRequest = {

   scopes: [https://graph.microsoft.com/offline_access,https://graph.microsoft.com/openid],
     }

  console.log('handleResponse.......',response)

    if (response !== null) {
        accountId = response.account.homeAccountId;
        console.log(accountId)
        // Display signed-in user content, call API, etc.

    } else {

        // In case multiple accounts exist, you can select

        const currentAccounts = this.$msalInstance.getAllAccounts();
        if (currentAccounts.length === 0) {
            // no accounts signed-in, attempt to sign a user in
            this.$msalInstance.loginRedirect(loginRequest);
        } else if (currentAccounts.length > 1) {
         // console.log('handleResponse.......96')

            // Add choose account code here

        } else if (currentAccounts.length === 1) {

         // console.log('handleResponse.......23')

            accountId = currentAccounts[0].homeAccountId;

           // console.log('handleResponse 111.......',accountId)

        }

    }

}

the result :
enter image description here

could you help please ? is there any missing code that I have to add ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

疏忽 2025-01-27 22:20:30

使用MSAL提供的AcquireToken方法,您可以接收应用程序需要调用的API的访问令牌。

源代码: - github样品

有关更多信息,请参阅以下链接: -

Using the acquireToken methods supplied by MSAL, you can receive access tokens for the APIs your app needs to call.

Source Code:- GitHub Sample

For more information please refer the below links:-

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文