【问题标题】:Vue + MSAL2.x + Azure B2C Profile EditingVue + MSAL2.x + Azure B2C 配置文件编辑
【发布时间】:2021-03-26 12:39:30
【问题描述】:

首先,我没有找到使用 MSAL 2.x 的 Vue 特定示例,我们希望使用 PKCE 流程。我在 AuthService handleResponse 之前运行路由器防护的方式存在问题,所以我一定是做错了什么。

在我的 ma​​in.js 中,我正在这样做...

// Use the Auth services to secure the site
import AuthService from '@/services/AuthServices';
Vue.prototype.$auth = new AuthService()

然后在我的 AuthConfig.js 我使用这个请求登录:

loginRequest : {
      scopes: [
         "openid", 
         "profile", 
         process.env.VUE_APP_B2C_APISCOPE_READ, 
         process.env.VUE_APP_B2C_APISCOPE_WRITE
      ]
   },

文档说它应该重定向到请求页面,但没有发生。如果用户转到受保护的主页,他们将被重定向到登录。他们登录后,所有内容都已正确存储,因此他们实际上已登录,但随后他们被发送回站点的根重定向 URL,而不是主页。

当用户想要登录时,我们只需将他们发送到受保护的主页,并且在路由器保护中调用了一个登录方法,如下所示:

router.beforeEach(async (to, from, next) => {
   const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
   const IsAuthenticated = await Vue.prototype.$auth.isAuthenticated()
   console.log(`Page changing from ${from.name} to ${to.name}, requiresAuth = ${requiresAuth}, IsAuthenticated = ${IsAuthenticated}`)
   if (requiresAuth && !IsAuthenticated) 
   {
     next(false)
     console.log('STARTING LOGIN')
     Vue.prototype.$auth.login()
     // Tried this
     // Vue.prototype.$auth.login(to.path)
   } else {
     next()
   }
 })

AuthServices.js 我有这个...

   // The user wants to log in
   async login(nextPg) {

      // Tell B2C what app they want access to and their invitation ID if they are new
      if (store.getters.userEmail != null) {
         aCfg.loginRequest.loginHint = store.getters.userEmail
      }

      aCfg.loginRequest.state = "APP=" + store.getters.appCode
      if (store.getters.appointmentLink != null && store.getters.appointmentLink != '') {
         aCfg.loginRequest.state += ",ID=" + store.getters.appointmentLink
      }

      // Tried this
      // if (nextPg && nextPg != '') {
      //    aCfg.loginRequest.redirectUrl = process.env.VUE_APP_B2C_REDIRECT_URL + nextPg
      // }

      return await this.msalInst.loginRedirect(aCfg.loginRequest)
   }

我尝试在登录方法中添加一个 nextPg 参数并向登录请求添加一个 redirectUrl 属性,但这给了我一个错误,说它不是配置的重定向 URL 之一。

此外,我正在尝试在使用上述技术时让用户体验更好。当您查看 MSAL2.x SPA 示例时,我发现当从配置文件编辑返回时,用户已注销并且需要再次登录。对我来说,这听起来像是糟糕的用户体验。示例:https://github.com/Azure-Samples/ms-identity-b2c-javascript-spa/blob/main/App/authRedirect.js

我是否需要创建自己的个人资料编辑页面并使用 MSGraph 保存数据来防止这种情况发生?对不起菜鸟问题。想法?

更新 - 我看起来很俗气的解决方法是将这两种方法添加到我的 AuthService.js:

   storeCurrentRoute(nextPath) {
      if (!nextPath) {
         localStorage[STOR_NEXT_PAGE] = router.history.current.path
      } else {
         localStorage[STOR_NEXT_PAGE] = nextPath
      }
      console.log('Storing Route:', localStorage[STOR_NEXT_PAGE])
   }

   reEstablishRoute() {
      let pth = localStorage[STOR_NEXT_PAGE]
      if (!!pth && router.history.current.path != pth) {
         localStorage[STOR_NEXT_PAGE] = ''
         console.log(`Current path is ${router.history.current.path} and reEstablishing route to ${pth}`)
         router.push({ path: pth })
      }
   }

我首先在登录方法中调用storeCurrentRoute(),然后在handleResponse() 中调用reEstablishRoute(),当它没有从profileEdit 或密码更改返回时。似乎没有这个我应该能够使事情正常进行。

第二次更新 - 从 B2C 的 ProfileEdit 用户流返回时,MSAL 组件未正确注销我。这是我的 AuthService 中 handlePolicyChange() 方法中的代码:

} else if (response.idTokenClaims[clmPolicy] === aCfg.b2cPolicies.names.editProfile) {
         Vue.nextTick(() => {
            console.log('BACK FROM Profile Change')
            Vue.prototype.$swal(
               "Success!",
               "Your profile has been updated.<br />Please log in again.",
               "success"
            ).then(async () => {
               this.logout()
            })
          })

      } 
:
   // The user wants to log out (all accounts)
   async logout() {
      // Removes all sessions, need to call AAD endpoint to do full logout
      store.commit('updateUserClaims', null)
      store.commit('updateUserEmail', null)

      let accts = await this.msalInst.getAllAccounts()
      for(let i=0; i<accts.length; i++) {
         const logoutRequest = {
            account: accts[i],
            postLogoutRedirectUri: process.env.VUE_APP_B2C_REDIRECT_URL
         };
         await this.msalInst.logout(logoutRequest);
      }
      return
   }

在调用 logout() 之前它工作正常,但我查看了我的站点存储(在 Chrome 的调试窗口 > 应用程序中),看起来 MSAL 没有像在我的正常情况下那样清除它的条目注销(总是成功)。想法?

【问题讨论】:

    标签: vue.js azure-ad-b2c msal


    【解决方案1】:

    作为 MSAL 身份验证请求的一部分,发送 state 参数。 Base64 编码用户在此参数中停止的位置。 MSAL 公开了extraQueryParameters,您可以在其中放入一个字典对象并发送身份验证请求,将您的state 键值对放入extraQueryParameters

    state 参数将在回调响应中返回,使用它将用户发送到您需要的地方。

    【讨论】:

    • 感谢您的回复。所以只需使用状态而不是本地存储......好吧。编辑个人资料后我还需要注销吗?因为 MSAL 存储了错误的信息,如果我不这样做,后续的 API 调用就会失败,对吗?
    • 确认使用 state 而不是 localStorage 效果更好。谢谢,贾斯
    • 从 ProfileEdit 返回仍然失败(请参阅上面的更新 #2)。谢谢
    • 实际上,通过在 logoutRequest 数据中不包含任何帐户,我能够在配置文件编辑后进行注销。
    猜你喜欢
    • 2017-01-01
    • 2018-07-04
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多