Vue.jsQuasarSPA在每次重新加载页面时重新启动身份验证代码流

问题描述

我有一个使用Quasar框架(基于Vue.js)构建的SPA。 SPA在Auth0中注册,并使用auth0-spa-js库通过Auth Code Flow处理登录。在登录有效并获得令牌的同时,当我重新加载页面时,将再次启动Auth Code Flow,并将用户重定向到/ authorize端点以获取代码,然后再次将其交换为新令牌。>

在我看来,这似乎不是正确的行为。我本来希望Auth0库在浏览器中缓存/存储令牌,并在页面重载时检查是否已经有一个有效的令牌,而不是每次都重新启动Auth Code Flow。

或者实际上应该考虑的是SPA,并且浏览器中的令牌存储不是很好。

引导文件中的代码

import createAuth0Client from '@auth0/auth0-spa-js';
import axios from 'axios'

export default async ({ app,router,Vue }) => {
    let auth0 = await createAuth0Client({
        domain: '{domain}.auth0.com',client_id: '{client_id}',audience: '{audience}'
    });

    const isAuthenticated = await auth0.isAuthenticated();
    if (isAuthenticated) {
        // show the gated content
        await afterLogin(auth0,Vue)
        return;
    }

    const query = window.location.search;
    if (query.includes("code=") && query.includes("state=")) {

        // Process the login state
        await auth0.handleRedirectCallback()
        
        await afterLogin(auth0,Vue)

        // Use replaceState to redirect the user away and remove the querystring parameters
        window.history.replaceState({},document.title,"/");
        
        return
    }

    await auth0.loginWithRedirect({
        redirect_uri: window.location.origin
    });
}

async function afterLogin(auth0,Vue) {
    let user = await auth0.getUser()
    Vue.prototype.$user = user
    Vue.prototype.$auth = auth0

    // let claims = await auth0.getIdTokenClaims()
    // console.log(claims)
    // setAuthHeader(claims.__raw)
    let token = await auth0.getTokenSilently()
    setAuthHeader(token)
}

function setAuthHeader(token) {
    axios.defaults.headers.common['Authorization'] = 'Bearer ' + token
}

我想念什么?

解决方法

刷新时,应检查用户是否存在。

 const user = await auth0.getUser();

您可以在src / boot文件夹中创建一个autoCheckUser函数,该函数可以在每次创建应用程序时检查用户是否存在...

,

Auth0的反馈是这是预期的行为。

“如果令牌存储在内存中,则刷新页面时它将被擦除。通过cookie会话静默请求一个新令牌。”

Here是原始答案的链接