nuxt-community / auth-module

Zero-boilerplate authentication support for Nuxt 2
https://auth.nuxtjs.org
MIT License
1.93k stars 924 forks source link

cookie headers are not sent in ssr request after new update to the axios module v5.12.2 #809

Closed msonowal closed 3 years ago

msonowal commented 4 years ago

I am using laravel sanctum as a authentication strategy, which is running fine with both ssr and client it was sending the correct headers/payloads so thus getting 200 response in user info api call. Either in full page reload(ssr) or client side.

But today I have updated the axios modue to the latest which is v5.12.2 and was previously v5.12.1.

So after update If I do full page reload then when it calls the user info api to get the details of the user and determines if logged in or not based on the status code 200 or 402. In that it does not pass the necessary cookies i.e. session cookies that was set already. So the api returns 401 resulting as unauthenticated. And then it again makes the call from the client side and now rechieves 200 as status as it is passing the correct headers. I have tried putting the previous version and it works.

Kindly let me know if you need anything.

correct headers when it is sent

{
"host": "auth-test.test",
"authorization": "********",
"content-type": "application/json",
"x-requested-with": "XMLHttpRequest",
"cookie": "auth.redirect=%2Faccount%2Fprofile; auth.strategy=laravelSanctum; v1={%22cart%22:{%22id%22:null}%2C%22currency%22:{%22code%22:%22INR%22}}; _ga=GA1.1.990862393.1598456492; _gid=GA1.1.1256557785.1598456492; auth._token_expiration.laravelSanctum=false; auth._token.laravelSanctum=200; XSRF-TOKEN=eyJpdiI6InE5bzdYRVBtd3hZSEN0dVFvM3YwOVE9PSIsInZhbHVlIjoiVjU0RnBWYlYvRDl0eWpnZ2VuNlNVQk1aeVZLd0JWUTcyZllXK2JNV0d1RDdpRVlTdW90WXJndm9kaTE4aEFWOU5Kd1N6NEp6SDZkdytDeENJOEFzcFY0eVBoWUEvNnd1eXBvMTdjdVluelRvZjBWanhtK3YyQjBjSFJIUFdrUjgiLCJtYWMiOiIxYjhmNTUxMjg5MGY2YzFhOTYwYTYyYTdkYTdlYmNmNzc0ZDU0NTE3N2UzMjA2MDVjMDVkMTE3OGM0ZjNmYjllIn0%3D; hashtagme_session=eyJpdiI6IlFxREZQZ2JjN3JCOXluYzQxUktHS2c9PSIsInZhbHVlIjoiYWo3RVdZT1FIUjFJakozU0t2aEhqbTFicVUzYXhqc3VHUmFGZjlEUnFNMXF1RFNQa2d2SUY4c0graHZ1d29hM0trMmk3aDVERjgwZTh0czJjak5OeTJKRmtKc1FSa0lyY2MwNmFKWGRNejlwSi9OQkFBemp6UkZGcktmeng4VW8iLCJtYWMiOiI4MGJjYzZlYmUxNjRlYmYwNWZlYWU0YzU1MzI4ZDJkYTgwNTBhYzc1ZmQzNDIxNTA5MTY3NTA1ZDNiZWUzOWQwIn0%3D",
"accept-language": "en-GB,en;q=0.9,en-US;q=0.8",
"accept-encoding": "gzip, deflate",
"referer": "localhost:3000",
"sec-fetch-dest": "document",
"sec-fetch-user": "?1",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "same-origin",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36 Edg/81.0.416.68",
"upgrade-insecure-requests": "1",
"dnt": "1",
"cache-control": "no-cache",
"pragma": "no-cache",
"connection": "keep-alive",
"accept": "application/json",
"content-length": ""
}

missing headers when buggy

{
  "connection": "close",
  "host": "auth-test.test",
  "user-agent": "axios/0.20.0",
  "authorization": "********",
  "accept": "application/json",
  "content-type": "application/json",
  "x-requested-with": "XMLHttpRequest",
  "content-length": ""
}

nuxt.config.js

export default {
  /*
   ** Nuxt rendering mode
   ** See https://nuxtjs.org/api/configuration-mode
   */
  mode: 'universal',
  /*
   ** Headers of the page
   ** See https://nuxtjs.org/api/configuration-head
   */
  head: {
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      {
        hid: 'description',
        name: 'description',
        content: process.env.npm_package_description || '',
      },
    ],
    link: [
      { rel: 'icon', type: 'image/XIcon', href: '/favicon.ico' },
      {
        rel: 'stylesheet',
        href:
          'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css',
      },
    ],
  },
  /*
   ** Global CSS
   */
  css: [
    // SASS file in the project
    '~/assets/custom.sass',
  ],
  /*
   ** Plugins to load before mounting the App
   ** https://nuxtjs.org/guide/plugins
   */
  plugins: [
    { src: '~/plugins/swiper.js', mode: 'client' }, // only on client side
    { src: '~/plugins/persistState' },
    { src: '~/plugins/directives' },
    // mode: 'client'
  ],
  /*
   ** Nuxt.js dev-modules
   */
  buildModules: [
    // Doc: https://github.com/nuxt-community/eslint-module
    '@nuxtjs/eslint-module',
    // Doc: https://github.com/nuxt-community/nuxt-tailwindcss
    '@nuxtjs/tailwindcss',
    // https://github.com/nuxt/components
    '@nuxt/components',

    '@nuxtjs/google-analytics',
    '@forked-prs/nuxt-facebook-pixel-module',
  ],
  /*
   ** Nuxt.js modules
   */
  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    '@nuxtjs/auth-next',
    '@nuxtjs/pwa',
    // Doc: https://github.com/nuxt/content
    '@nuxt/content',
    '@nuxtjs/toast',
  ],

  toast: {
    duration: 6000,
  },
  /*
   ** Axios module configuration
   ** See https://axios.nuxtjs.org/options
   */
  axios: {
    proxy: true, // Can be also an object with default options
  },

  proxy: {
    '/api/': process.env.API_URL || 'http://app',
    '/auth': {
      target: process.env.API_URL || 'http://app',
      pathRewrite: { '^/auth': '/' },
    },
  },

  auth: {
    redirect: {
      // login: '/login',
      logout: '/',
      // callback: '/login',
      home: '/account/profile',
    },
    watchLoggedIn: false,
    strategies: {
      laravelSanctum: {
        provider: 'laravel/sanctum',
        url: '/auth',
        user: {
          property: 'user',
          // autoFetch: true,
        },
        endpoints: {
          csrf: { url: '/user/csrf-cookie', method: 'get' },
          login: { url: '/user/login', method: 'post' },
          user: { url: '/api/user?from=sanc' },
          logout: { url: '/user/logout', method: 'post' },
        },
      },
      /*
      local: {
        // scheme: 'local',
        token: {
          property: 'token',
          // required: true,
          type: 'Bearer',
          maxAge: 60 * 60 * 24 * 30,
          // as of now setting for 30 days
          // in seconds default 1800 seconds
        },
        user: {
          property: 'user',
          autoFetch: false,
        },
        endpoints: {
          login: false,
          logout: false,
          user: { url: '/api/user?from=loc', method: 'get' },
        },
      },
      */
    },
  },

  googleAnalytics: {
    id: 'UA-XXXX-X', // Used as fallback if no runtime config is provided
    ecommerce: {
      enabled: true,
      enhanced: true,
    },
  },

  facebook: {
    /* module options */
    track: 'PageView',
    pixelId: 'xxx',
    disabled: false,
    debug: false,
    // wont run on development mode
  },

  publicRuntimeConfig: {
    brand: 'test',

    googleAnalytics: {
      id: process.env.GOOGLE_ANALYTICS_ID,
      debug: {
        enabled: process.env.GOOGLE_ANALYTICS_DEBUG || false,
        sendHitTask: process.env.GOOGLE_ANALYTICS_DEBUG || false,
      },
    },
    facebook: {
      /* module options */
      pixelId: process.env.FB_PIXEL_ID || 'some-staging-key',
      disabled: false,
      debug: false,
    },
  },

  components: true,
  /*
   ** Content module configuration
   ** See https://content.nuxtjs.org/configuration
   */
  content: {},
  /*
   ** Build configuration
   ** See https://nuxtjs.org/api/configuration-build/
   */
  build: {},
}

Reproduce the issue by following the readme

https://github.com/msonowal/nuxt-auth-411

paulvonber commented 4 years ago

Same here after update headers are gone. Only quick solution I found just add axios "0.19.2" to your packages.

devenjahnke commented 4 years ago

You are a life saver! I just started my first Nuxt project a few days ago (unknowingly after @nuxtjs/auth updated to 5.12.2) and have spent the last 48 hours banging my head against a wall trying to figure out why the authentication middleware would not work. Thanks to you, I have rolled back to 5.12.1 and sure enough everything works as expected.

I'm clearly no expert, but here is the GitHub diff between 5.12.2 and 5.12.1 for anyone who wants to take a look at what might have caused the issue: https://github.com/nuxt-community/axios-module/compare/v5.12.1...v5.12.2

dekadentno commented 4 years ago

Can confirm, changed my package.json from

...
    "@nuxtjs/axios": "^5.12.1",
...

to

...
    "@nuxtjs/axios": "5.12.1",
...

and it works (notice caret has been removed) . Thanks.

Smidds commented 4 years ago

I also can confirm that the issue appears to be explicitly with axios. For my project all I did was add a resolution to axios@0.19.2:

// package.json
"resolutions": {
   "axios": "0.19.2"
}
iamroi commented 4 years ago

@toiiia Я чувствую тебя, дружище. Бля потрачено впустую 4 часа

HassanZahirnia commented 4 years ago

Thanks god I found this thread while doing random searches in the repository. I was pretty much banging my wall against the wall for the past day trying to figure out why Nuxt is failing to authenticate the logged-in user in SSR mode. It just kept redirecting all my routes to /login for no reason. Downgrading the @nuxtjs/axios version from 5.12.2 to 5.12.1 did the trick. @Smidds I never heard of the resolutions property in package.json. Do you mind explaining what it does and how it is different from changing @nuxtjs/axios version explicitly ?

Smidds commented 4 years ago

Hey @xperator - The resolutions property is specific to yarn, I suppose I should've clarified. Here's the doc page for it!

lavrentiev commented 4 years ago

@iamroi @toiiia мужики сутки ломал голову, сочувствую вам )

fabiom91 commented 3 years ago

still not working in the middleware

kevcodez commented 3 years ago

Still broken, just wasted 3 hours. Downgrading to nuxtjs/axios 5.12.1 fixed it.

Joseluk commented 3 years ago

You have definitely saved me from hours of suffering

I just changed

"@ nuxtjs / axios": "^5.12.2",

to

"@ nuxtjs / axios": "5.12.1",

msonowal commented 3 years ago

@pi0 ping as it is broken in latest versions

bmulholland commented 3 years ago

Is this with v4 or v5 via @nuxtjs/auth-next? Can someone post a working codesandbox repro?

bmulholland commented 3 years ago

It's possible that this PR fixes the issue, but we need confirmation and ideally a way to repro. Can anyone try it out and verify? https://github.com/nuxt-community/axios-module/issues/411

mohsenMJ commented 3 years ago

I did downgraded axios from 5.12.3 to 5.12.1 but still my problem exists when login and hard refresh my nuxtjs application redirect to login page ,

any solution!!!

Milchreis commented 3 years ago

I run into the same issue. Downgrade to axios 5.12.1 didn't change anything. My current workaround is to disable the cookie feature which works to me, but this has some other downsides.

nuxt.config.js

    auth: {
        // ...
        cookie: false,
        strategies: {
            local: {
                // ...
            }
        }
    },
mohsenMJ commented 3 years ago

I tried all of your solution and Still have the same issue, Tired of debugging and having no results , with new release of @nuxtjs/auth-next 5.0.0-1607693598.34d83ea they fxed @nuxtjs/axios 5.12.1 version but I it didn't help me at all and every time I refresh the page it goes directly to login page causing me to have a really hard time developing my application

Please help if you have a solution !!

vakrolme commented 3 years ago

My suggestion to @mohsenMJ and @Milchreis is to search the yarn.lock for all mentions of axios to make sure that all of the sub-dependencies are resolved into the version you want. As someone mentioned above, you can explicitly force sub-dependencies to resolve into a specific version like so:

  "dependencies": {
    "@nuxtjs/axios": "5.12.1",
  },
  "resolutions": {
    "**/@nuxtjs/axios": "5.12.1"
  },

It works for me, and I didn't have to change anything in the nuxt.config.js.

P.S. Note no ^ character before the version number. I forgot to remove it at first and couldn't figure out why I still got 5.12.3 🤦

JoaoPedroAS51 commented 3 years ago

The issue was fixed in v5.12.4 of @nuxtjs/axios. Please, update to latest version of @nuxtjs/auth-next

mohsenMJ commented 3 years ago

Installed a new nuxt Projext along with the latest version of @nuxtjs/auth-next v5., @nuxtjs/axios but still have the same issue, when I refresh on a protected route it returns to login page

package.json

"@nuxtjs/auth-next": "5.0.0-1607967355.df8f01e",
"@nuxtjs/axios": "^5.12.4",

nuxt.config.js

axios: {
    baseURL : 'http://localhost:8000',
    credentials : true,
  },
auth:{
    strategies: {
      'laravelSanctum': {
        provider: 'laravel/sanctum',
        url: '/',
        endpoints: {
          csrf  : {url: '/sanctum/csrf-cookie', method: 'get'},
          login : {url: '/admin/login',  method: 'post', propertyName: 'token' },
          logout: {url: '/admin/logout', method: 'post' /*, propertyName : 'token'*/ },
          user  : {url: '/api/v1/admin/user',   method: 'post', propertyName: false }
        },
      },

    }
  },

login.vue

this.$auth.loginWith('laravelSanctum', {
        data: {
          email: 'test@test.com',
          password: 'password',
        }
      }).then(res => {
        console.log(res);
        this.$router.push('/dashboard');
      })
bmulholland commented 3 years ago

Thanks for reporting @mohsenMJ. Can you post a repro?

On December 15, 2020 at 15:09:27, mohsenMJ (notifications@github.com) wrote:

Installed a new nuxt Projext along with the latest version of @nuxtjs/auth-next , @nuxtjs/axios but still have the same issue, when I refresh on a protected route it returns to login page

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/809#issuecomment-745308128, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAB4PIMG3WOAAPGM4C7LL63SU5UZPANCNFSM4QMANIZQ .

lofbacke commented 3 years ago

I am also experiencing the same login redirect issue on protected routes after updating both @nuxtjs/auth-next and @nuxtjs/axios.

package.json

"@nuxtjs/auth-next": "^5.0.0-1608461079.ae1e5db",
"@nuxtjs/axios": "^5.12.4"
yrestom commented 3 years ago

I have the same problem:

"@nuxtjs/auth-next": "^5.0.0-1608568767.2fe2217", 
"@nuxtjs/axios": "^5.12.5",
mohsenMJ commented 3 years ago

after a long time suffering from this problem , I found out that if you don't set the right setting on your sever it won't work, I am using Laravel/Sanctum and here is what I did ( I was using my custom login method):

         $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);
        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) {
            $request->session()->regenerate(); // this line is important
            return new Response('', 204);  // make sure you return 204
        }
        throw ValidationException::withMessages([
            'email' => [__('auth.failed')],
        ]);

I successfully logged in and kept me on the page when refreshing any protected page.

Hope it could help you guys!

bmulholland commented 3 years ago

@mohsenMJ Do you know which "right setting on your server" made the difference?

lofbacke commented 3 years ago

Even if @mohsenMJ's solution is viable, I am not using Laravel/Sanctum, so it will not help everyone who is experiencing this issue. I am using a .NET Core API to provide the JWT and refresh tokens upon login as well as the user object. Please let me know what other information, if any, is needed to help trouble-shoot this problem.

Thanks in advance!

SvetoslavStefanov commented 3 years ago

after a long time suffering from this problem , I found out that if you don't set the right setting on your sever it won't work, I am using Laravel/Sanctum and here is what I did ( I was using my custom login method):

         $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);
        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) {
            $request->session()->regenerate(); // this line is important
            return new Response('', 204);  // make sure you return 204
        }
        throw ValidationException::withMessages([
            'email' => [__('auth.failed')],
        ]);

I successfully logged in and kept me on the page when refreshing any protected page.

Hope it could help you guys!

I had the same issue using Nuxt + Laravel Sanctum - My problem was the SESSION_DOMAIN variable that comes from the .env file. I'm using it on a subdomain and the SESSION_DOMAIN was pointing to ".domain.com". When I change it to "sub.domain.com" it worked great.

hutch78 commented 3 years ago

I am having the same issue as @nuxtjs/auth-next v5.0.0-1624817847.21691f1 requires nuxtjs/axios ^5.13.0.. my setup is as follows:

Laravel 8 w/ Sanctum api: http://localhost:8000 client: http://localhost:3000

nuxt/axios -> 5.13.6 I have "@nuxtjs/axios": "5.12.1", in my package.json

Debugging the outgoing requests sent from nuxt when I refresh the page, it is sending a request to /api/user, but not /sanctum/csrf-cookie beforehand. I think this has something to do with it.

Anyone have any ideas? I am about to try editing nuxt/axios versions in package-lock but that feels wrong.

johnymanuelli commented 2 years ago

Same problem persist until today...

SwapnilSoni1999 commented 2 years ago

Facing same

sauravkumal commented 2 years ago

Same issue

bmulholland commented 2 years ago

Fastest way to get this fixed is to dig into the code and figure out what's happening and why.

lukasjuhas commented 2 years ago

I've fixed this by tidying up my async functions. The problem in my case was that after I made a request to a server, after that setting tting a bunch of stuff, which were async functions, so I had to make sure that the request function was async and that everything had await so that one step could finish before next one would start and for example set the user using auth module.

To note here, I also have a custom graphql auth schema, and after I tidied up all the methods to use async await where relevant, the errors have disasapeared.

I recommend looking into your middleware if you have any, and make sure the code is fine.