Create an API with Laravel Passport & Personal Access Tokens

Поделиться
HTML-код
  • Опубликовано: 13 июл 2024
  • How to create an API with Laravel Passport and Personal Access Tokens
    In this video I'm going to show you how I like to setup a basic API using Laravel Passport. There are many ways to do this, but for the types of projects I work on, this typically suites my needs.
    Resources:
    laravel.com/
    laravel.com/docs/6.x/passport
  • НаукаНаука

Комментарии • 143

  • @ashisharyal64
    @ashisharyal64 4 года назад +34

    bro, dont stop. this is quality content. Im working on passport myself and this is exactly what wanted to see. Thank you

  • @PatBateman17
    @PatBateman17 4 года назад +10

    Great tutorial! In the latest version of Postman you can do the middleware GET request by choosing the Authorization tab, set Type to Bearer Token, and enter the token in the right.

  • @richasinha9326
    @richasinha9326 4 года назад +1

    The exact thing i was searching for a while. Thank you so much :)

  • @shafqatalinawaz3868
    @shafqatalinawaz3868 4 года назад +1

    I have been watching a-lot of videos but your way to explaining was splendid. Please keep up the good work and you really made great video for all those who want to learn Laravel Passport. +1 for great explanation +1 for following Laravel conventions. :D

  • @arafat1249
    @arafat1249 3 года назад +1

    I like your coding and explaining way. Very helpful tutorial, thank you very much.

  • @maxechendu1409
    @maxechendu1409 4 года назад +5

    You're a legend, thank you for this!!!!!

  • @chensam4794
    @chensam4794 4 года назад +1

    Thank you for your good tutorial which solve my question about the Personal Access Tokens of the passport

  • @seanrosen9855
    @seanrosen9855 4 года назад +1

    This is a super quality tutorial. Wishing you all the very best and please keep doing it.

  • @IvanBalkanov
    @IvanBalkanov 4 года назад +1

    So simple when watch the example. Thank you bro and go ahead!

  • @wilmeruzcategui3795
    @wilmeruzcategui3795 4 года назад +1

    Friend, excellent tutorial, it was just what I was looking for.

  • @globalevents5110
    @globalevents5110 3 года назад +1

    This is absolute quality content.

  • @sahilkhanna9782
    @sahilkhanna9782 3 года назад

    Simple, Finest and Greatest Content. Never Stop

  • @kirubaharanmayilvahanam8201
    @kirubaharanmayilvahanam8201 3 года назад

    This was a super confusing topic for me. You made it super clear! Please do more videos.

  • @devnebula
    @devnebula 4 года назад +1

    Hey, Thank you for this wonderful tutorial.

  • @CloudTechExpert
    @CloudTechExpert 4 года назад

    Bro Kudos. You are doing amazing stuffs. You have really helped me to understand Authentication and Authorization using laravel Passport.

  • @lysokkong5826
    @lysokkong5826 4 года назад +1

    Great job! please make more videos like this.

  • @aquibbhaiji7
    @aquibbhaiji7 4 года назад +1

    This is really helpful. I hope we will meet next video. Thanks

  • @PranoySinha
    @PranoySinha 2 года назад

    Like your code a lot, buddy. Looking forward to get some more videos like this. Keep it up.

    • @PranoySinha
      @PranoySinha 2 года назад

      Instead of relocating api.php in api/v1 it can also be done setting a prefix as v1 in actual api.php. I guess it also work.

  • @GonzaloG
    @GonzaloG 4 года назад +1

    Thanks you for your video! Awesome!

  • @pratikrane149
    @pratikrane149 4 года назад +5

    This was a great tutorial. Understood everything you explained.
    Can you also please make next part of this tutorial explaining how to integrate Socialite with Passport for API based social authentication !?

  • @wylinonwax
    @wylinonwax 3 года назад

    Thanks for a great tutorial!

  • @IELTSLISTENINGTESTCHANNEL
    @IELTSLISTENINGTESTCHANNEL 4 года назад +1

    Thank you very much. It is very nice content.

  • @wgnbass
    @wgnbass 4 года назад +1

    Thanks for the tutorial,.

  • @musiccreatorYuyakeMonster
    @musiccreatorYuyakeMonster 3 года назад +1

    Thank you so much. It is exact thing I want to do.

  • @mycslab-sikar9424
    @mycslab-sikar9424 3 года назад

    Very helpful. Thank you❤️

  • @markryandelarmente8349
    @markryandelarmente8349 4 года назад +1

    Nice tutorial. Thanks

  • @elyasmoshirpanahi7184
    @elyasmoshirpanahi7184 4 года назад +1

    this video really helped me god bless you!🌹🌹🌹🌹💚💚💚💚

  • @adnan24150
    @adnan24150 3 года назад +1

    thank you very much for this explain :)

  • @moriskakengi2628
    @moriskakengi2628 2 года назад

    Perfect Tutorial

  • @Ravidelle
    @Ravidelle 3 года назад +1

    Cool! A git repo would be awesome as well so we get to compare and analyze stuff on the go (no need getting to certain parts of the video)

  • @fatih-araz
    @fatih-araz 4 года назад +1

    U should extend this tut. Great quality.

  • @rochim9478
    @rochim9478 3 года назад

    This is Great content, don't stop create contents :D

  • @houiderwalid5842
    @houiderwalid5842 4 года назад +1

    Thank you so much sir !

  • @madanmalhotra
    @madanmalhotra 3 года назад

    Thanks bro, very nice

  • @jacklindcosta6740
    @jacklindcosta6740 2 года назад

    Awesome !

  • @philippechavatte8741
    @philippechavatte8741 4 года назад +1

    Good job !

  • @josemariemojica2474
    @josemariemojica2474 3 года назад

    Thanks a lot bro

  • @19_ridwansatriawicaksana87
    @19_ridwansatriawicaksana87 Год назад

    Thank you so much

  • @autopop9679
    @autopop9679 4 года назад

    Great tutorial. It’s based on use of personal tokens whilst other (mostly older tutorials) are based on password grant tokens. Are there any pros/ cons related to either route asides personal tokens being simpler (in the sense of not worrying about creating a back-end proxy to hide details of client_id, client_secret, grant_type?)

  • @mohammadazimmhdfakhruddin3475
    @mohammadazimmhdfakhruddin3475 4 года назад +1

    thank you!

  • @rubenvl
    @rubenvl 3 года назад

    Hi! Thanks for the tutorial. What are the clients created for if we don't use them in postman? Thanks!

  • @kevinpallado9638
    @kevinpallado9638 3 года назад

    hi man you got some good voice and excellent teaching technique, hoping that you also have explanation regarding "Client credentials grant tokens"

  • @josuebarros5727
    @josuebarros5727 2 года назад

    Thanks a lot!!!
    I'm really thinking about using Passport along with an company test I'm attending.
    I'm using Vue2 on front-end...

  • @malikabdulsamiawan4085
    @malikabdulsamiawan4085 3 года назад

    thanks buddy

  • @webleydevelopment
    @webleydevelopment 4 года назад +2

    Hi. This is great. Is this the typical way to create an RestFul API for my laravel web app? I want my users to be able to use a mobile app to use my application. Thanks!

  • @AnilSingh-uh8xp
    @AnilSingh-uh8xp 3 года назад +1

    best tutorial

  • @mdmahmudulhasan6448
    @mdmahmudulhasan6448 3 года назад

    nice bro... keep it up...bro

  • @camiloaraya5605
    @camiloaraya5605 4 года назад

    Thank you for your video, i have a question about laravel passport. I am developing a app with laravel 6.x and i going implement Vue JS just frontend framework ( same laravel project ), so my question is about how use laravel passport and Auth Laravel with the frontend in the same project , worth it working with laravel passport if the frontend is in the same laravel project ? , and another question is, if i need to use laravel passport, what kind of grant access or token should use in this case ?
    Thanks !

  • @MuhammadAsif-nx7om
    @MuhammadAsif-nx7om 3 года назад

    good one

  • @SuperNausif
    @SuperNausif 4 года назад +3

    If anybody wants to test incorrect token, then pass a key in Header below Authorization named "Accept" and its value as "application/json" to get error in json else it will output HTML code

  • @TroyerProz
    @TroyerProz 4 года назад +1

    Big problem using Laravel passport with personal access tokens its everytime the user tries to log in a new token is created. It's fine when we are talking about mobile apps because its pretty easy to save the first token created and rarely the user will log in again but when we are talking about web its another thing, mostly the token is going to be lost on the web browser every few days and he needs to login again and it means another token is going to be generated.
    Any work around?

  • @kyahAndoy
    @kyahAndoy 3 года назад

    Great tutorial Sir! By the way can I integrate this in my React App?

  • @EugeneChe-81
    @EugeneChe-81 4 года назад +1

    Привет, я из России. Спасибо за урок. Мир)

  • @anujme3
    @anujme3 3 года назад

    Is passport good for simple REST API? I don't need full OAuth2 server implementation just CURD operation from Angular to PHP Laravel. So will JWT or random token generation is good enough for Authentication ?

  • @josuebarros5727
    @josuebarros5727 2 года назад

    What do you recommend for Registering?
    Is that hard to implement Fortify along with Passport???

  • @stalinwesley
    @stalinwesley 4 года назад

    Thanks

  • @lserranoit
    @lserranoit 3 года назад

    Question can I use Laravel passport for create an API to send an email?

  • @kameshvinayaka
    @kameshvinayaka 2 года назад

    Hi, this is so gud explaination, i have a doubt can we create a multidevice token that means users have many tokens along with that i need to save some device information along with that token is it possible with this passport

  • @Dibujartmex
    @Dibujartmex 2 года назад

    in the part of migration, ¿ what wappend if i have many tables whith many dats and i wanted to use one of this tables for the passport?

  • @whatsupbudbud
    @whatsupbudbud 3 года назад

    Which class is createToken() part of? Is it a trait? Mine doesn't get recognized as being part of Auth::user() return result which is Authenticable::class.

  • @mister_tompkin
    @mister_tompkin 4 года назад +2

    thank you for this video! but i hove one question is where is refresh_token ?

    • @scrypster
      @scrypster  4 года назад +3

      By default, Personal Access Tokens are long-lived, so they are good for a year. I don't believe this access token method comes with a "built-in" refresh option. If you wanted to issue shorter-lived access tokens you could opt for the Password Grant Token and this would provide a refresh token in the json response. For this video I just went for a "proof of concept" with the Personal Access Token.

  • @kausarahmad4879
    @kausarahmad4879 3 года назад +1

    Your videos are the best out here on youtube. I'm more interested in Vue.js than ever, But could you plz ZOOM IN on VS Code when recording so the code is not tiny || increase font size plz.

    • @scrypster
      @scrypster  3 года назад

      Thank you so much! Unfortunately I recorded a bunch of these videos before I realized my text was too small. :-( So there will be a few more videos coming out with small text. HOWEVER, after 5-6 videos I realized and I made the font much larger. My GoLang Videos have much larger text. I also have a Real-Time Chat with Laravel and Vue.js Tutorial going out this afternoon. So check that out and let me know if the font size is good. Again, Thank you for the feedback!

    • @kausarahmad4879
      @kausarahmad4879 3 года назад

      @@scrypster Thank you mate! I have seen the font is fixed now in the new tutorial about Chat App you uploaded today. Keep up good work. I wish you could do some full length courses like multiple lectures on Vue and Laravel . Ppl & me will pay to learn from u , coz ya got the skill and soothing voice.

  • @GoogleUser-mx5oe
    @GoogleUser-mx5oe 2 года назад

    So did you have that email before in database?

  • @rajtechteam-view
    @rajtechteam-view 3 года назад +1

    GOOD WORK. I need registration system. please create another video for passport system

  • @devtube734
    @devtube734 3 года назад

    brother, in case of laravel socialite user, what will be the login and registration function

  • @jamols09
    @jamols09 4 года назад +1

    Can you make a tutorial Passport using VueJs and like confirming on the token when the users performs an input ? Like please ? can you ? I need help with VueJs and I'm still studying it.

  • @dennisvandermeer8238
    @dennisvandermeer8238 4 года назад +4

    I'm using Laravel 7.20.0 and it seems there are some changes necessary in the LoginController.php for everything to work:
    Your line $accessToken = Auth::user()->createToken('authToken')->accessToken; does not work because CreateToken does not exist.
    And I have added some code to account for an empty user table.
    public function login( Request $request ) {
    $login = $request->validate([
    'email' => 'required|string',
    'password' => 'required|string'
    ]);
    if ( !Auth::attempt( $login )) {
    return response( ['message' => 'Invalid login credentials.'] );
    }
    $user = $request->user();
    if ($user) { // Check if we have users in the database
    $accessToken = $user->createToken('authToken')->accessToken;
    return response(['user' => Auth::user(), 'access_token' => $accessToken]);
    } else {
    return response( ['message' => 'No user found in the database.'] );
    }
    }

    • @teczoa
      @teczoa 4 года назад

      Add in App/User
      class User extends Authenticatable
      {
      use Notifiable, HasApiTokens;
      the
      HasApiTokens
      to work

  • @adam_devs
    @adam_devs 3 года назад

    could this be used as sso ? for multiple domain

  • @shygrammer
    @shygrammer 2 года назад

    i"d really like a git repo to this project. where can i find that?

  • @tasya_nabila
    @tasya_nabila 2 года назад

    My resource folder didn't have the component folder. Am I doing something wrong?

  • @karthikbalan8005
    @karthikbalan8005 3 года назад

    bro mobile app using google and facebook login for signin. after logged in by google or facebook the users can access api of the app by creating other side. how could be authentication and authorized to access token

  • @chiragmistry1863
    @chiragmistry1863 4 года назад

    How to use in multiple guard?

  • @thaungthanhan5928
    @thaungthanhan5928 3 года назад

    I am having 419 unknown status error. I believe it is something to do with middleware. How do you take care of your routes' middleware? It only works when I put the routes in the exception but that is not the right way to solve. Please kindly help sir.

  • @AriqDaffaA
    @AriqDaffaA 4 года назад +1

    Great tutorial! But the vscode window and font is too small

  • @syedfurquan5220
    @syedfurquan5220 4 года назад +1

    Hi. Nice tutorial just 2 things 1- It would have been great if you had maximise VS code .2 how did you register the user that you used for login?

    • @pratikrane149
      @pratikrane149 4 года назад

      Possibly thru the Laravel auth scaffolded UI based register form, or directly saved in the database by running a query in database.
      But in real we will have to actually make our own API based RegistrationController.

    • @dgloria
      @dgloria 4 года назад

      @@pratikrane149 Which table contains that data? I added user with email=email and password=password to my users table (Laravel7 ) it isn't good, not sure why.

    • @pratikrane149
      @pratikrane149 4 года назад

      @@dgloria Did you bcrypt your password before saving it?

    • @dgloria
      @dgloria 4 года назад

      I have figured out the login credential stuff: in your users table add email = email, go to bcrypt-generator.com/ and hash your password, and save this as password in the users table.

    • @dgloria
      @dgloria 4 года назад

      @@pratikrane149 yup, just figured it out, had to lookup google what encryption Laravel7 uses :D

  • @jonahmarsden
    @jonahmarsden 2 года назад

    what if you dont have access to the database only api?>

  • @waqasyousuf8053
    @waqasyousuf8053 2 года назад

    When I am trying to get the details using the generated access token giving authorization in request Header as Bearer just as you did. But I am getting error "message: unauthenticated"

  • @zenasawuku7695
    @zenasawuku7695 3 года назад +1

    createToken() method is undefined for Auth::user(). Can someone please help me out?
    13:54

  • @GoogleUser-mx5oe
    @GoogleUser-mx5oe 2 года назад

    Why you add an api on controller when you can use the api on routes ?

  • @ashique12009
    @ashique12009 3 года назад

    This is very good but how you got the user to login, you didn't create the user?
    You just created 2 clients by passport command.
    Where from you got the email and password :( ?
    Thanks.

  • @winstonwolf2981
    @winstonwolf2981 3 года назад

    What about refresh tokens?

  • @giannizamora7247
    @giannizamora7247 2 года назад

    I ran into an issue, I am using laravel 8 to follow this but passport seems to have removed the front-end components generated by vendor command. anybody else ran into this issue or know how to fix?

  • @won1626
    @won1626 2 года назад

    How can I store Token on session?

  • @marcelodias6638
    @marcelodias6638 4 года назад

    Firstly, AWESOME TUTORIAL! But I'm having trouble with the "php artisan migrate" command.
    This is the error I'm getting:
    Illuminate\Database\QueryException
    SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables where table_schema = laravel and table_name = migrations and table_type = 'BASE TABLE')
    at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
    667| // If an exception occurs when attempting to run a query, we'll format the error
    668| // message to include the bindings with SQL, which will make this exception a
    669| // lot more helpful to the developer instead of just the database's errors.
    670| catch (Exception $e) {
    > 671| throw new QueryException(
    672| $query, $this->prepareBindings($bindings), $e
    673| );
    674| }
    675|
    +34 vendor frames
    35 artisan:37
    Illuminate\Foundation\Console\Kernel::handle()
    Can any one help me with this? Thanx!

    • @eliezerciriaco8356
      @eliezerciriaco8356 Год назад

      you might need to update your database details in your .env file

  • @kristofszobacsi5123
    @kristofszobacsi5123 3 года назад +1

    Heyy!! Great content man! Im developing a multi tenant app, which uses vuejs and laravel, the thing is when using global scopes i get out of the session the tenant_id but have no way of using that info in this manner, since in the controller i cannot get the session() info or i get null, i cannot user Auth::user()->tenant_id but al these work in blade views...How could i make that only logged in user can access api calls but without this token nightmare? Since the user will already have to log in to see the dashboard and so on it seems ridiculous to ask him again when he wants to see the data corresponding to him/she....Any ideas? Cheers!

    • @scrypster
      @scrypster  3 года назад +1

      Hmm. I’m not sure I fully understand your issue. Is your tenant_id the same as the user ID? Or are you specifically looking for the session ID? I would think there are many ways to get this information. Is Auth::id() not the same as your tenant_id?
      Another option is using Laravel Sanctum. Check out a video I just posted about Laravel Jetstream (Jetstream uses Sanctum). Jetstream is pretty cool and I think it might accomplish what you are trying to do.
      A third option would be to use Vuex to store state within your frontend Vue application. Then after your user logs in, create an API call with your user Bearer Token and request the tenant_id and store it with Vuex.

    • @kristofszobacsi5123
      @kristofszobacsi5123 3 года назад

      @@scrypster I may have explained myself rather poorly... The scenario is: Having a frontend for the clients, and adminpanel for the workers or(CMS). Then thing is that in the CMS i plan to have various hotels working, each hotel can only see the data which is for them, so every user and other data has a hotel_id so you can differentiate and show if a usrr has hotel_id = 1 i only show them data which has that hotel id in it, that i hve done global scopes and adding a event listener so in the session i grab the hotel id of the user and just get the info corresponding to them and in my case the admin which i can see everything.... The problem arrives when i try to load the content through the api to ge it loaded with axios in vuejs, since these routes of api doesnt have auth connected to them it loads every info doesnt matter the session hotel id which i got with the event listener... I dont eant them to log in once and then get acces tokens to see their corresponding data, just log in once and apply somehow that global scope to the api call... Thanks for answering so fast by the way! your videos are awesome!!!!

    • @scrypster
      @scrypster  3 года назад +1

      So it sounds like there are a lot of moving parts. It’s really difficult to make a recommendation without seeing the current code and system architecture. If you currently have a system working, using sessions, what are you trying to accomplish by exposing domain.com/api/.../... ? Do you want to allow 3rd party apps to interact on behalf of your users? Why do you want to use the API routes at this point in time? I still think Laravel Sanctum is probably the answer to your problem.
      The video your commenting on is to bypass the use of sessions. So there are absolutely no sessions. If you want to use both Sessions and API, I think you probably want Laravel Sanctum.

    • @kristofszobacsi5123
      @kristofszobacsi5123 3 года назад +1

      @@scrypster Heey !! thenk you very much for your response! I got it, had to find the technical terms for these things i want because otherwise its very misleading...What i wanted is to consume my own API with Javascript(Vuejs), by installing passport and setting the driver in config to passport, config the AuthServiceProvider i can use the global scopes with my api and each user just gets through the api what he should...Thanks again man for the replies it shows that you care and pay attention to your people hehe :D have a great week!

  • @jamols09
    @jamols09 4 года назад

    Why are you not making a part 2 ?

  • @artist00jk
    @artist00jk 3 года назад +2

    Thanks for the video, appreciate this content :)
    I am a bit new here so I am confused as to how laravel knows that the users email is your email and the password is "password"? And additionally how it knows that "password1" is the incorrect password.

    • @scrypster
      @scrypster  3 года назад +1

      This is an older video I did maybe a year ago. Pretty sure I created a user account that wasn’t part of the video. Sorry about that.

    • @artist00jk
      @artist00jk 3 года назад +1

      @@scrypster I just realised when i went and watched a previous video of yours :)
      Thanks for the reply!

    • @pwhak
      @pwhak 3 года назад

      @@scrypster My lesson came to a halt too. How do you create the account for logging in?

    • @pwhak
      @pwhak 3 года назад

      Not sure if this is the best way but I was able to create a user account with 'php artisan tinker'. Then 'DB::table('users')->insert(['name'=>'test','email'=>'test@test.com','password'=>Hash::make('1234')])'. Hope it helps someone else who may have gotten stuck. Also doesn't take away from how amazing these videos are. Thank you for making them!

  • @syedm.hharis3009
    @syedm.hharis3009 3 года назад

    i get the error "Unable to locate publishable resources" when I run php artisan vendor:publish --tag=passport-components
    can someone help me

  • @seiu2911
    @seiu2911 3 года назад +1

    とても助かりました!😁
    どうもありがとうございます!
    Thank you so much\(^o^)/

  • @jlvargas18
    @jlvargas18 3 года назад

    Anyone know why Auth::user() is null in LoginController?

  • @flint0131
    @flint0131 4 года назад +6

    I'm an atheist but thank god for this 🥳

  • @prane81
    @prane81 3 года назад

    How to refresh the token

  • @patahapamovies4796
    @patahapamovies4796 4 года назад

    you did not complete crud ..... can you create a route for register user?

    • @ScalableScripts
      @ScalableScripts 4 года назад

      you can check more for register user route here: ruclips.net/video/F9Xmc3iHc88/видео.html

  • @kamujutrinadh8291
    @kamujutrinadh8291 3 года назад

    Where to provide authentication key and password?

  • @Mahmudulhasan-ts5hm
    @Mahmudulhasan-ts5hm 4 года назад

    how to delete token?

  • @jeanrodrigosantos285
    @jeanrodrigosantos285 3 года назад +1

    19:25 When did you create this user? Anybody can tell me ?

    • @iBusik
      @iBusik 3 года назад

      you can use laravel tinker to add new user

    • @kyahAndoy
      @kyahAndoy 3 года назад

      I'm also confused by this

  • @mobsovichea1968
    @mobsovichea1968 2 года назад +1

    Undefined method 'createToken'

  • @klavenreymatugas2850
    @klavenreymatugas2850 3 года назад

    How to change users.id to users.user_id?

  • @vivekchourasiya1875
    @vivekchourasiya1875 3 года назад

    plz make video for b2b api

  • @stefan4800
    @stefan4800 4 года назад

    Bigger screen please. ;)