- Create a new Laravel project.
composer create-project laravel/laravel -passport-starter --prefer-dist - Install(add) laravel passport
composer require laravel/passport - Make sure your database is well set-up
- Run
php artisan migrate - Run
php artisan passport:installThis will generate encryption keys and database access clients(personal and Password grant) - Add
HasApiTokenstrait to your User class. - Next add
Passport::routes();to theAuthServiceProviderto register all the routes needed by passport. - Finally for setup change the api driver from
tokenropassportinauth.phpconfig file.
For registration do it like any other registration in laravel application, You can even add email verification and the likes.
To login here are the steps:
- Create a middleware
InjectPasswordGrantCredentialsand add it to the namedmiddleware Kernelfile. - On the
AuthServiceProvideroverride theoauth/tokenroute to include theInjectPasswordGrantCredentialsmiddleware. - The middleware will require a
password_grant_client_idsetting in theauthfile or you can put it in your app specific config file. - Now it's okay and you can login using Post
{{url}}/oauth/tokenwith the following parameters:email = '[email protected]'//user inputpassword = 'supersecretpassword'//user inputgrant_type = 'password'// This must be password.
- In response you will get a
token,refresh_token,expires_inandtoken_type(See login .png)
In order to access restricted resources, create the url inside the auth:api middleware group.
- To be identified as user the
Authorization: Bearer {{token}}must be include. - Create a model resource using
php artisan make:resource UserResource - Then Get
{{url}}/api/user
The access token given expires after expire_in time given and to get a new token you will need to refresh token.
Here are the steps:
- use Post
{{url}}/oauth/tokenwith the following parameters:refresh_token = {{refresh_token}}//Refresh token you got when you logged ingrant_type = 'refresh_token'// This must be refresh_token.
- make sure the header contains
Authorization: Bearer {{token}}//Access token got from loggig in.
To log out just send a post request to {{url}}/api/logout The header must contain Authorization: Bearer {{token}} `
If i have missed anything or a better secure way to do it send a pr/issue i will appreciate.