nuxt-community / auth-module

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

Module not sending cookie in the fetchUser() request? #1259

Closed Giuliopime closed 1 year ago

Giuliopime commented 3 years ago

Version

module: 5.13.6 nuxt: 2.15.7

Nuxt configuration

mode:

Nuxt configuration

  axios: {},

  router: {
    middleware: ['auth']
  },

  auth: {
    strategies: {
      cookie: {
        scheme: '~/schemes/customScheme',
        cookie: {
          name: 'session_id',
        },
        token: {
          required: false,
          type: false
        },
        user: {
          property: false,
          autoFetch: true
        },
        endpoints: {
          login: {
            url: `${process.env.API_BASE_URL}/login`,
            method: 'post'
          },
          logout: {
            url: `${process.env.API_BASE_URL}/logout`,
            method: 'post'
          },
          user: {
            url: `${process.env.API_BASE_URL}/user`,
            method: 'get'
          }
        }
      },
    }
  }

~/schemes/customScheme.js

export default class CustomScheme extends LocalScheme {
  // Override `fetchUser` method of `local` scheme
  async fetchUser (endpoint) {
    // Try to fetch user and then set
    return this.$auth.requestWith(
      this.name,
      endpoint,
      this.options.endpoints.user
    ).then((response) => {
      this.$auth.setUser(response.data)

      return response
    }).catch((error) => {
      this.$auth.callOnError(error, { method: 'fetchUser' })
    })
  }
}

I use Ktor for my backend and when I login via the /login route I receive the following response so the cookie gets set correctly in the client browser. Screenshot 2021-08-12 at 17 55 39

The issue is that when I then try to fetch the user via the /user route the cookie doesn't get sent in the request and so I get a 401 back as the server doesn't get any session cookie so it threats me as unauthorized.
Screenshot 2021-08-12 at 18 03 06

Also I'm using the customScheme.js scheme because the normal fetchUser() method of the default local scheme just fails silently.

Questions

Checklist

Giuliopime commented 3 years ago

For all those who have the same issue, just create a plugin for axios and put

export default function ({ $axios }, inject) {
  $axios.defaults.withCredentials = true
}

This allows the cookie to be sent and it's missing in the auth module

bmulholland commented 2 years ago

Another workaround is to set axios to use credentials in nuxt.config.js:

axios: {
  credentials: true
}