Vikas Chauhan, Khagesh Agrawal
Make an OAuth2 server using Laravel Passport
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 a native OAuth 2 server for Laravel apps. Laravel Passport package comes with a database migrations, routes and middleware to ultimately create an authorisation server that will return access tokens to allow access to server 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:
- NPM installed on your local machine.
- PHP 7 or later installed locally.
- Composer installed on your local machine.
- 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 the directory.
First of all, install 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 |
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 terminal.
$ php artisan serve |
Now, you get http://127.0.0.1:8000 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 run migration command you will get several new tables in the database. So, let’s run below command:
$ php artisan migrate |
Create a Users table.
<?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 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; 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 API auth configuration.
<?php return [ ‘defaults’ => [ ‘guard’ => ‘web’, ‘passwords’ => ‘users’, ], ‘guards’ => [ ‘web’ => [ ‘driver’ => ‘session’, ‘provider’ => ‘users’, ], ‘api’ => [ ‘driver’ => ‘passport’, ‘provider’ => ‘users’, ], ], ‘providers’ => [ ‘users’ => [ ‘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.
<?phpuse 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
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.
- Register Users
- Login users
- 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’ ],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); } 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’); }} |
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::class, \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 thing is 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 registered email and password.
When you log in with your registered email and password, you get a token. Either you can store this token in the local storage, or in the oauth_access_tokens table.
We will be sending GET request to your URL and we need to send token as Authorization Header.
Conclusion
Above way we can do API authentication in Laravel Application with 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.