0% found this document useful (0 votes)
0 views

Make an OAuth2 Server Using Laravel Passport _ by Successive Digital _ Successive Digital _ Medium

This document provides a step-by-step guide on how to create an OAuth2 server using Laravel Passport, which is a native OAuth 2 server for Laravel applications. It covers installation requirements, database migration, configuration, route setup, and controller creation necessary for implementing API authentication. The article emphasizes that it is not a general tutorial on OAuth or Laravel but focuses specifically on using Laravel Passport for OAuth server setup.

Uploaded by

icesalman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Make an OAuth2 Server Using Laravel Passport _ by Successive Digital _ Successive Digital _ Medium

This document provides a step-by-step guide on how to create an OAuth2 server using Laravel Passport, which is a native OAuth 2 server for Laravel applications. It covers installation requirements, database migration, configuration, route setup, and controller creation necessary for implementing API authentication. The article emphasizes that it is not a general tutorial on OAuth or Laravel but focuses specifically on using Laravel Passport for OAuth server setup.

Uploaded by

icesalman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

10/18/23, 2:36 PM Make an OAuth2 server using Laravel Passport | by Successive Digital | Successive Digital | Medium

Make an OAuth2 server using Laravel Passport


Successive Digital · Follow
Published in Successive Digital
5 min read · Jan 30, 2020

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.

The source code to the todo application is available on GitHub.

⚠️ 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:

PHP 7 or later installed locally.

Basic Knowledge of Laravel PHP framework.

Basic Knowledge of OAuth and how it works.

Step 1 — Getting Started


Let’s go ahead and create a brand new Laravel project first of all. Open your
Terminal or Command Prompt and go to the directory where you want to create an
app. You can use the following command to change directory.

First of all install the composer in your system and this command.

$ composer install

Use command to change directory.

$ cd Desktop/

Then, run the following command to create a new project.

$ composer create-project --prefer-dist laravel/laravel auth-app

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

Next go inside the directory by running this command.

$ cd auth-app/

Run migration Database.

$ php artisan migrate

Generate a secure application key.

$ php artisan key:generate

Now, run your project after install successfully using this command on the terminal.

$ php artisan serve

Now, you get http://127.0.0.1:8000 to click it and you see laravel homepage.

Step 2 — Installing Laravel Passport


Now let’s install Laravel Passport as well by running the following command.

composer require laravel/passport

Step 3 — Migrate Database


After Passport service provider registers, we require to run the migration command,
after running the migration command you will get several new tables in the
database. So, let’s run below command:

$ php artisan migrate

Create a User table.

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;

class CreateUsersTable extends Migration


{

public function up()

{
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();

});

public function down()


{

Schema::dropIfExists(‘users’);

At .env file we have to manage database configuration.

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

Step 4 — Passport Configuration at our project


In this step, we have to do the configuration on three place Model, Service provider, and
config/auth.php file.
So you have to just follow change on that file.

In User model : we added Laravel\Passport\HasApiTokens trait,

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable


{

use HasApiTokens, Notifiable;

protected $fillable = [

‘name’, ‘email’, ‘password’,

];
protected $hidden = [

‘password’, ‘remember_token’,

];
}

In app/Providers/AuthServiceProvider.php call Passport::routes

<?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 = [

‘App\Model’ => ‘App\Policies\Modelpolicy’


];

Public function boot()


{
$this->registerPolicies();

passport::routes();
}}

In auth.php, we added an API auth configuration.

<?php
return [

‘defaults’ => [
‘guard’ => ‘web’,
‘passwords’ => ‘users’,
],

‘guards’ => [
‘web’ => [

‘driver’ => ‘session’,


‘provider’ => ‘users’,
],

‘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

‘driver’ => ‘eloquent’,


‘model’ => App\User::class,

],
],
‘password’ => [

‘users’ => [
‘provider’ => ‘users’,

‘table’ => ‘password_resets’,


‘expire’ => 60,
],

],
];

Step 6 — Set API routes


Create all our routes in routes/api.php.

<?php
use Illuminate\Http\Request;
Route::group([

‘prefix’ => ‘auth’


], function () {

Route::post(‘login’, ‘Auth\AuthController@login’)-
>name(‘login’);
Route::post(‘register’, ‘Auth\AuthController@register’);
Route::group([

‘middleware’ => ‘auth:api’


], function() {
Route::get(‘logout’, ‘Auth\AuthController@logout’);

Route::get(‘user’, ‘Auth\AuthController@user’);
});

});

Step 7 — Create Controller


https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 7/19
10/18/23, 2:36 PM Make an OAuth2 server using Laravel Passport | by Successive Digital | Successive Digital | Medium

Now we need to create AuthController. Run the following command.

$ php artisan make:controller Auth/AuthController

Then, open AuthController.php and add this code.

In this code, we make 3 functions.

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([

‘message’ => ‘Unauthorized’

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,

‘token_type’ => ‘Bearer’,


‘expires_at’ => Carbon::parse(
$tokenResult->token->expires_at

)->toDateTimeString()
]);

}
public function register(Request $request)
{

$request->validate([
‘fName’ => ‘required|string’,
‘lName’ => ‘required|string’,

‘email’ => ‘required|string|email|unique:users’,


‘password’ => ‘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([

‘message’ => ‘Successfully created user!’


], 201);
}
https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 9/19
10/18/23, 2:36 PM Make an OAuth2 server using Laravel Passport | by Successive Digital | Successive Digital | Medium

public function logout(Request $request)


{

$request->user()->token()->revoke();
return response()->json([
‘message’ => ‘Successfully logged out’

}
public function user(Request $request)

{
return response()->json($request->user());
}

Step 8 — Now Adding CORS Middleware


Run the following command to create a new Middleware.

$ php artisan make:middleware Cors

<?php
namespace App\Http\Middleware;
use Closure;

class Cors
{

Public function handle($request, Closure $next)


{
return $next($request)

->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

Step 9 — Register new middleware in app/Http/Kernal.php.

<?php
namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;


class Kernel extends HttpKernel
{
protected $middleware = [

\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,
];
}

Finally, Run the following command to run.

$ php artisan passport:install


$ php artisan serve

Tests
Now time to test the whole things are working properly or not, if you get an error
please follow all these steps again.

We are simply tested by rest-client tools.

For Register New Users

Sending First Name, Last Name, Email and Password in POST requests.

Now log in with your register email and password.

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.

Servers Laravel PHP Framework

Follow

Written by Successive Digital


242 Followers · Editor for Successive Digital

A next-gen digital transformation company that helps enterprises transform business through disruptive
strategies & agile deployment of innovative solutions.

More from Successive Digital and Successive Digital

https://medium.com/successivetech/make-an-oauth2-server-using-laravel-passport-73f7b22d30 12/19

You might also like