Introduction
Nuxt.js is a nice framework for creating both SSR and SPA apps easily in vue. It is easy to use, but sometimes there are so...
For further actions, you may consider blocking this person and/or reporting abuse
Nuxtjs auth module dev community developed a refresh scheme for local strategy and it will be available in @nuxtjs/auth V5, but if you want to use it in the meantime, use the @nuxtjs/auth-next :
dev.auth.nuxtjs.org/schemes/refres...
Awesome! When it will be released I will update the post. I hope my post served it's purpose well for more than 6 months, until it is no longer needed. I am not using JWT tokens anymore, but happy to see they got it built-in finally! No more workarounds! Thank you for telling.
For anybody here using django-simpleJWT and having trouble with the Refresh token. I'd like to share my solution by modifying lines
and make sure have the following settings in Django
@mrnaif2018 thanks a lot for this tutorial. It saved me a lot of time. @jjspscl Hi, thanks for the update on using django-simpleJWT (that's what my project uses) I've been trying to register a new user but I've been getting a 403 forbidden error on my register endpoint, meanwhile my login works fine. Any idea what could be wrong?
Seems of out topic, it would be best if you'd Chat me
Okay please follow back so I can access you via dm ๐๐ฟ thanks
Thanks for sharing that! I was using my custom JWT implementation so responses differ a little bit of course!
Greetings, it was a very useful post for me, first of all thank you :)
There is a problem for me. While browsing my portfolio website, it always puts me on the login page. I just want the authentication processes to work only when I enter the login page (for admin panel and post some staff. router path is
/panel
). how can i achieve this?With my setup, all pages are by default for authorized users only, with small exception. Use auth: false(disable at all) or auth: "guest"(viewable for only non-authorized users) on your pages which don't require auth(i.e. in export default block, like
export default {
auth: false,
....
}
Or, if all your pages by default don't require auth, you might want to change global auth middleware behaviour then by removing it at all from nuxt.config.js, and enabling only on individual pages, see:
auth.nuxtjs.org/guide/middleware.html
It has been a while since I read the documentation, I forgot this detail. Thank you very much.
I have observed something that I do not understand.
$auth
works very well while browsing the application and clicking on the router links. But when I try to enter a valid URL for$auth
in the browser url part, the same page opens without authentication, the application does not recognize$auth
at this stage.For example: Authentication is requested when I click on the toolbar 'Panel Button' and '/login' page comes up. but if I write the same url (/panel) from the browser and enter it, it does not ask authentication, it enters '/panel' route directly.)
Hmm, are you sure you have enabled auth middleware on that page?
Could you send a minimal snippet(repl.it, codesandbox, github/github gist or other sharing services) to reproduce that? I can look what is wrong.
Maybe try using built-in middleware and not the one from that post. In my situation it displays the page for a sec, and redirects to login page on client side. Probably custom middleware isn't needed anymore, I can't tell for sure as I am migrating to API tokens(randomly generated) with OAuth requests support and token revoking instead of JWT, it actually solved a loot of problems I had.
I tried the built-in middleware; it works smoothly in this scenario. I use
django-rest-framework-simplejwt
as the JSON Web Token authentication. We are probably using the same infrastructure.Yeah, same for now, at least both APIs are in python (;
But I am migrating from JWT for good, will write an article why, at least for now it seems better.
Hey!
Thanks for the great post. I cant get the $auth instance from the destruction of the app object in the auth.js plugin tho.
//auth.js
export default async function ({ app }) {
const { $axios, $auth } = app <------- $auth is not avaialbe i.e undefined
I dont really understand what I should do to get it avabile in the plugin.
Its availabe in the App it self.
Also $axios (and for med $vueitfy) is instantiated and avaialbe.
Thanks for any tips! :)
/J
To get $auth instance on your app, your plugin should be specified as nuxt auth plugin, not normal nuxt plugin.
Recheck your nuxt.config.js file, I'll be glad to help!
Yes that was it! Thanks!
For anybody wondering where the " self. " comes from in the login component (and getting error messages about it not being defined), above the post request there should be:
const self = this
Basically it is used to access " this " inside the promise.
(not sure how clean this is, though)
Yes, exactly. It was mentioned a line above in my full code, missed it (:
Anyone who visits the full repo can see the full code (:
Thank you for noticing this! I updated the gist and the post to use
this
instead, as(if I understand it correctly), when using arrow functions for.then
callbackthis
is not lost.I think its at least, a very dangerous practice to expose an enpoind that returns valid tokens. That kind of strategie dont looks very production ready, as you my bee wanted. You should concider adicional stuff like you might find at owasp.org
Sorry? Please, if you don't like the way it is implemented, suggest you own way. This post is mostly about how to make it working at least, backend structure is not discussed here, just one of possible cases is shown. "Additional" stuff can be anything. Endpoint returning valid token is bad? Then how could application get appropriate tokens to access protected endpoints? Why is it dangerous? There is no other way for code to get tokens without requesting them. Please, if you tell that something is "bad", explain why. Owasp.org has some documents on web applications, but it doesn't tell anything about returning tokens from endpoint.
Official guide on implementing JWT in Nuxt is here github.com/nuxt/docs/blob/master/e...
Good guide,I saw that, but this article is not about implementing JWT which is indeed easy and supported, but for implementing JWT refresh functionality. Thank you for the useful link!
Yes, sorry, your article is great, but I found it looking for a simple JWT implementation guide in Nuxt, so someone might have come with the same query.
Thanks for this great post. I implemented it in my application. I have one operation that invalidates the access_token on the server side. I'm trying around with renewing it using the refresh_token, however not really successful for now. Do you have an idea how to implement a check, if the access_token is still valid and if not to refresh it using the refresh_token?
Thank you!
You can see the
~/plugins/auth.js
file and functiondecodeToken
in it.So if token is still valid then you can do like
if (decodeToken(token).exp > 0)
// valid
Basically this piece of code in the plugin does exactly that(also found in
~/plugins/auth.js
file):if (refreshInterval < 0) {
refreshInterval = (await refreshTokenF($auth, $axios, token, refreshToken) * 1000 - Date.now()) * 0.75
$auth.fetchUserOnce()
}
Haven't really tried to implement this solution yet, but I wanted to thank you in advance! This is the exact problem I am currently facing with my nuxt/jwt project. My lack of experience in js / vue / nuxt made this impossible to solve on my own.
My ugly workaround was to set the jwt token to never expire on the backend, and hope the official support will come before I need to go to production. Relevant github issue, if you are interested - github.com/nuxt-community/auth-mod...
Yeah! That's why I have written it. It is so hard to set up just this auth, I spend a loot of time doing it, and I came to this solution after lots of experiments. That's why I share it, I want to save people's time, and, possibly, point nuxt devs to such an inconvenience.
P.S. I am no js expert as well, it's just "science touch method" :D
Hi MrNaif
I have a question I really need help with. I thought you would be the one able to help me as you created this amazing plugin.
When trying to access a page with auth middleware, everything works correctly. The problem is, though, that the application asynchronously loads and sees if the token is valid.
This causes 2 redirects that don't look very good for the user experience. How can I make it so that the token gets check SYNCHRONOUSLY and nothing is being shown on the page, and THEN perform redirects whenever the user is not authenticated?
Please see a GIF of the issue here:
i.imgur.com/ZSx5ByF.gif
(PS: Page not found notification is because I haven't defined the login route yet.)
Hello! I think that for the best UX redirects should be done server side, via a middleware. Maybe try adding a middleware which checks token, and redirects based on that. Also those redirects look a little bit like hydration issues, check if you have those.
Thanks for your reply!
Do you mind giving out your contact details? I don't really know what you mean.
There'll be a little reward too ^^
Sure, as long as it is something simple (:
Contact me in telegram(@MrNaif_bel)
Great Post. One issue.
middleware: ["loggedIn"] in nuxt.config not working for me :(
if i set middleware: ["auth"] in nuxt.config that working.
i want to all site rrquired authenticaion without login + signup page
Thank you! Strange that it didn't work as it is almost a full copy of auth middleware, but glad you got it resolved (:
In my setup there are login and signup pages, but it's up to you how to organize your site.
Thanks for quick reply :)
I don't understand why you use middleware: ["loggedIn"] :(
Can you please explain easyway. If you don't mind :)
Thanks
It was because of rehydration errors, not matching content on server and client side, and by enabling this middleware client side only it solved the issues.
if (!process.client) return;
is the only change. Not DRY, I know (:In near days I am going to hunt one more bug, will update the post after I fix that(axios dynamic base url not used, it requests local server and not the remote one).
Hello, thanks for this post, it helps me a lot.
Just a question: I need to pass a param to user url to get the user. I need to do something like that:
so how can I pass userId params to get the user?
Thanks
Hello! You should implement something like /users/me in your backend to just return current user. Unless you JWT token has user id in, it is impossible to fetch that endpoint as it fetches user data(with user id in it).
Awesome post!
Thank you! Should I also write a post about dynamic environment variables loading in nuxt?
Yes please!
Done! Enjoy!
How to load dynamical environment variables with Nuxt.js
MrNaif2018 ใป Dec 16 ใป 2 min read
Thanks for sharing this. I couldn't help but wonder isn't this solution much simpler? stackoverflow.com/a/53866447/12634779
Hi! It might be, but this solution makes tokens refresh a bit before access token expiration, which is useful sometimes. Plus middleware was needed because of bugs of @nuxt/auth on server side. They are releasing refresh token support soon, so soon all those solutions wouldn't be needed.
Dude you have no idea how long I've been trying to solve this as a frontend newbie.
Really appreciate sharing the code <3
Thanks! Together we solved it (:
thanks for the detailed post but can you also add how you would handle facebook google and twitter login with nuxt/auth
This is outside of the scope of this article. It shows how to workaround limitations and bugs about refresh token implementation in nuxt/auth.
Google auth, social providers auth are there:
auth.nuxtjs.org/providers/google.html
auth.nuxtjs.org/providers/facebook...
Etc.
Thank you for sharing :)
media.discordapp.net/attachments/4...
I am getting this error when writing the axios.js plugin. What should I do?
As I have written in the article, it is a dynamic environment variable, you can replace it with your setting, or implement environment variables loading as written in my another article:
How to load dynamical environment variables with Nuxt.js
MrNaif2018 ใป Dec 16 '19 ใป 2 min read
$auth.getRefreshToken(strategy) always return false to me, what am I doing wrong?
Hi! There are lots of possible causes.
Just a few guesses:
Might it be that vuex/something else that is required for nuxt auth is not enabled in your app?
Or maybe the backend returns false so it gets stored?
Or some other issue, try debugging the setRefreshToken calls, etc.
Hello @mrnaif2018 is there a way i could contact you ? gmail or fb, i need some help with nuxt.js auth.
Hi! I'm @MrNaif_bel on telegram. I might add that to the profile, it would be good if it was supported by dev.to natively.
Not only do you need to roll out your own refresh token mechanism. Handling 2FA authentication also needs some work...
When I get to implementing 2FA I think I will make a new post showing how to avoid some difficulties (:
how to create @nuxt/auth google can be validated with jwt in my server api
Hmm, sorry? Could you provide more context please? If it is related to google oauth, nuxt auth module has oauth provider built-in.
Nice!
Thank you! I usually don't write posts, but this is the thing you can't easily find on the internet (:
Hi. Thanks for your posting.
Could you share project that frontend is Nuxt.js and backend is Node.js?
I want to feel with Nuxt and Node through example project.
Thanks.