#1: SPA Authentication using Laravel Sanctum Tutorial
HTML-код
- Опубликовано: 24 июл 2024
- In this Laravel Sanctum tutorial, you will learn how to build a SPA authentication system using Laravel Sanctum & Vue.js.
Laravel Sanctum provides a lightweight authentication system relying on Laravel's built-in cookie-based session authentication services.
In this Sanctum tutorial, we will create a complete register and login feature for a single page application in Vue.js and Laravel Sanctum. We will create separate projects for the frontend (in Vue.js), and for the backend (Laravel), that will interact with one another through a REST API.
𝐆𝐢𝐭𝐇𝐮𝐛 𝐑𝐞𝐩𝐨 𝐟𝐨𝐫 𝐋𝐚𝐫𝐚𝐯𝐞𝐥 𝐒𝐚𝐧𝐜𝐭𝐮𝐦 𝐄𝐱𝐚𝐦𝐩𝐥𝐞
github.com/qirolab/laravel-sa...
#2: API Token Authentication using Laravel Sanctum
• #2: API Token Authenti...
𝐋𝐚𝐫𝐚𝐯𝐞𝐥 𝟕 𝐑𝐞𝐥𝐞𝐚𝐬𝐞 𝐍𝐨𝐭𝐞𝐬
laravel.com/docs/7.x/releases
𝐒𝐦𝐚𝐫𝐭 𝐰𝐚𝐲 𝐭𝐨 𝐮𝐬𝐞 𝐀𝐏𝐈
• #8 - Smart way to use ...
𝐕𝐮𝐞.𝐣𝐬 𝐋𝐢𝐟𝐞𝐜𝐲𝐜𝐥𝐞 𝐇𝐨𝐨𝐤𝐬
• #10 - Vue.js Lifecycle...
𝐕𝐮𝐞.𝐣𝐬 𝐄𝐯𝐞𝐧𝐭 𝐁𝐮𝐬
• #8 - Event Bus & Commu...
#𝟏 - 𝐋𝐚𝐫𝐚𝐯𝐞𝐥 𝐏𝐚𝐬𝐬𝐩𝐨𝐫𝐭 𝐎𝐀𝐮𝐭𝐡𝟐 𝐒𝐞𝐫𝐯𝐞𝐫 𝐈𝐦𝐩𝐥𝐞𝐦𝐞𝐧𝐭𝐚𝐭𝐢𝐨𝐧
• #1 - Laravel Passport ...
#𝟐 - 𝐓𝐨𝐤𝐞𝐧 𝐒𝐜𝐨𝐩𝐞𝐬 𝐢𝐧 𝐋𝐚𝐫𝐚𝐯𝐞𝐥 𝐏𝐚𝐬𝐬𝐩𝐨𝐫𝐭 𝐎𝐀𝐮𝐭𝐡𝟐
• #2 - Token Scopes in L...
#𝟑 - 𝐑𝐞𝐟𝐫𝐞𝐬𝐡 𝐭𝐨𝐤𝐞𝐧𝐬 𝐢𝐧 𝐋𝐚𝐫𝐚𝐯𝐞𝐥 𝐏𝐚𝐬𝐬𝐩𝐨𝐫𝐭 𝐎𝐀𝐮𝐭𝐡𝟐
• #3 - Refresh tokens in...
𝐖𝐡𝐚𝐭'𝐬 𝐧𝐞𝐰 𝐢𝐧 𝐋𝐚𝐫𝐚𝐯𝐞𝐥 𝟕?
🔗 • What's new in Laravel 7?
Support my work:
1. On BuyMeACoffee: www.buymeacoffee.com/qirolab
2. On Patreon: / qirolab
#Laravel, #Laravel7, #Sanctum
Also, follow us on:
𝐅𝐚𝐜𝐞𝐛𝐨𝐨𝐤: qirolab
𝐓𝐰𝐢𝐭𝐭𝐞𝐫: / qirolab Наука
Support my work:
1. On BuyMeACoffee: www.buymeacoffee.com/qirolab
2. On Patreon: www.patreon.com/qirolab
this is exactly the tutorial I need because I really want to try to separate the front end from the back end and now it's crystal clear to me, thank you so much for making this!
Glad it was helpful!
This tutorial is super helpful. Thank you for saving me days of research you're a hero!
Glad it helped!
This is the ultimate solution of Laravel Sanctum SPA authentication..
Glad you like it!
Great tutorial. Explained very nicely for a beginner like me. Thank you.
Awesome tutorial man, and you are very knowledgeable.
Glad it was helpful!
Thank you for this great tutorial, helped me set up my project.
I have a few suggestions though....
As far as I can tell, you are not required to request the CSRF cookie before every request.
Only on fresh request, which logically would be (where the user has not been authenticated beforehand)
1. Register New User.
2. Login User.
3. Password reset request
4. The Password reset page that would open from the link received in the forgot password email.
Other than that, it's not required. As the CSRF cookie will be saved in the browser, and Axios will send it along with every request.
I am able to hit the /user, /logout without hitting the CSRF cookie.
Also, I believe that a better way to store Authentication information would be vuex store.
It is not the most secure way, but still better than local storage, as the local storage value can be changed very easily, whereas the vuex values are hard to change and require some amount of skill.
Also, vuex state updates every time we refresh.
As a fail-safe, just ask for the /user from the API every time you need to do something sensitive.
Hope this helps someone. :)
Spot On Tutorial. Thanks Heaps
Awesome tutorial 😍 Make full sense of Laravel Sanctum✔
I am not still figuring it out
Very Good... You have put all resources together in one place and made others work easier... Well Done... Claps...
Thanks a lot 😊
This is exactly what I was looking for. Trying to do the same using Laravel 9 with Sanctum as backend and Svelte on the front.
Thanks for clarifying as simple as posible
Glad to hear that!
Thank you. I have a question (maybe i don't understand all), how do you refresh the expiration of user's cookie if the guy is active in Front-end app? For example, we have 10 minutes of expiration for the cookie, how the cookie is refresh when user interacts with the API to still have access on protected routes?
very good good good good tutorial. Thanks, QiroLab. Subscribed!
Thanks for the sub!
What about if the user goes to developers tools, and manually create a localstorage "auth: true"? its show dashboard component anyway...
Fantastic tutorial Ever. I hope in future you publish the project basis tutorial-like E-commerce with a blog or more advance. Thank you so much and waiting for your next exclusive something new
This video is really help me a lot, I have one question
you had set xsrftoken and laravellsession in the cookie, why did you set it on local storage as well? can you help me, I'm little bit confusing about it. Thanks in advance
Thank you... I've been working on this problem for over a week now. Solved it in 2 hours with your vid / repo... I'm wondering if you could comment on how to implement a ForgotPasswordController that works with the SPA / sanctum?
thanks for this tuto , please I have some issues , I have a laravel api that i want consume it in separated frontend and also in mobile app . so should I use just spa auth with sanctum or I need api tokens also ?
Thank you for making this video!
My pleasure!
Hey, Brother, I love to see your tutorials, because you explain everything in detail, can you plz make series on any kind of project with nuxt and laravel plz...
Thank you.
Sure, I will create tutorials on Nuxt and Laravel as well.
@@QiroLab Thank you brother, it'll help many people like me....
@@shekhsaifuddin1353 why am I getting html content instead of json data?
@@QiroLab I'm waiting for it. too
I'm new to this, why do you actually need to make a request to /crsf-cookie by registering? And do you need to make a request to that laravel url everytime a user goes to a vue page with restricted access, so that it can check if a cookie token is set in the backend?
as you said on 05:40 how to work with different urls? For example: I have a backend code hosted in someother url and the vue is hosted in other url. How to work on this?
This is an excellent tutorial. I've watched a lot of tutorials. I did not enjoy them.
This tutorial is good because author is explaining every step. He first shows raw version and only then abstracts the complexity.
Most courses go straight abstracted way and everything works like magic but you don't see how that works under the hood which is important when you are learning.
Glad you enjoyed it!
how do you implement the same laravel sanctum authentication but with vuex and not event bus on refreshind the nav links?
Where are the "user" or any other model defines in nuxt? (In this vue video says -> src/apis/User.js)?
What is the "best practice" for this?
Can somebody to help me?
Nice, I want to know one thing, that can we create multiple authentications using laravel sanctum and vuejs like Admin, Seller and front user having different tables for admin, seller and users and having different views.
When checking the requests using Insomnia I get a 405 error: Method not allowed when my login credentials are wrong. However when I input correct credentials it returns me with code 200 for both registration and login.
Can i use laravel jetstream default functions in api call ? like regiter, login and others ?
You are the best. So thanks you for all you done for me 🤩🤩
Thank you so much 😀
Great video bro, very helpful
Glad to hear it!
in which folder is the admin panel created? in client project or inside laravel project?
401 /api/user
Fix:
SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8080
(Vue on 8080)
thanks bro, it solved my problem
Thanks man!
These change not fixed for me.
Thanks!!
work bruh big thanks
Hey bro, I always get this type of error {"message":"Unauthenticated."} after successfully login... now how can i fix that???
You are doing great job bro, I replicate the code but it's sending two requests of register and get cookie method when i check console , can you identity the issue?
Nice 👍
how can The Api just can access only our android studio porject
Thank you so much!
You're welcome!
Thanks , very useful
Glad it was helpful!
how to write "public function ..name of method... () {} " autocomplete like u do?
Hi, do you know why i don't have csrf error. When I register a user, I can do so without the csrf route
same here
the best ever
It's the best tutorial
Glad to hear that!
Hello, I have followed your tutorial and almost set up on my local too. But I got a error because I am using laravel 8 and vue 3 and bootstrap 5. I manage to fix other error except one - which is as below on console.
Uncaught TypeError: this.$root.$on is not a function
on Navigation.vue because $on is removed on vue 3 here
mounted() {
this.$root.$on("login", () => {
this.isLoggedIn = true;
});
and another warning on console is
[Vue warn]: Unhandled error during execution of mounted hook
at
at
I hope you will help me out.
regards.
thanks sir nice tutorial
Most welcome
Great video it respond to my issue the only issue is that my front is in Angular and it used HttpClientModule. where can i create the Csrf.getCookie() function so i can apply it to my register and login
i've just installed a fresh vue vite app and user.js full of errors nah
I don't understand how to handle sanctum with vue directly in the laravel project.
I mean, how to make myapp/admin, protect routes inside and then redirect and manage the whole thing in vue-router
use Nuxt :D
Csrf and login is working. But when I am trying to get user from
Http://localhost:8000/api/app/user
It is giving CORS error in console.
I have set true in cors.php file as you said.
I have also the same problem
Will there be a problem if I have the Laravel app with Laragon on a virtual host like 'myapp.test' and my Nuxt app running on LocalHost as they are not in the same domain ?
Yes, it will not work. Both domains must be the same.
@@QiroLab so how can i set a vhost for Nuxt app?
amazing bruhh am from indonesian
thank u for sharing ure knowladge bruhh
Glad you liked it!
All the tutorial is awesome.Although we can by bypass auth by adding our own localstorage auth:true. What is your method of protecting for it.. Answer would be helpful . How you solve this kind of problem in real world project.
maybe i am wrong, but the getCookie() call should only be called once? the docs say: This token should then be passed in an X-XSRF-TOKEN header on subsequent requests, which libraries like Axios and the Angular HttpClient will do automatically for you.
Yes, you are right, we don't need to call `getCookie()` every-time. I have already explained it in this video. Watch it from 49:42
I get permanent error 401 everytime I try to access /api/user.
csrf - OK, login - OK, user - error. :(
Same problem :X
i got same problem but i think every thing is ok... now how can i fix it???
the problem was in the configuration of the virtualhost (Windows -> C:\Windows\System32\drivers\etc\hosts).
I commented out the lines (#) below "localhost name resolution" and "dns localhost"
Hello, thanks for this excellent tutorial. I have a permanent error 419 on register, the csrf doesn't return me error. I'm at point of minute 22:00 of the video. Thanks in advance!
Sorry, I found the issue, I declared baseURL as 127.0.0.1:8000/api instead localhost:8000/api. It's working now!
I'm stuck in the same place, changed the URL to localhost and still getting error 419
Hello, ty for tutorial, but why api/user response 401?
i am also have this issue, did u find out why
did you solve this problem? I have him too
My problem in cors (i use apache lara, and nginx vue cli)
CAN SOMEONE HELP ME?!!! :'CC why I haven't the 419 error? my project works without '/sanctum/csrf-cookie' config?
I have same problem. but solution to this problem is in this video comment by oher people. try to find
I resolved it, I was configurating my domain and sub domaion wrong, thank you bro!
when i implement the register function without getting the csrf cookies I'm not getting the 419 error, i get the 422 error straight away. I can also register a user without getting the cookies. How do i fix this?
SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8080
Also check the gitHun Repo ... its looks like he has done some changes that are not shown on int he video
@@Cybersix6666 wao bro
I always follow your great tutorial videos. I learned laravel sanctum from these video series. I developing a project with laravel sanctum but when I Deploy my project on sub domain. I am getting 401 error. Can you please make a video on laravel sanctum project deploy on live server
Did you make a mobile token based version yet?
There is a bug. If the cookie expires the app is still "logged in" but gets an 401 error. How to solve this. Maybe there is a better way without using the localstorage and check the validity of the cookie.
when you get 401 error, clear the localstorage and rediect to login page.
🔥 🔥 🔥
do we need to run php artisan make:auth ?
In this example, we are working with SPA application. So, we don't need to run `php artisan make:auth` command.
why dont we use both laravel and vue on the same app? using laravel/ui? Why do we have to make them separate?
If they are in the same app you can use Laravel's built in session auth and you don't need Sanctum.
it's all about preference and project requirements. Some developers like separate app some like in same app. So, its all on you.
@@QiroLab Thank you for replying.
First of all nice tutorial really helpfull. But Why do i get CORS errors? Everything should be set in cors.php also configs.
spa app: localhost:8080, laravel app just: localhost
Did you get a solution to this?
It's a great video. but I have faced a problem where login successfully but after fetching user information it's showing Unauthenticated where the user logged in. Is there any suggestions for me ?
I think you should watch the video again. That is also explained in the video.
@@QiroLab Thanks for the reply. I have tried many times and also clone the GitHub repo but the result is the same. after login user information showing Unauthenticated on the response. I don't know it's laravel version-related problem or not I am using Laravel 7.x now. Before 10 months it works for me now it makes the issue
please remake sanctum tutorial spa auth with vuex+Authentication from laravel.
8:10 - your prononciation of "middleware" always cracks me up
Even cleaner way of handling csrf cookie reqests is using axios interceptor.
I don't understand why putting auth state in the localstorage. A user can easily change this value to true?
Isn't there any smarter way to do this?
Please make laravel sanctum multi auth tutorial using vuetify
Is it required to get csrf-cookie before each request to API?
Except `get` request. I mean, if your sending post, patch, put or delete request then it is required to get `csrf-cookie` first.
@@QiroLab why? old token is wrong?
with sending POST you receive a new XSRF-TOKEN and it's still valid, so why send request for new?
@@alexios4392 Here I mean, XSRF-TOKEN is required for post, patch, put or delete request but for `get` request it is not required. If the browser has already valid XSRF-TOKEN cookie then you don't need to get `csrf-cookie` from API. Watch from 47:50
csrf - OK, login - OK, user - error. :(
/api/user 401
Be inspired!
I will wait another tutorial like this when its using Lumen.
and dont forget to include all grant type tutorial.. :v
Make React+Laravel Sanctum Authentication. Please
Sir can you continue this sanctum tutorial with crud function, with user password Reset fuction
Glad you liked Laravel Sanctum tutorials. There is nothing new for CRUD or the user password Reset feature with Sanctum. Just use the regular way of creating CRUD and password reset features and use it with Sanctum as shown in the tutorial. It will work fine. I think there is no need for another tutorial for that.
@@QiroLab I am new in Vue and laravel sir your teaching mathod is unique. It's easy to understand ❤️ . I never seen any other RUclips channel explaing like this.
Your video tutorials are super ❤️. So if possible to make video on crud function . It Will better for new Lerner like me thank you.
Very helpful. However I think this package isn't as simple as they make it seem.
Am stuck at 19.51 seconds app.js:
GET 127.0.0.1:8000/api/csrf-cookie 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (app.js:826)
at settle (app.js:1087)
at XMLHttpRequest.handleLoad (app.js:295)
it shows html content
I think, that is because you may have forget to add configuration 'prefix' => 'api' in the sanctum config file. Watch from 18:15
@@QiroLab I have modified it inside Service
And btw I have a question which has consumed my last 2 days before i saw your video
Why is it that instead of returning json data as expected,my console prints html content? it really sucks.The first login attempt works well but the subsequent ones print html contents in my browser instead of json response
I'm gonna ask you about your editor font :)
It is 'Droid Sans Mono', 'monospace', monospace, 'Droid Sans Fallback'
/api/user 401 after successful logging and and cookies set
i have problem like you .
did you solve this problem? I have him too :(
@@paulorcaldera I can't Fix.
i got a same problem please anyone help me..
the problem was in the configuration of the virtualhost (Windows -> C:\Windows\System32\drivers\etc\hosts).
I commented out the lines (#) below "localhost name resolution" and "dns localhost"
oh Man please make authentication with email verification and forgot password email verification.
For that you can use the built of inbuilt feature of Laravel, it will work the same. Watch this video of email verification: ruclips.net/video/dbmox3tgI2k/видео.html
Can't understand a word he is saying.
Hello. Good video, but I have some comments.
1. Instead of "Api.defaults.withCredentials = true" can put the "withCredentials" into the axios create method:
let Api = axios.create({
baseURL: 'api/',
withCredentials: true
})
2. Why do you call the "Csrf.getCookie" in the register? (and later from everywhere!?) Much better to put this into the Api.js right after the "create" method. In the request interceptor. It runs before your request reaches the server:
import Cookies from 'js-cookie'
const Api = axios.create({
baseURL: 'api/',
withCredentials: true
})
const onRequest = (config) => {
// If the XSRF-TOKEN cookie is not present, call 'csrf-cookie' (only when you use "post", "get", or "put"...)
if ((config.method === 'post' || config.method === 'put' || config.method === 'delete') && !Cookies.get('XSRF-TOKEN')) {
return setCSRFToken()
.then(response => config)
}
return config
}
const setCSRFToken = () => {
return Api.get('csrf-cookie')
}
Api.interceptors.request.use(onRequest, null)