Devise API Authentication With Vue JS | Ruby on Rails 7 Tutorial
Vložit
- čas přidán 19. 05. 2024
- This Ruby on Rails 7 tutorial will teach you how to create a Devise API and login to it from JavaScript using a Vue JS frontend with a Vuex store. Because a Devise API Authentication guide alone would take 20 minutes, and the Vue JS project would take another 60, I've heavily edited this video to make it more digestible.
If needed, please pause and use the timestamps to jump around.
Join this channel to help support these videos:
/ @deanin
Repository for this video:
github.com/Deanout/devise-vue...
Styles used in session manager gist:
gist.github.com/Deanout/f5199...
Enable Session Storage Rails 7:
api.rubyonrails.org/v6.0.3.3/...
Timestamps
0:00 Devise API With Vue JS Demo
0:22 Creating the Devise API
1:30 Devise JWT Tutorial
3:30 Devise API JWT Controllers for Sessions and Registrations
7:53 Devise JWT Secret Key
8:48 Routing for Devise API
9:53 Configure Session Store in Rails 7
11:23 Vue JS User Login Application
12:20 Vuex Store for User Login
19:37 Devise API and Vue JS Stay Logged in on Refresh with JWT
21:05 Vue JS User Account Session Manager Component
27:35 Fixing Mutations using Payload instead of Data
27:51 Putting it all together.
Follow me on social media:
linktr.ee/deanin
If you liked this video, please consider subscribing: t.co/RZ4EwP0F2a
devise jwt rails api
#Deanin #Software #Programming
Edit: Looks like there was an issue with the members controller. def get_user_from_api_token should have been def get_user_from_token.
github.com/Deanout/devise-vue-api/issues/1
It's finally here. This was a monstrosity to learn how to do, please share it with everyone it might help. If you want a React JS version, leave a comment so I know there's demand please. :)
If you have any questions, I'll try to address them as they come up. I know first hand how much of a headache this is to understand. 😅
I hope this helps!
Hey man, nice tutorial, but how can I update user information with this app?
Is there a react version?
Good tutorial, very clear. I'd like to see the subsequent turtorial for the next React components you suggested at the end
Thank you. This finally helped get Devise and Devise JWT working with a regular app AND an api for a mobile app.
This is super useful content. Please keep these coming
You've just earned a sub. Finally a video that actually helps with Devise authentication. Thanks man
This is amazing! Flawless tutorial!
Thank you!
I had some issues with DELETE(sign_out) and I fixed that by making this change
log_out_success && return if !current_user -> I added a bang in front of current user method to negate it to true.
In general, this was a great tutorial as it was easy to pick up Devise concepts pretty quickly. Highly recommend!
Hi
Thanks for the blog!!!
I was thinking, instead of Postman - which you said was cumbersome for this tutorial - you could use tests instead. Tests allow you to send requests to your endpoint. Since it's all internal, you don't have to configure anything. Also, you can leverage Rail's internal hash-to-json conversion to write easier tests.
If you go the test route though, remember to add `as: :json` to your requests; else you'd have to include ActionController::Flash to your application controller - or some common root for all your Devise controllers.
Happy coding!
That's a really good idea.
And thanks for pointing out the as: :json, there's a good chance I would have wasted hours figuring that out haha.
Thank you,you are perfect teacher!!!!
Hello sir, thank you for this video. i'd like to ask why is it needed to singularize the naming for the JWTDenyList?
I gave this a thumbs up because after many hours of headache it got me to where I neeeded to go using React/Redux on the front end, but I wish you would explain more. A lot of the times you're just reading the code "Here we're gonna pass in the continuumTransfunctioner in as an argument and then deconstruct the mariachiBandInitializer". That sounds great, but it doesnt mean anything. What do the continuumTransfunctioner and the mariachiBandInitializer actually do?
Great tut! Is it a best/common practice to do this deny list approach to invalidate tokens? My (naive) understanding of JWTs is that they are supposed to be stateless so you don't store them on the server. By storing a deny list on the server, you are now creating state on the server and just inverted the concern of how state is stored (logged in state vs logged out state).
Hi thanks , that was very helpful, but i think this line is missing: in devise initializers, config.navigational_formats = [:json], without that when it have an unauthorised error, it redirects to the /users/sign_in route
thanks for the video, do you consider creating a rails 7 tutorial? I've not seen many around!
Yeah I've been gradually covering topics in Rails 7. If there's anything in particular you'd like to see feel free to suggest it and I'll add it to my list. 🙂
Hi boss 🎉!. Suppose i wanted to store the current cart_id such that a user can add products to that same cart. How can i generate a token with the cart id and hiw how to get that id such that i can set it in other controllers..
Hello thanks for the tutorial, can you do the same with react instead of vue?
Do you have a similar tutorial but with React as the FE?
Hi Deanin thanks for making this tutorial. I have some questions.
Is this going to leave us with API authetication option only while using Devise? What if we want to have authentication for both the API and the normal HTML requests? Is that not possible using this approach? What changes do we need to do for that?
I'm actually not sure, since I created the app in API only mode. I can take a look at using both JWT and the regular login setup later. If I figure out how to make it work, I'll let you know 🙂
Understandable, I get lost a lot myself making these videos. It's always hard to cover topics that touch on two entirely different tools like Vue and Rails haha.
Still trying to figure out the best way to break down these topics without spending an hour in a single JS file explaining what I can only describe as magic lol.
Hi dude. First of all, thank you for this video. After the back-end authentication step, would it really be different to implement a front end in React? I need as part of a training project to create a back-end in Ruby and a front in React. A kind of blog where an authenticated user can access articles, create them...
I absolutely have to go through devise-jwt to validate my project. Thanks and big up !
Nah, it should be pretty much the same. It's pretty much drag and drop replace with React from the point where Rails sends and receives data I think.
Great video,
I wanted to add additional things to the user login, such as "email, password, city". where do I change that in the rails section?
would there be any difference to the code if I chose postgres instead of sqlite?
Thank you for the video! I just have a question when I try to sign_out using thunder cloud(like postman) I always get the log_out_failure instead of the log_out_success. I am trying to use it for my reactjs app instead of vuejs
but the token is added to the denylist
having the same issue
thx😀
Sweet! Ever thought about making a video on React + Redux + Rails?
Yup, that's actually one of the next ones I've been working on haha.
Hello, may I ask what and wher is the payload coming from?
Hey man, nice tutorial, but how can I update user information with this app?
Hi Deanin can you make one video with a full operational calendar like fullcalendar, or something like that
I'll take a look at fullcalendar and see what I can do. Consider it added to "The List" 😅
@@Deanin thaanks ❤
One thing I didn't get though is why you had to rename the jwt_denylists table to jwt_denylist
How do you sign in
Is there a way to display the messages sent by the rails controllers?
Yes, you can store a state name errors or something and check if the response are containing that error object if it's just loop through the array and render the error page or you can do a better methodology , it's to go to your controller and specific the status of the error response to 401 and in the actions check if the response code is 401 push that errros to the state, you can be more creative
Hello! Awesome tutorial!
I was able to follow most of it. However, in order to log out successfully I need to refresh the page otherwise I get this server error:
Started DELETE "/users/sign_out" for ::1 at 2022-07-17 19:32:26 -0400
Processing by Users::SessionsController#destroy as HTML
Filter chain halted as :verify_signed_out_user rendered or redirected
Completed 401 Unauthorized in 1ms (Views: 0.3ms | ActiveRecord: 0.0ms | Allocations: 342)
Any idea why? I'm assuming it's because it's not able to get the cookie/JWT. But I'm at a loss for troubleshooting.
(and I checked in multiple browsers so it's a consistent problem)
Hi @NikaCodes I had this issue as well. It was driving me mad but it started working for me when I renamed the headers for the logout call from 'authorization' to 'Authorization'. If you copied the code exactly then its line 59 in session_manager.js. Hope this helps
Hi, i don't think it is a good idea enabling sessions on api-only applications
The rails-api application comer withs session disabled.
The warden auth requires a session to store.
U could simple tell devise.rb to not store sessions
config.warden do |manager|
manager.scope_defaults :user, store: false
end
Also enabling sessions would provoke a bug in devise retrieving the last user_logged_in besides the authenticated token user.
EDITOR=nano is not recognized on my pc. Please help me resolve this.
If you're using VS code, you can try:
EDITOR="code --wait"
Instead. Then just save and close the file, and the console should update afterwards.
You can basically replace the NANO with any editor on your machine that allows you to use a console command to open it I think. Stuff like Vim also works if you have it.
@@Deanin thanks for your quick response! That is not recognized neither
@@Deanin is there any other way to get to it?
Are you on windows? If so, you could try notepad?
EDITOR=notepad rails credentials:edit
If that doesn't work then I'm not sure. You'd have to search up and install an editor like visual studio code, add it to your system path (which might happen during installation, just restart your terminal/console before trying the command) and then try the editor="code --wait" command again
#
Looking into it, will reply when I figure out what's up. I know that Devise and turbo don't play well together, but I don't remember what I did in this video lol.
So flash is a message that is created in the parent controller from devise:
github.com/heartcombo/devise/blob/main/app/controllers/devise_controller.rb
@@Deanin Very very thanks for your support. Your classes are great. Keep helping us jedi master. Congratulations.
@Edcel Estadola Did you get ?
It can be resolved by just setting navigational formats to empty in the generated devise.rb file in a case of an api only app. config.navigational_formats = []
Hi.
Thank you for all your effort doing all these series.
I have a strange issue.
I cannot import on the SessionManager.vue file the line
import '@store/index.js';
when i run the command npm run serve i get the following error:
ERROR Failed to compile with 1 error
This dependency was not found:
* @store/index.js in ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/vue-loader-v16/dist??ref--1-1!./src/components/SessionManager.vue?vue&type=script&lang=js
To install it, you can run: npm install --save @store/index.js
Error from chokidar (C:\): Error: EBUSY: resource busy or locked, lstat 'C:\DumpStack.log.tmp'
then i run the following command:
npm install --save @store/index.js
and i get this:
npm ERR! code E404
npm ERR! 404 Not Found - GET registry.npmjs.org/@store%2findex.js - Not found
npm ERR! 404
npm ERR! 404 '@store/index.js@*' is not in this registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
Any idea about that?
When i comment that line that i am importing, the server runs but does not do any calls in the rails backend.
Thank you in advance.
It looks like you have "@store/index.js"
Maybe try this with a slash after the @ and see if it works?
import "@/store/index.js";
@@Deanin Thank you !
Hi @Deanin I could use your help:
I keep getting a Can't verify CSRF token.
Changed the devise.rb from
jwt.secret = Rails.application.credentials.devise[:jwt_secret_key]
to
jwt.secret = Rails.application.credentials.devise(:jwt_secret_key)
Since it kept failing under another message:
devise.rb:19:in `[]': no implicit conversion of Symbol into Integer (TypeError)
Any idea on how to fix this?
Hi Deanin thanks for making this tutorial.but when I'm running the server `rails s` I'm getting this error message:
"undefined method `[]' for nil:NilClass (NoMethodError)
jwt.secret = Rails.application.credentials.devise[:jwt_secret_key]"
Is there someone who can help me?
Hi, try instead Rails.application.credentials.dig(:devise, :jwt_secret_key)
same issue but you just have to make sure you have the correct spacing when you create the secret key @8:31