Make an OAuth2 Server Using Laravel Passport _ by Successive Digital _ Successive Digital _ Medium
Make an OAuth2 Server Using Laravel Passport _ by Successive Digital _ Successive Digital _ Medium
Listen Share
Laravel already makes it easy to perform authentication via traditional login forms,
but what about APIs? APIs typically use tokens to authenticate users and do not
maintain session state between requests.
Laravel Passport is native OAuth 2 server for Laravel apps. Laravel Passport package
comes with a database migrations, routes, and middleware to ultimately create an
authorization server that will return access tokens to allow access to server
https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 1/19
10/18/23, 2:36 PM Make an OAuth2 server using Laravel Passport | by Successive Digital | Successive Digital | Medium
resources. It uses the League OAuth2 Server package as a dependency but provides a
simple, easy-to-learn and easy-to-implement syntax.
⚠️ This is not an OAuth or Laravel tutorial, so this article will focus solely on how
you can use Laravel Passport to create an OAuth server on an existing application. If
you want to learn more about Laravel or OAuth, you can look here and here
respectively.
Installation/ Requirements
Before we start setting up, make sure you have the following requirements ready as
they will be necessary to follow through this article:
First of all install the composer in your system and this command.
$ composer install
$ cd Desktop/
https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 2/19
10/18/23, 2:36 PM Make an OAuth2 server using Laravel Passport | by Successive Digital | Successive Digital | Medium
$ cd auth-app/
Now, run your project after install successfully using this command on the terminal.
Now, you get http://127.0.0.1:8000 to click it and you see laravel homepage.
https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 3/19
10/18/23, 2:36 PM Make an OAuth2 server using Laravel Passport | by Successive Digital | Successive Digital | Medium
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
{
Schema::create(‘users’, function (Blueprint $table) {
$table->bigincrements(‘id’);
$table->string(‘first_name’);
$table->string(‘last_name’);
$table->string(‘email’)->unique();
$table->timestamp(‘email_verified_at’)->nullable();
$table->string(‘password’);
$table->rememberToken();
$table->timestamps();
});
Schema::dropIfExists(‘users’);
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Database
DB_USERNAME=Username
https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 4/19
10/18/23, 2:36 PM Make an OAuth2 server using Laravel Passport | by Successive Digital | Successive Digital | Medium
DB_PASSWORD=Password
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
protected $fillable = [
];
protected $hidden = [
‘password’, ‘remember_token’,
];
}
<?php
namespace App\Providers;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 5/19
10/18/23, 2:36 PM Make an OAuth2 server using Laravel Passport | by Successive Digital | Successive Digital | Medium
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as
ServiceProvider;
class AuthServiceProvider extends ServiceProvider
Protected $policies = [
passport::routes();
}}
<?php
return [
‘defaults’ => [
‘guard’ => ‘web’,
‘passwords’ => ‘users’,
],
‘guards’ => [
‘web’ => [
‘api’ => [
‘driver’ => ‘passport’,
‘provider’ => ‘users’,
],
],
‘providers’ => [
‘users’ => [
https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 6/19
10/18/23, 2:36 PM Make an OAuth2 server using Laravel Passport | by Successive Digital | Successive Digital | Medium
],
],
‘password’ => [
‘users’ => [
‘provider’ => ‘users’,
],
];
<?php
use Illuminate\Http\Request;
Route::group([
Route::post(‘login’, ‘Auth\AuthController@login’)-
>name(‘login’);
Route::post(‘register’, ‘Auth\AuthController@register’);
Route::group([
Route::get(‘user’, ‘Auth\AuthController@user’);
});
});
1. Register Users
2. Login users
3. Logout
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
//
public function login(Request $request) {
$request->validate([
‘email’ => ‘required|string|email’,
‘password’ => ‘required|string’
]);
$credentials = request([‘email’, ‘password’]);
// print_r($credentials);die;
if(!Auth::attempt($credentials))
return response()->json([
https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 8/19
10/18/23, 2:36 PM Make an OAuth2 server using Laravel Passport | by Successive Digital | Successive Digital | Medium
],401);
$user = $request->user();
$tokenResult = $user->createToken(‘Personal Access Token’);
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
‘access_token’ => $tokenResult->accessToken,
)->toDateTimeString()
]);
}
public function register(Request $request)
{
$request->validate([
‘fName’ => ‘required|string’,
‘lName’ => ‘required|string’,
]);
$user = new User;
$user->first_name = $request->fName;
$user->last_name = $request->lName;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return response()->json([
$request->user()->token()->revoke();
return response()->json([
‘message’ => ‘Successfully logged out’
}
public function user(Request $request)
{
return response()->json($request->user());
}
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
->header(‘Access-Control-Allow-Origin’, ‘*’)
->header(‘Access-Control-Allow-Methods’,
‘GET, POST, PUT, PATCH, DELETE, OPTIONS’)
->header(‘Access-Control-Allow-Headers’,
‘Content-Type, Authorization, X-Requested-With, X-
XSRF-TOKEN’);
}
}
https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 10/19
10/18/23, 2:36 PM Make an OAuth2 server using Laravel Passport | by Successive Digital | Successive Digital | Medium
<?php
namespace App\Http;
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::cl
ass,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\Cors::class,
];
}
Tests
Now time to test the whole things are working properly or not, if you get an error
please follow all these steps again.
Sending First Name, Last Name, Email and Password in POST requests.
https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 11/19
10/18/23, 2:36 PM Make an OAuth2 server using Laravel Passport | by Successive Digital | Successive Digital | Medium
When you log in with register email and password you got token. You can store this
token in local storage. This token is also stored in the oauth_access_tokens table.
We will be sending GET request to your URL and we need to send token as
Authorization Header.
Open in app Sign up Sign In
Conclusion
Above way we can do API authentication in Laravel Application with a passport.
Laravel Passport makes it super easy and it takes only a few steps as we have seen in
the article to make your application OAuth 2 enabled. If you get any errors please
follow the steps again.
Follow
A next-gen digital transformation company that helps enterprises transform business through disruptive
strategies & agile deployment of innovative solutions.
https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 12/19