Learn about Grant Types in Laravel Passport

Published on by

Learn about Grant Types in Laravel Passport image

OAuth2 is a security framework that controls access to protected areas of an application, and it’s mainly used to control how different clients consume an API ensuring they have the proper permissions to access the requested resources.

Laravel Passport is a full OAuth2 server implementation; it was built to make it easy to apply authentication over an API for laravel-based web applications.

Terminology

Before going any further, we need to understand the following definitions:

Client This is the application trying to consume our API, creating clients in Passport is done via this console command:

php artisan passport:client

Every client will have a key, name, secret, redirect URI, and a user (Application Creator/Owner).

Resource Owner This is the entity (User) that owns the data a client is trying to consume.

Resource Server That’s our API; it may have public data that doesn’t require an owner permission to read, and other private data that requires an owner permission.

Public endpoints can be, for example, the endpoint for searching tweets, that doesn’t require a specific resource owner permission.

On the other hand, an endpoint that posts tweets on behalf of a user is a private endpoint, interacting with such endpoints requires permission from the resource owner.

Scope It’s a permission to access certain data, or perform a certain action.

You may define scopes using Passport::tokensCan() method inside your AuthServiceProvider.

Passport::tokensCan([
'read-tweets' => 'Read all tweets',
'post-tweet' => 'Post new tweet',
]);

Grant It’s the method used to get an access token.

Access token That’s the token an app (client) needs to communicate with the server (API).

How to Authorize third-party apps

First, we need to create a test app using the following command:

php artisan passport:client

Laravel Passport will prompt asking you for the user ID, app name, and the redirect URI.

Now that we have the client registered we can now get an access token using the “Authorization Code Grant”.

This type of grants works by pointing the browser to the authorization server where the user can log in to his account and grant access to the app, once access is given the app shall send another request asking for an access token, using this token the app will be able to make further requests.

For most of the cases you’ll be using this grant type to allow all kind of applications to consume your laravel-based API private endpoints, this includes server-side apps, JavaScript apps, & native mobile apps.

Step 1: Asking for permission

From the client app, you’ll need to point the user to the following URL:

http://resources.dev/oauth/authorize?client_id={CLIENT_ID}&redirect_uri={URI}&response_type=code&scope={SCOPE}

Using the correct CLIENT_ID & URI as in the client created by passport.

You can list the scopes as a space separated list of permissions you’d like to get from the resource owner, for example:

read-tweets post-tweets follow-others

Now if Passport was installed correctly such that the routes are published in your AuthServiceProvider, if all is well the above request will show a nice screen asking the user to give permission to the app, the screen will list all the scopes the app is asking for.

In case the user denied access, Passport will redirect the user to the given redirect_uri with error=access_denied in the URL.

However, if the user approved access, Passport will redirect to the redirect_uri with code={authorization_code_here}.

Step 2: Getting an access token

Now that we have the Authorization Code, we need to send a POST request to http://resources.dev/oauth/token to get the access token, the body of the request should contain the following:

  • grant_type: authorization_code
  • client_id: the one created by Passport
  • client_secret
  • redirect_uri
  • code: The given Authorization Code

The response is going to be a JSON object with the following keys:

{
"token_type": "Bearer",
"expires_in": 3155673600,
"access_token": "eyJ0eXAiOiJKV1QiL....",
"refresh_token": "XslU/K6lFZShiGxF1dPyC4ztIXBx9W1g..."
}

Refreshing an access token

By default the access_token will not expire for 100 years, if you don’t mind this then you don’t need to save the refresh token, otherwise, if you’d like the access_tokens to have a short lifetime you can tell Passport:

Passport::tokensExpireIn(Carbon::now()->addDays(15));
 
Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));

If your tokens are short-lived, then the client needs to save the refresh_token to use it later to issue a new access token.

To refresh an access token the client needs to make a request to http://resources.dev/oauth/token with the following parameters:

  • grant_type: refresh_token
  • client_id: the one created by Passport
  • client_secret
  • refresh_token
  • scope

Authorizing first-party apps

If you’re authorizing a trusted app of your own there’s no need for such a long road to get an access token, you only need to ask the user to provide a username/email & password in order for the app to get an access token. This type of grants is called Password grant.

You need to check your database to grab the password client created by Passport.

To get an access token for a first-party app you need to make a POST request to http://your-app.com/oauth/token with the following parameters:

  • grant_type: password
  • client_id:
  • client_secret
  • username
  • password
  • scope

The response is going to be a JSON object with the following keys:

{
"token_type": "Bearer",
"expires_in": 3155673600,
"access_token": "eyJ0eXAiOiJKV1QiL....",
"refresh_token": "XslU/K6lFZShiGxF1dPyC4ztIXBx9W1g..."
}

Authorizing an app manually

Passport ships with a way to create access tokens manually, this is useful in multiple situations such as testing during development or maybe if you allow authenticating users on a third-party application via their mobile number instead of a login web form.

For example, a third party app may show a phone field for the user, when filled a service on your server sends an SMS to that number with an access code, the user will input this code upon reception in which the app will exchange with an access token from your server.

To create an access token:

$token = $user->createToken('Pizza App', ['place-orders', 'list-orders'])->accessToken;
Mohamed Said photo

Web Developer and Laravel Core Contributor

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Laravel Idea for PhpStorm logo

Laravel Idea for PhpStorm

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Laravel Idea for PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
JetShip - Laravel Starter Kit logo

JetShip - Laravel Starter Kit

A Laravel SaaS Boilerplate and a starter kit built on the TALL stack. It includes authentication, payments, admin panels, and more. Launch scalable apps fast with clean code, seamless deployment, and custom branding.

JetShip - Laravel Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Dynamic Mailer Configuration in Laravel with Mail::build image

Dynamic Mailer Configuration in Laravel with Mail::build

Read article
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article