Auth-module: Nuxt Auth redirects (login/logout/home) not working

Created on 29 Aug 2019  ·  83Comments  ·  Source: nuxt-community/auth-module

Version

v4.8.1

Reproduction link

https://codesandbox.io/s/codesandbox-nuxt-0vhpu

Steps to reproduce

On bare simple setup

empty store.js

export const state = () => ({})

nuxt.config.js

auth: {
  redirect: {
    login: '/login',
    logout: '/',
    home: '/app',
    // callback: '/login'
  },
  watchLoggedIn: true
},

but seems only login redirect works... and in some rare cases logout but logout() can leave you on current page even if it required auth (when at worse it should at least take you back to login...)

if redirect.logout or redirect.callback points to a page that has middleware: ['auth'] then those pages can then be opened without requiring auth

couldn't get rewriteRedirects to work either... tried all combinations watchLoggedIn/rewriteRedirects

What is expected ?

short version that redirects work...

when auth.watchLoggedIn === true
after login() that user is redirected to auth: redirect.home

after logout that it kicks you out if you where on a require auth page

in codesandbox fiddle logout() from /app takes you back home... this is not happening in my project where it lets you on /app route giving the "Oupps"
(could it be i've got a slow old computer? I actually have issues too of npm run dev freezing and this doesn't happen on faster machines)

when auth.rewriteRedirects == true
that user is sent back to page he asked in first place

What is actually happening?

sometimes logout redirects (only when called from a page that didn't require auth... which isn't the common case)

lets logged out users open the current auth required page

routes mentioned as auth.redirect.logout or auth.redirect.callback becomes open to everybody no mater if had required auth.

This bug report is available on Nuxt community (#c407)

Most helpful comment

To be honest... that issue led me to abandon vue / nuxt totally !!
Took me few hours to write a proper bug report... weeks and nothing ?

On simple things like that not working and no signs that it'll be fixed...

when using passport js is just so simple... out of nuxt

I moved to Angular ...

good luck guys

All 83 comments

I have the same issue. In my case I have auth: 'guest' option in login page and I get redirected to the root page if I'm authenticated in DEV environment. However, redirection does not work in production environment. It works in production MODE in DEV environment, but it does not work in production MODE and production environment.

To be honest... that issue led me to abandon vue / nuxt totally !!
Took me few hours to write a proper bug report... weeks and nothing ?

On simple things like that not working and no signs that it'll be fixed...

when using passport js is just so simple... out of nuxt

I moved to Angular ...

good luck guys

I understand your struggle. Actually, I didn't know that there is a separate auth module in Nuxt and initially I wrote my own middleware where I was detecting the requested path and redirecting to the root path if my authenticated user was not allowed to see that specific page. But when I found this module, I started to use its interface and everything worked perfectly until I deployed my app to production and encountered this issue.

Maybe you should've given more chances to Nuxt.

I don't think so... I get things done 10x faster since I've moved on... tired of waisting my time to do basic simple things that turns out a nightmare most of the time.
Angular was much easier to get my hands on !!

Edit: why put thumbs down ?!!!
It's the truth, the learning curve to Angular is much easier than the one to broken logic in nuxt...

Is there something like Nuxt / Next built on top of Angular?

Le 15 sept. 2019 à 11:52, Mahram notifications@github.com a écrit :

Is there something like Nuxt / Next built on top of Angular?

there is much more... but universal angular amongst others :)

Maybe it is late according to the previous comments but I had some problems with the logout redirect too. I was able to redirect and avoid this problem calling the auth logout method
directly in one of my store actions:

async logout () { await this.$auth.logout() }

https://auth.nuxtjs.org/api/auth.html#logout-args

I had this behavior in my app and in my case the reason was something you also have in your sandbox in login.vue, line 44 — auth: false. Removing this line fixed the behavior for me (even though I have auth set up as app-wide middleware, the login route stays accessible). I kinda wish the docs were clearer.

thanks vakrolme

but this doesn't fix the problem of letting access to pages that shouldn't let you in as wen one clicks on
"Callback (try me before login to see...)"

I kinda wish the docs were clearer.

When I looked at the doc back then, it said that you had to specify auth: false;
But what doc are we talking about as there are 2 docs for this module that contredicts one another.

But as I said earlier... 4h after switching to Angular I had all this working like a charm... and was further in my app then in 1 week with nuxt...

I've been struggling the same problem and after taking a look into the source of auth-module I have figure out the configuration and it works, you can take a look here https://codesandbox.io/s/nuxt-starter-n4b6v-n4b6v
Note that in login page I have auth: "guest"

I've achieved rewriteRedirects like this.

  1. Enable rewriteRedirects option in nuxt.config.js
  2. Manually redirect in login page after successfully logged in like this:
    (Unfortunately automatic redirecting after logged in seems to be not working)
const path = this.$auth.$storage.getUniversal('redirect') || '/';
this.$auth.$storage.setUniversal('redirect', null);
this.$router.push(path);

Note that this feature is not tested enough and so buggy. We need to improve it.

https://github.com/nuxt-community/auth-module/blob/85466345311bf882ae2f603ba43ef1dc638d2cdb/lib/core/auth.js#L58

The problem is with this line. It check whether current page enable auth middleware to see if you have right to stay on current page when logout. But I can't figure out the point of this check when login.

When I remove auth: false, or use auth: 'guest' the redirect works.

https://auth.nuxtjs.org/api/options.html#redirect
The problem origin post encounter is actually specified in the docs. you'll only be redirect when

after logout, current route is protected.

Maybe it could be an option to disable this behavior.

The problem when login, on the other hand, is weird. It make sense to think you would have to disable auth middleware to prevent infinite redirect on login page. But you actually don't have to do that. When you disable it, it'll prevent the redirect. It not a straightforward behavior.

Can any person of the core team explain why this check is necessary while login or it's a bug?

If the check is necessary, maybe add a note to the docs about you can't disable auth middleware in login page. If it's a bug. How to fix it is a problem, just disable the check in login would result in different redirect page if the fallback redirect dev added after login is different.

Nice job to have figured this out.

But how about ditching all that crap and just have something like nuxt-community/passport

It could be more useful... and probably a complet rewrite could give it a chance to get somewhere useable a bit further than just to get "what I need write now to work, the rest we'll see later"... Isn't it wordpress world philosophy?

How many dev contributing to nuxt are actually in search of a wordprout alternative?

It's impossible to think out of the box from within the box...

I think working with angular could open the box for many nuxt dev...
It's what happened to me, and since, each time I have to deal with nuxt, it just reminds me of wordpress...

I think you made a good analysis of the problem, so you have to be pretty smart to have worked this out and perhaps your time is too precious to continue bother with nuxt :)

Regards

Le 6 févr. 2020 à 02:50, jasonlyu123 notifications@github.com a écrit :

https://github.com/nuxt-community/auth-module/blob/85466345311bf882ae2f603ba43ef1dc638d2cdb/lib/core/auth.js#L58 https://github.com/nuxt-community/auth-module/blob/85466345311bf882ae2f603ba43ef1dc638d2cdb/lib/core/auth.js#L58
The problem is with this line. It check whether current page enable auth middleware to see has right to stay on current page when logout. But I can't figure out the point of this check when login.

When I remove auth: false, or use auth: 'guest' the redirect works.

https://auth.nuxtjs.org/api/options.html#redirect https://auth.nuxtjs.org/api/options.html#redirect
The problem origin post encounter is actually specified in the docs. you'll only be redirect when

after logout, current route is protected.

Maybe it could be an option to disable this behavior.

The problem when login, on the other hand, is weird. It make sense to think you would have to disable auth middleware to prevent infinite redirect on login page. But you actually don't have to do that. When you disable it, it'll prevent the redirect. It not a straightforward behavior.

Can any person of the core team explain why this check is necessary while login or it's a bug?

If the check is necessary, maybe add a note to the docs about you can't disable auth middleware in login page. If it's a bug. How to fix it is a problem, just disable the check in login would result in different redirect page if the fallback redirect dev added after login is different.


You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/437?email_source=notifications&email_token=AA7DNJLC6SL46D3FDNKB7ULRBOQKVA5CNFSM4IR2HXA2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEK6ASBI#issuecomment-582748421, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJJRB73GHJ6ST22YH23RBOQKVANCNFSM4IR2HXAQ.

woa dude alm down its not an nuxt issue..

I fixed it like

redirect: {
      home: false
    },

and then in my login method

  await this.$auth.loginWith('local', {
          data: this.login
        })
        this.$router.push(this.localePath({ name: 'dashboard' }))

its not 100% working maybe you can add check on mounted/created and redirect

how is anybody suppose to guess such a trick ?

And altho it's not a nuxt issue, it's common in all the nuxt eco-system.

I got more done by 3rd day working with angular than after 3 month fighting with nuxt...

It's just an advice I gave you...
If you want to waist energy on hacking a framework to get it to do such an exotic thing as using auth :-/

But for anyone reading here... lets not lead them into heal.

To be honest, nuxt has some nice sides, but don't believe one second it's easier than angular.
And if you need auth in your app, using nuxt, be prepared to go threw hell.. unless you don't care auth feeling very bugus.
At some point, who cares, if you rely on api auth to handle the real security, it's just the interface that will behave bugus.
Then one can hack it to feel better, and what happens when nuxt will overcome thos issue, need to unhack it? In a few years, it'll be fun to remember what the story was...

Le 6 févr. 2020 à 12:19, Marko Bolliger notifications@github.com a écrit :

woa dude alm down its not an nuxt issue..

I fixed it like

redirect: {
home: false
},
and then in my login method

await this.$auth.loginWith('local', {
data: this.login
})
this.$router.push(this.localePath({ name: 'dashboard' }))

You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/437?email_source=notifications&email_token=AA7DNJLL6K6ACVYT4Q7HISLRBQS7FA5CNFSM4IR2HXA2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEK7S2JY#issuecomment-582954279, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJNVCT74SBI74VOOTVDRBQS7FANCNFSM4IR2HXAQ.

Now it's my personal opinion and advice for new arrivers to nuxt... move on to angular, you'll save your time, your nerves and your energy...
At the end of the day, we are all free to do what we want, but I wish I had read somewhere the advice I'm giving here, it would have saved me several month of useless work/energy.

Edit:
And yes sorry, I should mention nuxt can become a nice frontend to wordpress... but this is not how I picture the futur of my work. I've had to dive into wordpress code and I hope never to have to do it ever again.

@cantoute Your comment is very dangerous, you are selecting and encouraging a technology, it is based on your inexperience or frustration.

If you come from Wordpress, the thought of installing and using is hurting you and if you say that you did it faster in Angular, it is because capable your previous way of working adapted to that, and I understand the frustration you have hate towards a technology, but one knows that it has matured when it leaves that hatred back and returns to keep learning.

About your issue:

@cantoute I do like angular's robustness and appreciate the featureful ecosystem Google and angular's team has provided. I personally would prefer to do my own project in angular.
But the advantage or angular also come with the cost of high learning curve. It hard for me to persuade all of my colleague to spend their personal time to learn it. Vue also still have the advantage to be easy to learn and scalable (somewhat different scales with angular in my opinion thought). It's much more easier for my team to switch to.
Every major frontend framework/library has its pro and cons, strengths and weaknesses, there is no perfect one for every use case.
Also, since this is an community maintained project , that's just maintain a constructive discussion and contribute our opinion/advise to make it better.

I am facing an error where, after I am successfully logged in, I should get redirected to /my-account. But I get redirected to /logged-out, then shortly after, I get redirected to /my-account.

I believe I so far solved most of my problems with the auth module. Would be nice to be able to handle redirects and middleware yourself though, for ultimate control.

Anyhow, I figured after changing certain settings, I had to shutdown development server and boot it up again for changes to take effect.

I am still facing this error. After successful login once I refresh a secured page, I get redirected to login page. Is there a workaround for this problem?

@HappyStore Are you using ssr? I have a maybe similar problem with ssr mode but it's not related to this topic. The problem is that auth module make a request on server to fetch user data and the request got rejected due to self-signed ssl certificate and no error is thrown.

@HappyStore Are you using ssr? I have a maybe similar problem with ssr mode but it's not related to this topic. The problem is that auth module make a request on server to fetch user data and the request got rejected due to self-signed ssl certificate and no error is thrown.

Hmm, once I removed "user" endpoint it worked as expected. Could be SSR problem you mentioned. Thank you!

I am still facing this error. After successful login once I refresh a secured page, I get redirected to login page. Is there a workaround for this problem?

I never have that problem, can you make a repo with the code and example of the response of your api..

I have same problem. Make sure user endpoint gets the user object correctly. If your user api responds the whole user object set the propertyName to false to tell Nuxt to directly use API response.

auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: '/api/auth/local', method: 'post', propertyName: 'jwt' },
          logout: { url: '/api/auth/logout', method: 'post' },
          user: { url: '/api/users/me', method: 'get', propertyName: false }
        }
      }
    }
  }

Came here to find a way to redirect my users only to find angular spam.
@cantoute we get it, you moved to angular. Then go ahead and move on and please let us focus on the issue of the redirect here 👍

To the issue:
I'm trying to make this happen with the auth0 strategy. No luck so far but will try some more suggestions from this thread and report back

Le 31 mars 2020 à 11:59, Sumit Kumar notifications@github.com a écrit :

Came here to find a way to redirect my users only to find angular spam.
@cantoute https://github.com/cantoute we get it, you moved to angular. Then go ahead and move on and please let us focus on the issue of the redirect here 👍

6 month still not one step towards a solution...

My advice isn't spam... it's just a warning to anyone not to get trapped in this loophole of asking something so exotic for an app to be able to manage authentification.

Perhaps you can read between the lines my frustration (and the fact I can't bare mediocrity)
I had worked on an app assuming nuxt could manage a simple authentification... lost 3 month of my time for that mistake, so my honest advice to anyone wanting to use nuxt is that I hope you don't need authentification.

Took me several hours to do this bug report not because no-one hit into this issue, but because no-one else bothered... And they were right, no-one look at it for over 3 month and still not a single hope of this issue to get near by to be solved simply because this auth module doesn't make any sense... why not simply have passport integration ? (ex: nuxt/auth-passport)

having a universal framework not having a single usable auth solution is a crazy... but this isn't the worse part of the incoherence in this framework, it seems so much that dev here are ex-wordpress dev repeating exactly what they where trying to run away from...

To the issue:
I'm trying to make this happen with the auth0 strategy. No luck so far but will try some more suggestions from this thread and report back

Enjoy....

issue published 6 month ago... the only clue shoing up is that could be Vue.js devtools chrome extension could be related to the issue... :-/


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/437#issuecomment-606718801, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJKYDQW2XHGNAHWG4O3RKIHNXANCNFSM4IR2HXAQ.

Le 31 mars 2020 à 12:23, Majid Zarrin notifications@github.com a écrit :

Vue.js devtools chrome extension!!!
removing it from chrome made my Nuxt app alive.

Vue.js devtools chrome extension https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd/related?hl=en

Marvelous !!

First answer that looks into solving that issue...


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/437#issuecomment-606732184, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJKI53OVPWBHH6UHRXTRKIKITANCNFSM4IR2HXAQ.

I don't think so... I get things done 10x faster since I've moved on... tired of waisting my time to do basic simple things that turns out a nightmare most of the time.
Angular was much easier to get my hands on !!

Came here to find a way to redirect my users only to find angular spam.
@cantoute we get it, you moved to angular. Then go ahead and move on and please let us focus on the issue of the redirect here 👍

To the issue:
I'm trying to make this happen with the auth0 strategy. No luck so far but will try some more suggestions from this thread and report back

I could simply delete that bug report and send you all to f..k yourself... 6 month and no-one f...ing bothered to think of trying to solve it... no-one needs auth in their app ?

Watch it guys... next comment like this and I delete that bug report and you can do it yourself to see !!

And you want to make me look like I'm the bad guy here when it seems here that I'm the only-one here who actually did something looking towards trying to solve the problem ?!!
Yeah, making a bug report is part of looking into the right direction...
And because it came obvious that this isn't the common behavior here, yes, I advertise for anyone not yet in that trap to look elsewhere.
If it feels to you guy like a kick in the b...ks, it's what it is!!
It's my f..k you very much for the time I wasted with this crap... your crap?

Sorry to be rude but to some point one collect what one deserves !!
And that community just reminds me of that of wordpress !!

@cantoute I wish start again, can you try with this example, and explain specifically the bug.

https://nwzyp.sse.codesandbox.io/
https://codesandbox.io/s/codesandbox-nuxt-nwzyp

Le 31 mars 2020 à 23:32, Jose Manuel Casani Guerra notifications@github.com a écrit :

@cantoute https://github.com/cantoute I wish start again, can you try with this example, and explain specifically the bug.

https://nwzyp.sse.codesandbox.io/ https://nwzyp.sse.codesandbox.io/

I don't see what isn't clear here...
When I click on (try me before login to see...) I get to see a page that should require auth... amongst other things that don't behave as expected


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/437#issuecomment-607007110, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJJV2RA5TRFW22ZDBE3RKKYUHANCNFSM4IR2HXAQ.

Le 31 mars 2020 à 23:32, Jose Manuel Casani Guerra @.*> a écrit : @cantoute https://github.com/cantoute I wish start again, can you try with this example, and explain specifically the bug. https://nwzyp.sse.codesandbox.io/ https://nwzyp.sse.codesandbox.io/
I don't see what isn't clear here... When I click on (try me before login to see...) I get to see a page that should require auth... amongst other things that don't behave as expected

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub <#437 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJJV2RA5TRFW22ZDBE3RKKYUHANCNFSM4IR2HXAQ.

That is because I use my API, change with your api and try. I can't reproduce the bug.

Le 31 mars 2020 à 23:38, Jose Manuel Casani Guerra notifications@github.com a écrit :

Le 31 mars 2020 à 23:32, Jose Manuel Casani Guerra @.*> a écrit : @cantoute https://github.com/cantoute https://github.com/cantoute https://github.com/cantoute I wish start again, can you try with this example, and explain specifically the bug. https://nwzyp.sse.codesandbox.io/ https://nwzyp.sse.codesandbox.io/ https://nwzyp.sse.codesandbox.io/ https://nwzyp.sse.codesandbox.io/
I don't see what isn't clear here... When I click on (try me before login to see...) I get to see a page that should require auth... amongst other things that don't behave as expected
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub <#437 (comment) https://github.com/nuxt-community/auth-module/issues/437#issuecomment-607007110>, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJJV2RA5TRFW22ZDBE3RKKYUHANCNFSM4IR2HXAQ https://github.com/notifications/unsubscribe-auth/AA7DNJJV2RA5TRFW22ZDBE3RKKYUHANCNFSM4IR2HXAQ.

That is because I use my API, change with your api and try. I can't reproduce the bug.

Strange...

In the sandbox I put with bug report I still have the issue

https://codesandbox.io/s/codesandbox-nuxt-0vhpu https://codesandbox.io/s/codesandbox-nuxt-0vhpu


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/437#issuecomment-607008868, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJI3IKY34QVA6WKF2K3RKKZNBANCNFSM4IR2HXAQ.

I delete watchLoggedIn: true, because is unnecessary , the default value is true ..

And add custom strategies routes:

strategies: {
      local: {
        endpoints: {
          login: {
            url: "/v1/auth/login",
            method: "post",
            propertyName: "access_token"
          },
          user: {
            url: "/v1/auth/yo",
            method: "get",
            propertyName: "data"
          }
        }
      }
    }

@cantoute If you ask about the callback page for auth users, the callback page if always public:

https://github.com/nuxt-community/auth-module/blob/dev/lib/core/middleware.js#L54

Le 31 mars 2020 à 23:45, Jose Manuel Casani Guerra notifications@github.com a écrit :

@cantoute https://github.com/cantoute If you ask about the callback page for auth users, the callback page if always public:

https://github.com/nuxt-community/auth-module/blob/dev/lib/core/middleware.js#L54 https://github.com/nuxt-community/auth-module/blob/dev/lib/core/middleware.js#L54

I'm really sorry guys, this is over 6 month old and I did fight over 2 weeks on trying to get this to work, reading loads of contradictory information...

All this is over complicated and twisted minded when compared to using passport strategy (over vanilla js or with other frameworks)

To me, all this nuxt-auth is to be refactored from base and I'm not going to put my head into this ever again.

Perhaps nuxt dev should work with other framework and consider a total refactor of a new vuejs universal assembly with a wider view of the problem... a next-vue ?

My advise to anyone here is to not waist more energy on this sinking ship...
But every one is free to spend it's time on what ones want, even if it's on a sinking ship...

I can only wish you all the best, and really I can't get it that I'm the only one having issue with nuxt-auth... uness one doesn't care having to super-hack to get a simple auth to work.
Really, give a try to any passport auth package to see how simple it is to have something powerful to work... it's really less then 10 lines clear and simple!


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/437#issuecomment-607010622, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJPFFDLGP4QWCIZJ7N3RKK2FNANCNFSM4IR2HXAQ.

@cantoute Help me to help you. The frustation can be big, but you need stay relaxed and look.

I recommend this, do in Angular (can be more easy for you) that can motivate you, and when your are relaxed, can you return this report bug, I always stay here to help you.

If I find the bug, I will to make the pull request to fix.

Le 1 avr. 2020 à 00:08, Jose Manuel Casani Guerra notifications@github.com a écrit :

@cantoute https://github.com/cantoute Help me to help you. The frustation can be big, but you need stay relaxed and look.

I recommend this, do in Angular (can be more easy for you) that can motivate you, and when your are relaxed, can you return this report bug, I always stay here to help you.

If I find the bug, I will to make the pull request to fix.

I know you try to be helpful, but this comes just 6 month to late for me...

And how should I relax if 6 month later I'm still waiting my time still trying to help to get this issue fixed !


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/437#issuecomment-607018354, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJINHZPHQ3SCYBIJGRTRKK42FANCNFSM4IR2HXAQ.

Le 1 avr. 2020 à 00:10, Antony antony@cantoute.com a écrit :

Le 1 avr. 2020 à 00:08, Jose Manuel Casani Guerra <[email protected] notifications@github.com> a écrit :

@cantoute https://github.com/cantoute Help me to help you. The frustation can be big, but you need stay relaxed and look.

I recommend this, do in Angular (can be more easy for you) that can motivate you, and when your are relaxed, can you return this report bug, I always stay here to help you.

If I find the bug, I will to make the pull request to fix.

I know you try to be helpful, but this comes just 6 month to late for me...

And how should I relax if 6 month later I'm still waiting my time still trying to help to get this issue fixed !

And btw, I work with many other devs and the only other community I got in this kind of pointless fights/arguments is wordpress...


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/437#issuecomment-607018354, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJINHZPHQ3SCYBIJGRTRKK42FANCNFSM4IR2HXAQ.

Well, can explain specifically the bug? I think make a video trying to reproduce the bug and fix.

Le 1 avr. 2020 à 00:15, Jose Manuel Casani Guerra notifications@github.com a écrit :

Well, can explain specifically the bug? I think make a video trying to reproduce the bug and fix.

I still don't understand what in the sandbox isn't clear about nothing working as expected... nor a "auth only" page nor login that should route to app nor logout to home...


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/437#issuecomment-607020128, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJK7TSJ7PYTPBPXMOVDRKK5XLANCNFSM4IR2HXAQ.

Le 1 avr. 2020 à 00:15, Jose Manuel Casani Guerra @.*> a écrit : Well, can explain specifically the bug? I think make a video trying to reproduce the bug and fix.
I still don't understand what in the sandbox isn't clear about nothing working as expected... nor a "auth only" page nor login that should route to app nor logout to home...

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub <#437 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJK7TSJ7PYTPBPXMOVDRKK5XLANCNFSM4IR2HXAQ.

Ok, I will make the video trying to reproduce the bug and share here.

Le 1 avr. 2020 à 00:19, Jose Manuel Casani Guerra notifications@github.com a écrit :

Le 1 avr. 2020 à 00:15, Jose Manuel Casani Guerra @.*> a écrit : Well, can explain specifically the bug? I think make a video trying to reproduce the bug and fix.
I still don't understand what in the sandbox isn't clear about nothing working as expected... nor a "auth only" page nor login that should route to app nor logout to home...
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub <#437 (comment) https://github.com/nuxt-community/auth-module/issues/437#issuecomment-607020128>, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJK7TSJ7PYTPBPXMOVDRKK5XLANCNFSM4IR2HXAQ https://github.com/notifications/unsubscribe-auth/AA7DNJK7TSJ7PYTPBPXMOVDRKK5XLANCNFSM4IR2HXAQ.

Ok, I will make the video trying to reproduce the bug and share here.

If you like.

I don't see how this will improve the situation but it can't heart.

perhaps one could look into integrating passport

when looking at this it really looks painful to get them working together!
https://github.com/Scharkee/vue-nuxt-passport-bulma-express-boiler https://github.com/Scharkee/vue-nuxt-passport-bulma-express-boiler

and see of a way to make passport easier to integrate... a @nuxt/auth-passport ?

just an idea...


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/437#issuecomment-607021276, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJOGEEOGNXX532BRYELRKK6GVANCNFSM4IR2HXAQ.

So after spending many hours on this, I figured this out:

  • If you are using axios baseURL and mode 'universal' in nuxt config, then redirects won't work. Change mode to 'spa'.
  • OR, stop using axios baseURL and use nuxt axios proxy instead.

Either solution should resolve redirection issues.

@namanyayg: Could you provide a working snippet of your configuration? I'm struggling with the same problem and I'm not 100% sure if I understand your hint correctly. ;-)

@DavidFeller modified my comment to be more clear, is that helpful?

So after spending many hours on this, I figured this out:

  • If you are using axios baseURL and mode 'universal' in nuxt config, then redirects won't work. Change mode to 'spa'.
  • OR, stop using axios baseURL and use nuxt axios proxy instead.

Either solution should resolve redirection issues.

Great work !

Thank you very much for all of us to have isolated the issue.

I would never have guessed the issue could come from combining with axios :-/

With that clue perhaps someone will find a fix... but I would't count on any of those who down voted me here lol (I have doubt on their ability to code... Could they prove me wrong, I would apologize, but I would be really surprised, when coders make me look like the bad guy, by my experience, they had proven they were trying to hide their incompetence. Please prove me wrong :)

@namanyayg @DavidFeller Can you try to enable logging in nuxt-axios module to see if there is any error get logged?
They try catch most of request and didn't rethrow or log error in auth.js.
you can see #478 for related issue
Also, these are the issue with what i mentioned about universal sometime ago.

If you are using axios baseURL and mode 'universal' in nuxt config, then redirects won't work. Change mode to 'spa'.
OR, stop using axios baseURL and use nuxt axios proxy instead.

Thank you!!!

i am using universal mode. First i am working on local schema.
i set
axios: {
proxy: true
}
and global middleware to auth
but still after login it is not redirecting to / route. So as a last attempt i did location.reload() both in login and logout methods after doing $auth.loginWith() or $auth.logout()
and it is working now.

This is not report of a Bug!
The Nuxt Auth is the Bug!
for me The Nuxt Auth takes more than 3 times of completing all other part of my project.
Auth documentation seems complete but it is not strait-forward telling.

This is not report of a Bug!
The Nuxt Auth is the Bug!
for me The Nuxt Auth takes more than 3 times of completing all other part of my project.
Auth documentation seems complete but it is not strait-forward telling.

time to have a nuxt/auth-passort !!

@namanyayg could you be more specific on the config you added for axios proxy. I added the proxy module and set the axios proxy config to true and kept my app at universal and it is still not working.

I see the code to find the bug, and think this part of code interesting in the config 🤔

  axios: {
    proxy: true
  },
  proxy: {
    '/api': 'http://localhost:3000'
  },

@cantoute @mjzarrin @la-jamesh

I made this video to test the module and see all normal. If your have some config to test or fix, send me here or in private @MrJmpl3 in Twitter, to made another video

https://www.youtube.com/watch?v=uYZBoCDMZ4I&feature=youtu.be

This is not a good idea, but it works for me:
this.$auth.redirect("home", true)

Guys, this is _most likely_ because your user routes are not defined correctly. Auth does not work if user object is not fetched correctly. If you don't need user object, you have to set user route to _false_.

And you, mister Angular, in your codesandbox I don't see any routes defined.

cool :)

just it took so long I gave up...

And I continue following this thread as solving this will help many avoiding same disaster I had to go threw.
And perhaps when this is solved I'll consider using nuxt on other projects :)

Le 3 mai 2020 à 09:11, Fyroman notifications@github.com a écrit :

Guys, this is most likely because your user routes are not defined correctly. Auth does not work if user object is not fetched correctly. If you don't need user object, you have to set user route to false.

And you, mister Angular, in your codesandbox I don't see any routes defined.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/nuxt-community/auth-module/issues/437#issuecomment-623108022, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJILDHZRMW6RLCPL6T3RPVUO5ANCNFSM4IR2HXAQ.

cool :) just it took so long I gave up... And I continue following this thread as solving this will help many avoiding same disaster I had to go threw. And perhaps when this is solved I'll consider using nuxt on other projects :)

Le 3 mai 2020 à 09:11, Fyroman @.*> a écrit : Guys, this is most likely because your user routes are not defined correctly. Auth does not work if user object is not fetched correctly. If you don't need user object, you have to set user route to false. And you, mister Angular, in your codesandbox I don't see any routes defined. — You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub <#437 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/AA7DNJILDHZRMW6RLCPL6T3RPVUO5ANCNFSM4IR2HXAQ.

🤔 I made a video and all was correct, nobody make a comment about my video 😥

@MrJmpl3 because @cantoute very much seems like a troll. He's trying to implement auth system without any api routes defined. The whole guide is in this module's docs. What the hell does he think he logs in with?

If Angular actually made it clearer to beginners how to set up an auth system, then I must say I'm surprised, because that whole framework is a clusterf*.

Please, don't fight, If this report don't help to fix the bug or the reporters don't want to help to fix, I recommend close, maybe another people create new report with more info or with more expectations in helping.

revisiting this it looks like I'm only having issues when deployed to AWS via serverless/fastify. Running locally through nuxt in universal mode with auth0 appears to be working fine. I'll have to see where my configuration is wrong for serverless/fastify. Thanks for all the comments here.

Thanks for all helps. Closing as there are enough answers to the original question. Let's keep nuxt community a friendly place :heart:

v5 branch is also under heavy development and improvements including a more stable loggedIn state (#620) and many more improvements by @JoaoPedroAS51.

Please open a new issue with proper reporo in case you had similar issues :)

for me all suggestion didn't work. The login was succeeding, everything set to local storage but no redirection to the correct page. Checked all I could and didn't work. Then I remembered one other project I worked with nuxt and found the solution and here I share it

my backend was sending back something like

{
    "success" : true,
    "message" : "Succesfully logged in",
    "token" : "JWT Token Here"
}
    async login () {
      try {
        const response = await this.$auth.loginWith('local', {
          data: {
            username: this.username,
            password: this.password
          }
        })
        if (response.data.success === true) {
          this.$auth.setUserToken(response.data.token)
        }
      } catch (err) {
        console.log(err)
      }
    }

@mtangoo What does your configuration look like?

Here we go!

auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: '/users/login', method: 'post', propertyName: 'token' },
          logout: { url: '/users/logout', method: 'post' },
          user: { url: '/users/profile', method: 'get', propertyName: false }
        },
        tokenRequired: true,
        tokenType: 'Bearer',
        autoFetchUser: false
      }
    },
    redirect: {
      login: '/login',
      logout: '/logout',
      home: '/dashboard'
    }
  }

I think it's because of autoFetchUser: false. Might as well set user endpoint to "false" since it seems like you don't really use it.

If you have user endpoint defined, from what I understand nuxt-auth expects user to be fetched and only after that does it set the "loggedIn" state. If that doesn't happen, it won't consider you logged in and will not proceed with redirects.

So if you don't need the user object, just set the endpoint to "false" and it will not expect it to be called.

I think it's because of autoFetchUser: false. Might as well set user endpoint to "false" since it seems like you don't really use it.

No I use it. But it was annoying that when login failed it would request user anyway (My login endpoint is return always 200 with login status in JSON reponse)

So I had to turn it off for automatic but I use it

If you have user endpoint defined, from what I understand nuxt-auth expects user to be fetched and only after that does it set the "loggedIn" state. If that doesn't happen, it won't consider you logged in and will not proceed with redirects.

But why does refresh work?

But it was annoying that when login failed it would request user anyway (My login endpoint is return always 200 with login status in JSON reponse)

Hi @mtangoo! I believe one solution would be creating a custom scheme that extends local scheme. That way you can override the login method to match your requirements and enable autoFetchUser again :)

Before creating the custom scheme, you will need to add @nuxtjs/auth to transpile.

nuxt.config.js

build: {
  transpile: ['@nuxtjs/auth']
}

With this set up, you can create your scheme file.

~/schemes/customLocalScheme.js

import LocalScheme from '@nuxtjs/auth/lib/schemes/local'

export default class CustomLocalScheme extends LocalScheme {
  // Override `login` method of `local` scheme
  async login (endpoint) {
    if (!this.options.endpoints.login) {
      return
    }

    // Ditch any leftover local tokens before attempting to log in
    await this.$auth.reset()

    const { response, result } = await this.$auth.request(
      endpoint,
      this.options.endpoints.login,
      true
    )

    // If not succeeded, bail
    if (!response.data.success) {
      return
    }

    // Set token if `tokenRequired` is enabled
    if (this.options.tokenRequired) {
      const token = this.options.tokenType
        ? this.options.tokenType + ' ' + result
        : result

      this.$auth.setToken(this.name, token)
      this._setToken(token)
    }

    // Fetch user if `autoFetchUser` is enabled
    if (this.options.autoFetchUser) {
      await this.fetchUser()
    }

    return response
  }
}

Then set your new scheme in the auth config.

nuxt.config.js

auth: {
  strategies: {
    local: {
      _scheme: '~/schemes/customLocalScheme',
      /* ... */
    }
  }
}

I will try that one. Makes life easy sharing with projects

For those who like me got stuck on why their own redirection was going through home page even with the home: false

await this.$auth.loginWith("local", { data: { email, password } })
// i get a specific URL to redirect to from my user response
const url = this.$auth.user.url
this.$router.push(`/${url}`)

Switching to logout: false instead made the job (makes no sense but it's working for now).

My auth config :

auth: {
    redirect: {
        login: "/login",
        logout: false
    },
    strategies: {
        local: {
            endpoints: {
                login: {
                    url: "/users/login/token",
                    method: "post",
                    propertyName: "token"
                },
                user: { url: "/users/login/me", method: "get", propertyName: "user" },
                        logout: { url: "/api/auth/logout", method: "post" },
            }
        }
    }
}

https://github.com/nuxt-community/auth-module/blob/85466345311bf882ae2f603ba43ef1dc638d2cdb/lib/core/auth.js#L58

The problem is with this line. It check whether current page enable auth middleware to see if you have right to stay on current page when logout. But I can't figure out the point of this check when login.

When I remove auth: false, or use auth: 'guest' the redirect works.

https://auth.nuxtjs.org/api/options.html#redirect
The problem origin post encounter is actually specified in the docs. you'll only be redirect when

after logout, current route is protected.

Maybe it could be an option to disable this behavior.

The problem when login, on the other hand, is weird. It make sense to think you would have to disable auth middleware to prevent infinite redirect on login page. But you actually don't have to do that. When you disable it, it'll prevent the redirect. It not a straightforward behavior.

Can any person of the core team explain why this check is necessary while login or it's a bug?

If the check is necessary, maybe add a note to the docs about you can't disable auth middleware in login page. If it's a bug. How to fix it is a problem, just disable the check in login would result in different redirect page if the fallback redirect dev added after login is different.

Also, I want to note that the "auth" option must be used on layouts, not on pages ( I was doing it wrong ) for this to work.
Maybe they don't need to fix the module, but update the docs ( because they are confusing )

Yeah. I tried to submit a PR to update the doc but not been accepted. Maybe you can try it.
I think the opposite of auth: true is not false but 'guest'. false would disable redirect, not just the middleware. At first glance I would think redirect after login/logout is not the responsibility of a middleware thus think it won't affect redirect but it's not.

I had a similar problem. I had to redirect the user depending on the Role (User or admin), so, the solution of just writing one common redirection did not work for me. I did the following, I have created a vue page called redirect.vue and there I wrote a middleware that checks the role of the user in order to redirect to the correct page (getting the users info from the vuex store), this solution may not be the best one but works. I hope this help someone!

redirect.vue (page):

<template>
  <div></div>
</template>

<script>
export default {
  middleware: 'redirect_middleware',
  data() {
    return {}
  }
}
</script>

redirect_middleware.js (middleware)

export default function({ store, redirect }) {
  if (
    store.state.auth.loggedIn &&
    (store.state.auth.user.role === 'user'
  ) {
    return redirect('/userspage')
  } else if (
    store.state.auth.loggedIn &&
    store.state.auth.user.role === 'admin'
  ) {
    return redirect('/adminpage')
  }
}

Note: For this to work, make sure that in the users table is a field called "role"

auth object inside nuxt.config.js
auth: { strategies: { local: { endpoints: { login: { url: 'api/auth/login', method: 'post', propertyName: 'token' }, logout: { url: 'api/auth/logout', method: 'get' }, user: { url: 'api/me', method: 'get', propertyName: 'data' } } } }, redirect: { home: '/auth/redirect', login: '/auth/login', logout: '/' }, fullPathRedirect: true }

From Colombia to the world! :)

I get 'this page could not be found`

This shit is annoying

I get 'this page could not be found`

This shit is annoying

Create the page that is not found, under /pages directory. If you need any help. just reply!

I get 'this page could not be found`
This shit is annoying

Create the page that is not found, under /pages directory. If you need any help. just reply!

I get 'this page could not be found`

This shit is annoying

Hi,

I found out it is due to nuxt-i18n - it creates routes for all the different languages(locales) and the auth module does'nt, out of the box, play nicely.

What i did on 'nuxt-i18n' was to disable the prefix option via strategy: 'no_prefix'

However, im having issues with the module as it continually says the local strategy is not defined

  /*
   ** Nuxt.js modules
   */
  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
    '@nuxtjs/auth-next',


    [
      'nuxt-i18n',
      {
        lazy: true,
        locales: [
          {
            code: 'en',
            file: 'en.js'
          }
        ],
        strategy: 'no_prefix',
        defaultLocale: 'en',
        fallbackLocale: 'en',
        lazy: true,
        langDir: 'locales/'
      }
    ]
  ],

 /*
   ** Auth module configuration
   ** See https://auth.nuxtjs.org/#
   */
  auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: 'auth/login', method: 'post' },
          user: false,
          logout: { url: 'auth/logout', method: 'get' }
        },

        tokenRequired: true,
        autoFetchUser: false
        //   tokenType: false
      }
    }
  },

Ive been trying to play with the options to try and get it to work and have had no luck.

@cantoute

In my company we develop large-scale apps in Angular and React and our customers are public sectors of countries.

I tell you now:

Angular is a MESS/HELL of observables, subscriptions. services, modules etc
and if you are a newbie you have to spend ALOT of time in order to learn how to setup a proper project architecture

Nuxt.j is GREAT and saves you a lot of time when developing large applications

@cantoute could have a more positive and collaborative approach.

That said, I used Nuxt.js for the first time in 2017, have been using it since from time to time, and I kinda understand the frustration: authencation was as much a pain 3 years ago as it is now in Nuxt.js. It still needs hours of debugging / figuring out / is not robust, reliable or flexible. It's such a pain that this is the main reason I hear for ruling nuxt out of a project. In the end, this is a big show of lack of maturity....

And this is too bad because Nuxt deserves love for so many other reasons !

@Atinux @pi0 @JoaoPedroAS51 I'm only suggesting here, but IMHO, it'd deserve much much more attention from Nuxt core team. This might seem like a nice2have module for Nuxt, but it's as much a complex subject for beginners/the community as it is a VERY VERY basic need for most project.

Also, with the insanely growing usage of GraphQL, some synergy with apollo-module would make sense

Dear @syffs indeed auth module deserved much more attention in the past and specially @JoaoPedroAS51 helped a LOT for upcoming v5. Unfortunately still majority of code-base is legacy and accepting new PRs based open usually made more new regressions.

Anyway i apology on behalf of nuxt team we couldn't allocate enough time so far and that certainly needs improvements. (and locking issue since it is known issue)

Was this page helpful?
0 / 5 - 0 ratings