Example of Laravel Sanctum with API Tokens
Vložit
- čas přidán 5. 09. 2024
- I've written a blog article for our QuickAdminPanel, and also decided to shoot a broader demo-video for those who haven't used Laravel Sanctum with API Tokens.
Original article: blog.quickadmi...
Laravel Sanctum docs: laravel.com/do...
- - - - -
Try our Laravel QuickAdminPanel: bit.ly/quickad...
Enroll in my Laravel courses: laraveldaily.t...
It's really weird. Just yesterday I was looking for passport and sanctum, how to use it, and just general information (wanted to use vue components and have a few api endpoints, at the end decided to go with livewire :) ) about it, tried looking at your channel too. And today - wollia! You've got me a video :D Are you spying on my search history? :D Thanks for this video, good job as always.
I just shoot too many videos, and sometimes they happen to be on point with something some people are working on right now :)
And don't forget to add throttle in your auth routes. Sanctum doesn't add middleware out of the box like Fortify does.
Simple and Clear. Many Thanks.
Thanks for the videos and daily tips on this channel. Just started with Sanctum and this was useful. Has been a great help :)
Great explanation of complex concept
Great video
Very good video, explained in a very easy and understandable way.
Can we apply it in multiple authentication using guard. Suppose there are two models User and Customer. For the User, if auth:sanctum middleware is used, then what will be for the Customer?
Can't believe you covered that stuff into 5 minutes. Would you do an udemy laravel course, i would instantly buy it
I have a lot of courses, here: laraveldaily.teachable.com
@@LaravelDaily how can we have a Post_id in the user table And filter posts by logged in post id in a One to many relationship
Am using passport and I used the same methodology to return token when user login with even three credentials for my mobile apps (email, mobile number, National ID number) . It works perfectly. And I see nothing is changed. Better to keep my old code.
thank u you help me a lot!!
How would you store this token in the frontend in a secure way? With jwt you have two tokens with the refresh token stored in a cookie but with sanctum you only have one?
Simple, easy and well explained ;) thanks
But if i have multiple table like users, customers then if i want to login with customer table also then how to do it?
can we define those tokens revoking time?
like its only usable for x hours or so?
doesnt/didnt laravel provide a basic api_token mechanism since few years ago? works kind of the same and i have used that before, i wonder what the main diff is between that and this..
Hi .. mine doesn’t show any message like whether its authorized or not .. can you know whats the problem?
how can we display json resource collection response in blade file laravel?
Your Great Sir.
Hello, can you make video draggable laravel/vue to-do lists. I try to do, but for whatever reason doesn't work.
Thanks a lot very clear
Here in this code we have csrf issue how can we prevent that?
Can I use this method to convert my existing Laravel application routes and share them with the mobile developer? I need to create and share an API with a mobile developer. Or is there any other method for mobile API?
Thank You!
It is possible to display api data into blade
how to create persistent login?
How to add prefix in default /login & /register api in laravel sanctum ?
Ex. Default api are /login & /register
I want /api/login & /api/register
How to achieve this?
Also in /user api i am getting many fields like id,name,email,created_date
I just want name and email id
How to do that?
is ok to store the token in localstorage??????
can i use spati role permission using sanctum api token?
Can I auth multiple auth with Sanctum
Hi Povilas, do you have a quick guide to show differences in the files generated by QuickAdminPanel now (for Sanctum) versus previously (for Passport)? I am working on something I generated initially using the Vuejs generator and I'd like to transition it to Sanctum and follow your examples. Also, how do you recommend storing the token on the frontend for a Vue SPA - is local storage ok?
This video is not about Vuejs generator version, that generator works like SPA with Sanctum now. Please check this help page: helpdocs.quickadminpanel.com/vue.js-generator-version/installing-downloaded-vue-panel
There are actually no files changed between Passport and Sanctum: only composer remove passport, composer install sanctum, then middleware changed from auth:api to auth:sanctum and you need to configure Sanctum domains. Should be it.
Awesome 👍
Sir, Isn't there any easy way to avoid sending authorization Bearer Token from the frontend everytimes ? Can't we set the Default Authorization after login from the Controller ?
That's the whole point of authorization from mobile, there's no way to have session active between mobile and server, without token every time, you may have a security issue.
@@LaravelDaily Thanks, Still i have one more question about security issues that, we are returning just created token from the backend and storing inside localstorage of the browser. Is it best practice ! Or we should encrypt at the backend and after encryption we should return the token . Also decrypt first before doing any process of the token. ?
thanks !
what life time of this token?
there is a difference with the laravel passport?
Yes. Laravel Passport uses OAuth. Read more here: blog.quickadminpanel.com/new-api-generator-2019-now-with-laravel-passport/
there is any way to create token by sanctum with different guards ??
Do you really need guards? Or do you need roles and permissions, then you do the auth with general sanctum, and add a role or permissions for that authenticated user
yes i need guards .... in my project there is 2 guards for different type of users they share the same DB , but different app
i think i should use guards in this case , or i should use roles and permissions i'am really confused
@@motazhesham2488 can't answer that in youtube comment, please read documentation for Sanctum and Authorization and Guards
@@motazhesham2488 you could use Spatie for user roles + Laravel Auth for login scaffolding + Sanctum for issuing tokens. Although you might need to modify the code a bit.
How to make multi guard api application for admin and user separate table, separate login
Same logic, with API or non-API: czcams.com/video/kZOgH3-0Bko/video.html
Also, my example with Vue: czcams.com/video/JatpAUl6_5E/video.html
Auth::guard('admin-api')->attempt($cred) with driver passport or sanctum give error "the driver guard does not have attempt function". So how to solve it. Passport accestoken issued for admin is accessible in user vice versa. Please make a tutorial on it. I already have watch you policy and gate many times, but couldn't conclude
Please make a video on multi-auth api with passport or sanctum with different tables of user, admin, vendors
I don't advise to store them in different tables, and don't advice to use Guards for that, so won't make a video on that. I advise to use roles/permissions instead.
I have even submitted that to the official Laravel docs:
"Guards and providers should not be confused with "roles" and "permissions". To learn more about authorizing user actions via permissions, please refer to the authorization documentation."
laravel.com/docs/8.x/authentication#introduction
How to list all personal tokens with the plainTextToken?
From the docs: laravel.com/docs/8.x/sanctum#issuing-api-tokens
foreach ($user->tokens as $token) {
//
}
@@PovilasKorop Thanks, but how I can get the plainTextToken to list it so user can copy and paste it?
@@mikro63tv94 well same answer, it's in auth()->user()->tokens you just take the first one. But I'm not sure if those tokens are supposed to be used for copy-pasting, please read the documentation of Sanctum usage
How to get auth user in public api using scantum
If it's PUBLIC api then there's no auth user. Or maybe I misunderstand.
@@PovilasKorop i mean when there is public post and i have to get list of public post which is liked or not by authenticated or unauthenticated user in browser or mobile app. I have been getting list of public post with authenticated user liked posts or comments by passing query ?user_id=1 if user is login otherwise ?user_id=0. Is there other way of getting auth user in public api??.
@@SussanRai I still don't really understand all the details, but I think in your case you're doing it right by passing a GET parameter.
@@SussanRai you can create 2 routes one with auth middleware and another without middleware (i.e. public). Both routes shall point to same function on controller. Then on controller you may use auth()->check() for loggedin status and do all your liked or not liked by auth stuff.
Yep there might be other way of extending auth middleware and not throwing error on failure. But i havent looked into it yet.
@@PovilasKorop from what i can tell, he probably meant "how to get User model based on Bearer Token?"
Me personally have done this by creating an API route called '/user' to fetch one of 3 User type based on their Bearer Token, but i thought it's impractical to test (the results could change).
Since i don't save PK on Mobile App, fetching User model after 1st time login are bit tricky, so i create /{user_type}/:phone_number where {user_type} are User Type (ex : users, admins, etc), i do this because these 3 are using different table.
From URL standpoint, it's ugly since phone_number always start with plus sign and each user on my app can only be identified by their User Type and Phone Number (meaning that 1 phone number can have more than 1 User Type).
I probably gonna make the endpoint can accept phone_number as query parameter like this (/users/?phone=:phone) while still allowing access by PK (ex. /users/77). What do you think about this approach? Sorry for the hijack, just so happens that OP's question are similar to mine
Nice. Please sir, could go a bit deeper and explain how the token ability feature works? I have followed what is at laravel.com/docs/8.x/sanctum#token-abilities but it did not work so I scrapped it from the project I was working on then. An explanation from you might help me see what was wrong. Thanks in advance sir.
I've personally never used those tokens because I was always going for authenticating users with auth:sanctum and then authorizing all the requests with that user's roles and permissions handled in roles/permissions DB table, or with an external package like Spatie Permission.
How to add prefix in default /login & /register api in laravel sanctum ?
Ex. Default api are /login & /register
I want /api/login & /api/register
How to achieve this?
Also in /user api i am getting many fields like id,name,email,created_date
I just want name and email id
How to do that?