Nuxt 3 Authorization

432 Views Asked by At

I am new to Nuxtjs, i come from a web application developed using Vuejs 3, using pure Client Side Rendering and i was testing Nuxt SSR functionality migrating my application. In my scenario, the web application exchanges data with a PHP server using a REST API.

I am having some problem understanding the authentication mechanism. I am using a Http Session based authentication, so when i login, the server creates a Session and tell the client to set a cookie. The browser does so and following requests to the Application Server are sent with Session Cookie.

Note that the URL of Application Server is on a different domain of the web application, so the cookie is secure and has the attribute "same domain = None". Just to give all the information.

The problem is that during SSR, my components try to fetch data from the application server without success because the server doesn't have the Session Cookie (all the handpoints of my application server require authentication). Running my Nuxt Application in CSR only (configuring nuxt.config.js file with "ssr:false") the application works fine. But enabling SSR break it

For example, i have a global middleware to protect the routes of my application

export default defineNuxtRouteMiddleware(async (to, from) => {


        if(to.path !== '/login') {

            const result = await useCheckAuth();
            if(result) return;
            else return navigateTo('/login')
            
        }

        else return;
    
    
  })

The Composable i use to check authentication is the following

export const  useCheckAuth = async () => {
    const config = useRuntimeConfig()

    const {data, error, status, pending} = await useFetch('/auth/check',
        
        {
            baseURL:config.public.apiBase,
            method: 'get',
            credentials: 'include',
        },
        
    )
    
    if(status.value === 'success') return true;
    else return false;
}

The "usecheckAuth" Composable always returns false when executed server side. In fact, if i authenticate correctly and enter in a protected page, if i reload the browser, the Route Middleware kicks me out because the authentication composable returns false

I have read in the documentation something about the "useRequestHeader" but couldn't figure out how to use it. Any idea how i can face this?

0

There are 0 best solutions below