nuxt-alt / auth

An alternative module to @nuxtjs/auth
https://nuxt-alt-auth.vercel.app/
MIT License
96 stars 20 forks source link

When you press F5, the login page appears, and then the protected page (middleware auth) #55

Closed ftrsoft closed 1 year ago

ftrsoft commented 1 year ago

Environment


Nuxt Config

auth: { strategies: { local: { scheme: 'refresh', localStorage: { prefix: 'auth.' }, token: { prefix: 'access_token.', property: 'results.access', maxAge: 60 5, global: true, }, refreshToken: { prefix: 'refresh_token.', property: 'results.refresh', data: 'refresh', maxAge: 60 60 24 15 }, user: { property: 'results.user', autoFetch: true }, endpoints: { login: {url: '/api/token/', method: 'post'}, refresh: {url: '/api/token/refresh/', method: 'post'}, user: {url: '/api/v1/user/', method: 'get'}, logout: {url: '/api/v1/user_logout/', method: 'post'} }, } }, routerStrategy: 'navigateTo', watchLoggedIn: true, globalMiddleware: true, pinia: { persist: true, }, redirectStrategy: 'query', redirect: { login: '/login', logout: '/', callback: '/', home: '/' } },

Reproduction

none links

Describe the bug

I have two pages: /login - Login page /order - page with middleware auth

When I go to the page "/order", I log in, everything is fine. But if you press F5 on the page "/order", then the page "/login" will load first, and then it will change to the correct one "/order"

I think that the middleware should read cookies and log in when the application initializes on the server side first time (SSR).

Additional context

To solve this problem, I used a server plugin that checks cookies and initializes auth if necessary: place it to /plugins/init.server.js file

import {defineNuxtPlugin, useRequestHeaders} from '#app';
import { useNuxtApp } from "#imports";

function cookieFromRequestHeaders (key) {
    const headers = useRequestHeaders(['cookie']);

    if ('cookie' in headers) {
        const cookie = headers.cookie.split(';').find(
            c => c.trim().startsWith(`${key}=`)
        );
        if (cookie) {
            return decodeURIComponent(cookie.split('=')[1]);
        }
    }
    return '';
}

export default defineNuxtPlugin(async (nuxtApp) => {

    const token = cookieFromRequestHeaders('auth.access_token.local');
    const refreshtoken = cookieFromRequestHeaders('auth.refresh_token.local');

    const ctx = useNuxtApp();
    const auth = ctx.$auth;

    if (token && token.length > 15 && refreshtoken && refreshtoken.length > 15) {
        await auth.setStrategy('local').then(()=>{
            auth.setUserToken(token, refreshtoken);
        });
    }
});

Perhaps something similar can be implemented here

Logs

No response

ftrsoft commented 1 year ago

In my implementation, the names of cookies and strategies are hard-coded. It's for refresh strategy

ftrsoft commented 1 year ago

I do not know, but after upgrade to nuxt 3.5.0 everything became fine. I tried to repeat it on the previous version, everything works too