Creating your own Oauth2 server using Laravel Passport — Password grant flow
Table of contents
- Initial config — Recommend you start here
- Setting up authorization code flow + with PKCE
- Creating your own Oauth2 server using Laravel Passport — client credentials flow
- Creating your own Oauth2 server using Laravel Passport — Password grant flow — You are here
- Creating your own Oauth2 server using Laravel Passport — Implicit grant flow
- Creating your own Oauth2 server using Laravel — Device Grant flow
What we will do
- We will implement password grant flow.
Analogy
Password grant is used to issue token using the client user name and password, for Laravel if you are using passport to issue tokens then it’s a good idea to use sanctum instead, this method is generally not recommended.
Password grant allows users to authenticate using their email/password combination without going through the whole authorization code flow. This can be used to authorize first party applications e.g. mobile app.
The best analogy for this, is assuming a stranger visits you and wants to make a purchase, so you ask this stranger for their secret name (email and password), and then with this information you visit your friend (OAuth2 server) and ask them if they recognize this user. But in order to verify that it is actually you, in addition to the strangers credentials, you also provide the shared secret between you and your friend. Once verification is successful your friend issues you the access token, and you can now use this token to make API requests in this case perform a transaction on behalf of the stranger. The flow will be as follows.
- Ask the stranger for their username/password.
- Visit your friend with the user credentials.
- Verify it’s actually you by providing the secret that only you and your friend know. (client_id + client_secret).
- If verification is successful your friend issues you with an access token.
- You can then use this token to make API requests.
Step 1: Creating the ‘password grant’ client in OAuth2-Server app
To create this client run the following
php artisan passport:client --password
You should have something like this
And in your DB the following record should be inserted
Step 2: Requesting for a token
In order to request for a token we will send a request as shown below
Step 3: Using the token
Once you’ve gotten you can access any of the APIs with ‘api’ guard. In our case the GET: api/user
route.
Conclusion
Hopefully you can now implement your own Oauth2 server. Leave a clap and feedback if you found this helpful.
You should always use scopes to limit what an access token issued can do in your system. The principle of lease privilege.
What next
References
- https://github.com/Ghostscypher/OAuth2-Tutorial — Github repo for this tutorial
- Laravel Passport — Laravel — The PHP Framework For Web Artisans