manchenkoff / nuxt-auth-sanctum

Nuxt module for Laravel Sanctum authentication
https://manchenkoff.gitbook.io/nuxt-auth-sanctum/
MIT License
150 stars 18 forks source link

[QUESTION] After logout If I don't refresh the login page I cannot login #145

Closed ezekel closed 3 weeks ago

ezekel commented 4 weeks ago

Hi @manchenkoff

Can I ask about this strange behavior, After I logout I am redirected to log in, then if type again my credentials and then submit I cannot log in I'm not redirected to the dashboard, but If I refresh the login page after I logout then input my credentials then submit I was successfully logged in and redirected to dashboard.

Http/Controllers/Auth/AuthenticatedSessionController.php

 public function store(LoginRequest $request): JsonResponse|RedirectResponse
    {
        $request->authenticate();

        $request->session()->regenerate();

        if ($request->expectsJson()) {
            // Return a JSON response for frontend requests
            return response()->json(['message' => 'Login successful']);
        }

        // Redirect for non-JSON requests
        return redirect()->intended(route('dashboard', absolute: false));
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): JsonResponse|RedirectResponse
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();
        if ($request->expectsJson()) {
            return response()->json(['message' => 'Logged out successfully']);
        }

        return redirect('/');
    }

api.php

    <?php

    use App\Http\Controllers\TokenAuthenticationController;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Route;

    Route::get('/user', function (Request $request) {
        return $request->user();
    })->middleware('auth:sanctum');

Thank you in advance.

ezekel commented 3 weeks ago

I think it works I replace this

    redirect: {
            onLogin: '/dashboard',
            onLogout: '/login',
        },
    to this
     redirect: {
            onGuestOnly: '/dashboard',
            onLogout: '/login',
        },

here is my dahboard.vue

         <script setup lang="ts">
      import { Button } from '@/components/ui/button'

      definePageMeta({
        middleware: ['sanctum:auth','sanctum-verified'],
      })

       <template>
            <p>Dashboard</p>
       </template>   

can you enlighten my mind please, why it works if I use onGuestOnly: '/dashboard'

Thank you in advance

manchenkoff commented 3 weeks ago

After I logout I am redirected to log in, then if type again my credentials and then submit I cannot log in I'm not redirected to the dashboard, but If I refresh the login page after I logout then input my credentials then submit I was successfully logged in and redirected to dashboard.

I assume it might happen because logout resets the identity in the Nuxt state, but the CSRF value is still old and the regenerated token from the backend is not kept yet. Can you call refreshIdentity after logout action and see if the problem persists?

However, I cannot reproduce the same behavior by using breeze-nuxt + breeze-api templates, can you check if they work for you?

can you enlighten my mind please, why it works if I use onGuestOnly: '/dashboard'

This should not affect the behavior of the authentication, but you can check both CSR/SSR requests to see if there are any additional calls against your API which triggers cookie refresh.

ezekel commented 3 weeks ago

I tried but it didn't work, I am using Laravel 11 latest

        <script setup lang="ts">

        import {Button} from "~/components/ui/button";

        const {user,logout,isAuthenticated,refreshIdentity } = useSanctumAuth();

        const logOut = async () => {

          await logout();
          await refreshIdentity();
        }

        </script>
    nuxtconfig
    redirect: {
           // onGuestOnly: '/dashboard',
            onLogin:'/dashboard',
            onLogout: '/login',
        },
manchenkoff commented 3 weeks ago

@ezekel can you provide details about requests being made for the 2nd login attempt that fails? The most important part is the headers list and cookie that are set in your browser before the request is sent. Also, the whole config of sanctum from your nuxt.config.ts would be useful.

ezekel commented 3 weeks ago

Hi @manchenkoff

Please let me know if you need other details.

here is the request headers

POST /login HTTP/1.1
Host: larabells.local
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0
Accept: application/json
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://nuxtnew.larabells.local:4000/
content-type: application/json
x-xsrf-token: eyJpdiI6InM1K2E1bUc4TEJaaHZZRUx6YzJTK3c9PSIsInZhbHVlIjoibVRnbHV0ZDU5S2paT3N6QjVaYUlHanVMSFRoYlh0ak1GTkRBR3U4Ujc5V2ExMHpIRUVKS3VrNU56b25ObDZMVjJwMG80SXh1RUc5dnJNUUxYR1p2US9lTXM0d2s5RzdHYjRwbE5IWURVYnRvcDMvdTFUdzZXdjNBSDh4bUNlUnQiLCJtYWMiOiIyODIzM2U1MjNiNDE4MWQzNjZkMWY5YWUzMDdmMzRlNDdkMDgyMmU3NWJjYjFmMWU0N2EzMDNkZTNjOTBhY2RiIiwidGFnIjoiIn0=
Content-Length: 66
Origin: http://nuxtnew.larabells.local:4000
Connection: keep-alive
Cookie: XSRF-TOKEN=eyJpdiI6InM1K2E1bUc4TEJaaHZZRUx6YzJTK3c9PSIsInZhbHVlIjoibVRnbHV0ZDU5S2paT3N6QjVaYUlHanVMSFRoYlh0ak1GTkRBR3U4Ujc5V2ExMHpIRUVKS3VrNU56b25ObDZMVjJwMG80SXh1RUc5dnJNUUxYR1p2US9lTXM0d2s5RzdHYjRwbE5IWURVYnRvcDMvdTFUdzZXdjNBSDh4bUNlUnQiLCJtYWMiOiIyODIzM2U1MjNiNDE4MWQzNjZkMWY5YWUzMDdmMzRlNDdkMDgyMmU3NWJjYjFmMWU0N2EzMDNkZTNjOTBhY2RiIiwidGFnIjoiIn0%3D; laravel_session=eyJpdiI6IjZ0b25KanBRczBJbStoeStqUW8welE9PSIsInZhbHVlIjoibHpiODNmaWN1QUdQSmxCc0ZGNUlXdUtCZDRLbHd2bzZPb255REsxd3I5VnVDOE1KREhaZ2UvRnY0SGhtY3JaRlc0aldrVW56M2g4V3VKMDE5NVpLVFQ1MUV0TnptRWN3OFVtU0trTktnMlFtTklFc2pTZVl6WXNselZPWTJMOVAiLCJtYWMiOiI1YTVlOTUwMDEwMDI2MWY5YTRiOGQ3N2NjMjgxYmRhZGZiM2UxNDE3ODFkMDE3ZGE2MTk5ZDBlNGFiYTJkZTYzIiwidGFnIjoiIn0%3D
Priority: u=4

here is the request cookies

laravel_session "eyJpdiI6IjZ0b25KanBRczBJbStoeStqUW8welE9PSIsInZhbHVlIjoibHpiODNmaWN1QUdQSmxCc0ZGNUlXdUtCZDRLbHd2bzZPb255REsxd3I5VnVDOE1KREhaZ2UvRnY0SGhtY3JaRlc0aldrVW56M2g4V3VKMDE5NVpLVFQ1MUV0TnptRWN3OFVtU0trTktnMlFtTklFc2pTZVl6WXNselZPWTJMOVAiLCJtYWMiOiI1YTVlOTUwMDEwMDI2MWY5YTRiOGQ3N2NjMjgxYmRhZGZiM2UxNDE3ODFkMDE3ZGE2MTk5ZDBlNGFiYTJkZTYzIiwidGFnIjoiIn0="
XSRF-TOKEN  "eyJpdiI6InM1K2E1bUc4TEJaaHZZRUx6YzJTK3c9PSIsInZhbHVlIjoibVRnbHV0ZDU5S2paT3N6QjVaYUlHanVMSFRoYlh0ak1GTkRBR3U4Ujc5V2ExMHpIRUVKS3VrNU56b25ObDZMVjJwMG80SXh1RUc5dnJNUUxYR1p2US9lTXM0d2s5RzdHYjRwbE5IWURVYnRvcDMvdTFUdzZXdjNBSDh4bUNlUnQiLCJtYWMiOiIyODIzM2U1MjNiNDE4MWQzNjZkMWY5YWUzMDdmMzRlNDdkMDgyMmU3NWJjYjFmMWU0N2EzMDNkZTNjOTBhY2RiIiwidGFnIjoiIn0="

This is my nuxtconfig

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({

    compatibilityDate: '2024-04-03',
    devtools: {enabled: false},
    ssr: true,
    devServer: {
        host: 'nuxtnew.larabells.local',
        port: 4000,

    },
    // vite: {
    //     server: {
    //         hmr: {
    //             protocol: 'wss',
    //             clientPort: 443,
    //         },
    //     },
    // },
    modules: [
        "@nuxtjs/tailwindcss",
        "shadcn-nuxt",
        '@nuxtjs/tailwindcss',
        '@nuxtjs/color-mode',
        "nuxt-auth-sanctum"
    ],
    colorMode: {
        classSuffix: ''
    },
    shadcn: {
        /**
         * Prefix for all the imported component
         */
        prefix: '',
        /**
         * Directory that the component lives in.
         * @default "./components/ui"
         */
        componentDir: './components/ui'
    },
    sanctum: {
        baseUrl: 'http://larabells.local', // Laravel API
        mode: 'cookie',
        endpoints: {
            user: '/api/user',
        },
        redirect: {
           // onGuestOnly: '/dashboard',
            onLogin:'/dashboard',
            onLogout: '/login',
        },
    },
})
manchenkoff commented 3 weeks ago

Hey @ezekel, unfortunately I couldn't reproduce it and these requests look fine. This setup requires proper debugging 😄 can you create a minimal repro (e.g. in public github repo) for both Nuxt and Laravel apps so I can test the behavior?

You can also try to use breeze-nuxt and breeze-api templates for that, but the issues didn't occur for me while using it.

ezekel commented 3 weeks ago

Hi thank you,

I checked the breeze-nuxt and It's just the same with my nuxt config, maybe it's because I am using frankenphp docker image and also my nuxt is also in docker. I run them with docker-compose.

I will just close this maybe I need to debug my setup.

Thank you.