nuxt-community / auth-module

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

middleware => auth: 'guest' not redirecting to home page. #798

Closed dgvai closed 3 years ago

dgvai commented 4 years ago

I am using route based middleware (not globally in nuxt.config.js),

In my pages/login.vue, I set:

export default {
    auth : 'guest'
}

Expecting that, after I logged in, if I manually load mysite.com/login (manually from browser), it should have redirected to'/'

But this is not working! Not redirecting!

azizk17 commented 4 years ago

hey, I think auth options don't work without the middleware, so you need to enable it either globally or per route.

export default {
    middleware: 'auth'
    auth : 'guest'
}
dsteinbach commented 4 years ago

@azizk17 that didn't fix it for me. I had to manually create middleware to handle this case manually.

dgvai commented 4 years ago

@dsteinbach same here, I also created a manual middleware to solve this issue.

jclaessens97 commented 4 years ago

@dsteinbach & @dgvai can you post the middleware you wrote to fix this? If I do a check client-side I can redirect manually, but in my middleware loggedIn is always false, so I can't use middleware to redirect. After the page is loaded client-side once the loggedIn is set succesfully...

dgvai commented 4 years ago

@jclaessens97 , sure, here is mine:

in middlewares/guest.js:

export default function (ctx) {
  if (ctx.app.$auth.$state.loggedIn) {
    return ctx.app.$auth.redirect('home')
  }
}
jclaessens97 commented 4 years ago

Hmm weird.. In my case $auth.$state.loggedIn is always false. I had the above middleware implemented myself, but I thought you guys were doing something extra 😅 . Not sure what the cause is that the loggedIn is only set on the client side and not on the SSR side :/ I've used this module before, once for a local strategy (+- 2 years ago) and 3 months ago with a oauth2 strategy and I can't remind myself that I had any problems with it back than 😬

nikolayandreev commented 4 years ago

@dgvai glad that worked for you, but I don't see why would you use that, when the plugin's auth middleware is better, so let's try to get this bad boy working eh?

In my case it works great if I setup a global routerMiddleware

Add this to nuxt.config.js

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

And then for routes I want to be public I add auth: 'guest' for each page!

layouts/default.vue - auth: false layouts/profile.vue - middleware: 'auth' - Try without it I think it's not neccessary to add it, but I can't test right now.

So keypoints:

Set auth middleware as global route Middleware default.vue should have auth set to false For each page which you want to leave public set auth to 'guest'

If this doesn't help please post your settings for the auth in nuxt.config.js.

geantas commented 4 years ago

I can't get it working, really. Spent 2 days on just this issue and I am almost giving up. Anyone would fancy helping me out?

layouts/default.vue

export default {
  name: 'DefaultLayout',
  auth: false
}

pages/login.vue

export default {
  auth: 'guest'
}

nuxt.config.js

  mode: 'universal',
  target: 'static',
  auth: {
    cookie: {
      prefix: 'auth_'
    },
    redirect: {
      login: '/login',
      logout: '/login',
      // callback: false,
      home: '/retailer/account'
    },
    strategies: {
      local: {
        endpoints: {
          login: {
            url: '/auth/login',
            method: 'post',
            propertyName: 'access_token',
            credentials: true
          },
          logout: {
            url: '/auth/logout',
            method: 'post'
          },
          user: {
            url: '/auth/me',
            method: 'post',
            propertyName: '',
            credentials: false
          }
        },
        token: {
          required: true,
          type: 'Bearer',
          global: true
        },
        autoFetchUser: true
      }
    },
    preserveState: true,
    watchLoggedIn: true
  },
  router: {
    middleware: [
      'auth'
    ]
  }

I can log in fine and I cannot access /login page when clicking a link. But if I manually enter /login into URL, it shows me the page, no redirections. I was trying to get logged in state by creating own middleware (see below), etc, but app.$auth.loggedIn always returns false in my case.

Custom middleware I've tried with: middleware/authenticated.js

export default function ({ app, redirect }) {
  if (app.$auth.loggedIn) {
    return redirect(app.localePath({ name: 'index' }))
  }
}
nikolayandreev commented 4 years ago

@geantas That's a long shot, but I noticed you have commented out callback from redirects, I understand that you do not use oAuth2 and that's why you think it should be commented out, but messing with callback url has created problems such as that one for me in the past.

Can you try to put this in nuxt.config.js in auth settings:

redirect: {
      login: '/login',
      logout: '/login',
      callback: '/login',
      home: '/retailer/account'
    },
geantas commented 4 years ago

@geantas That's a long shot, but I noticed you have commented out callback from redirects, I understand that you do not use oAuth2 and that's why you think it should be commented out, but messing with callback url has created problems such as that one for me in the past.

Can you try to put this in nuxt.config.js in auth settings:

redirect: {
      login: '/login',
      logout: '/login',
      callback: '/login',
      home: '/retailer/account'
    },

Hi @nikolayandreev , Unfortunately this did not change any behavior. Maybe you have any other ideas?

sergiocastrovale commented 4 years ago

I'm also stuck in this. Here are the test cases:

nuxt.config.js

auth: {
    plugins: ['~/plugins/auth.js']
    ...
}

~/plugins/auth.js

export default function({ app, $auth }) {
  $auth.options.redirect = {
    login: app.localePath({ name: 'users-login' }),
    logout: app.localePath({ name: 'index' }),
    callback: app.localePath({ name: 'users-login' }),
    home: app.localePath({ name: 'index' })
  }
}

login.vue

export default {
  auth: 'guest'
}

Any idea why this happens? Maybe @pi0 can help us out?

jclaessens97 commented 4 years ago

In my case it was due to my backend runs locally on https and a nodejs tls check stopped the auth module from working correctly because the axios calls on server side in nuxt are not secured. I set the https option of axios to true in nuxt.config.js, what fixed it for the deployed server, but not local. Locally I had to add the env var NODE_TLS_REJECT_UNAUTHORIZED=0. Also check the base url is set correctly.

Sorry for formatting. On mobile.

milladka commented 3 years ago

hey, I think auth options don't work without the middleware, so you need to enable it either globally or per route.

export default {
    middleware: 'auth'
    auth : 'guest'
}

worked

ernestopinto commented 3 years ago

Hi guys, let me post here my solution. First you must always bare in mind that SSR only works if a node based solution is set on your server, so the SSR = true is only effective on that conditions; other important aspect is the target of the build dist -> must be "static" for use in any shared / cloud hosting like digital ocean or aws (besides any node based/ docker based / container based solutions).

So here's my configuration for static web app hosted on cloud server:

nuxtconfig.js :

target: 'static', ssr: false, (...)

`auth: {

strategies: {
  local: {
    token: {
      property: 'data.access_token',
      type: 'Bearer'
    },
    user: {
      property: 'data.user',
      autoFetch: true
    },
    endpoints: {
      login: { url: '/login', method: 'post' },
      logout: { url: '/logout', method: 'post' },
      register: { url: '/register', method: 'post' },
      user: {url: '/user', method: 'get' }
    }
  }
},
redirect: {
  home: false
},

(...)

router: { middleware: 'auth' }

middleware/ guest.js :

export default function ({ store, redirect }) { // If the user is authenticated redirect to home page if (store.state.auth.loggedIn) { return redirect('/home') }

login.js :

export default { middleware: 'guest',

(...)

register/ index.js:

export default { auth: false,

for more info and contribuition : https://github.com/ernestopinto/nuxt-base-static

Hope this helps guys!

milladka commented 3 years ago

Hi guys, let me post here my solution. First you must always bare in mind that SSR only works if a node based solution is set on your server, so the SSR = true is only effective on that conditions; other important aspect is the target of the build dist -> must be "static" for use in any shared / cloud hosting like digital ocean or aws (besides any node based/ docker based / container based solutions).

So here's my configuration for static web app hosted on cloud server:

nuxtconfig.js :

target: 'static', ssr: false, (...)

`auth: {

strategies: {
  local: {
    token: {
      property: 'data.access_token',
      type: 'Bearer'
    },
    user: {
      property: 'data.user',
      autoFetch: true
    },
    endpoints: {
      login: { url: '/login', method: 'post' },
      logout: { url: '/logout', method: 'post' },
      register: { url: '/register', method: 'post' },
      user: {url: '/user', method: 'get' }
    }
  }
},
redirect: {
  home: false
},

(...)

router: { middleware: 'auth' }

middleware/ guest.js :

export default function ({ store, redirect }) { // If the user is authenticated redirect to home page if (store.state.auth.loggedIn) { return redirect('/home') }

login.js :

export default { middleware: 'guest',

(...)

register/ index.js:

export default { auth: false,

for more info and contribuition : https://github.com/ernestopinto/nuxt-base-static

Hope this helps guys!

in login export default { middleware: 'auth',auth:'guest'

bmulholland commented 3 years ago

The middleware configuration is documented at https://auth.nuxtjs.org/guide/middleware

If there's an issue to resolve, please create a new issue describing what's needed.

aacassandra commented 3 years ago

hey, I think auth options don't work without the middleware, so you need to enable it either globally or per route.

export default {
    middleware: 'auth'
    auth : 'guest'
}

without auth: 'guest' its works too

export default {
    middleware: 'auth'
}

looks like auth: guest is useless 😄

liviuzachin commented 3 years ago

I'm also stuck on this issue. Apparently auth: "guest" is not working in static mode.

satriaajiputra commented 3 years ago

I think the auth: 'guest' not work because the middleware being executed before the auth-module execute the user request. And finally, the loggedIn status always at false state every reloading (Ctrl+R) the page, and not redirecting.

dev-davexoyinbo commented 3 years ago

hey, I think auth options don't work without the middleware, so you need to enable it either globally or per route.

export default {
    middleware: 'auth'
    auth : 'guest'
}

Worked for me. Thanks man

pratamatama commented 2 years ago

I have the same issue, in my case, the login was successful and it was redirected to the home page but when I type the login endpoint manually in the browser, it shows up.

Project uses SSR.

brave_iZqH4QVptZ

nuxt.config.js

axios: {
  // Workaround to avoid enforcing hard-coded localhost:3000: https://github.com/nuxt-community/axios-module/issues/308
  baseURL: '/',
  proxy: true,
  credentials: true,
},
proxy: {
  '/laravel': {
    target: 'http://localhost',
    pathRewrite: { '^/laravel': '/' },
  },
},
auth: {
  strategies: {
    laravelSanctum: {
      provider: 'laravel/sanctum',
      url: '/laravel',
    },
  },
},
router: {
  middleware: ['auth'],
},

Login.vue

...
<script>
export default {
  name: 'LoginPage',
  auth: 'guest',
}
</script>
SuhaibKotb commented 2 years ago

@pratamatama I also have the same issue.

gmatkowski commented 2 years ago

same here ... any thoughts?

joinerleal commented 1 year ago

I have the same issue, in my case, the login was successful and it was redirected to the home page but when I type the login endpoint manually in the browser, it shows up.

Project uses SSR.

brave_iZqH4QVptZ

nuxt.config.js

axios: {
  // Workaround to avoid enforcing hard-coded localhost:3000: https://github.com/nuxt-community/axios-module/issues/308
  baseURL: '/',
  proxy: true,
  credentials: true,
},
proxy: {
  '/laravel': {
    target: 'http://localhost',
    pathRewrite: { '^/laravel': '/' },
  },
},
auth: {
  strategies: {
    laravelSanctum: {
      provider: 'laravel/sanctum',
      url: '/laravel',
    },
  },
},
router: {
  middleware: ['auth'],
},

Login.vue

...
<script>
export default {
  name: 'LoginPage',
  auth: 'guest',
}
</script>

I'm struggling with this, did you manage to get it fixed? pratamatama

pratamatama commented 1 year ago

Please apologize for the late reply @SuhaibKotb @joinerleal . Unfortunately no.. I decided to implement the auth manually using access token & local storage, and creating the middleware manually.