[指南] Auth0 SPA Vue2 串接精簡指南

Auth0 若要與 SPA 環境的 Vue2 版本串接,由於官方並沒有出 Vue2 版本專屬的 SDK。這邊筆記下用 @auth0/auth0-spa-js 套件的精簡流程。

auth0 vue


內容

1. 引入 Auth0Client 方法,僅需要 new 出一個 Auth0Client 即可。
2. 在 router.beforeEach 中進行管理。如果沒有 token 的話,就進行 coreAuth0Client.loginWithRedirect
3. 當取得 token 回來後,因為網址列會有 code 參數,可以用這個來進行判斷
4. 透過 coreAuth0Client.getTokenSilently() 取得 token; 透過 coreAuth0Client.handleRedirectCallback() 後就可再用coreAuth0Client.getUser() 取得 User

5. 為了避免網址列中殘存的 ? 而導致後續 hash mode 出錯,會利用window.location.replace(${window.location.origin}${window.location.pathname}) 來重新載入
6. 為了避免 refresh 之後,頭一次登入時取得的 user 資料遺失。在登入時需要用 localStorage 來進行暫存,登出時要記得清除。

程式碼


參考資料

1. The Complete Guide to Vue.js User Authentication with Auth0
2. Auth0 Single Page App SDK

按讚加入粉絲團

延伸閱讀