Do you want to know about a proper token based authentication mechanism for your RESTful APIs? If yes, then you are at the right place. In this post we will learn about Laravel REST API Authentication using Passport.
We have built RESTful APIs, many time earlier, but we never discussed about proper AUTHENTICATION. And that is why I am writing this post.
In this post, we will create a RESTful API for Login and Signup using Laravel. So now, without wasting any more time, let’s start.
Table of Contents
Laravel REST API Authentication using Passport – Video
If you are more comfortable in watching video tutorials rather than reading a long post, then don’t worry; I have a complete step by step video playlist for this topic as well.
But if you are ok with reading the post, then let’s move ahead.
Setting Up Everything
Before getting started we need to setup our development environment. So here are the things that I will be using.
- XAMPP (You can use other tools e.g mamp, wamp as well).
- Composer (Get it by clicking on the link)
- NodeJS
- Visual Studio Code (Or basically any code editor program).
Once you have all the above mentioned things, you are good to go.
Creating a Laravel Project
Now, choose a location in you machine where you want to save your project. Open terminal or command prompt here.
- We will run the following command to create a laravel project.
1 2 3 |
composer create-project laravel/laravel MyAPIProject |
- In the above command MyAPIProject is the name of our project. You can change it if you want.
Launching the Application
- Our empty project is ready and now we can launch it locally.
- Go inside your project directory and run the following command.
1 2 3 |
php artisan serve |
- If you will go to the shown address in your browser, then you will see your laravel home page.
Setting Up Database
Once you have the project created, it is needed that you setup a database for your application.
- Go to PhpMyAdmin (localhost/phpmyadmin) and create a database.
- Now open the .env file that you have inside your project folder and make the following changes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
APP_NAME=Laravel APP_ENV=local APP_KEY=base64:u7kC40c8iedM7PcSLWc0ggvxs1Iy+UmEpVseyMtu4BY= APP_DEBUG=true APP_URL=http://localhost LOG_CHANNEL=stack DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=mywebapp DB_USERNAME=root DB_PASSWORD= DB_SOCKET=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock |
- You need to define values for DB_DATABASE, DB_USER_NAME, DB_PASSWORD and if you are using linux based system then you must define a new value DB_SOCKET as you can see above.
Creating Authentication
With Laravel it is extremely easy to make authentication, everything is already done and we just need to execute some commands.
- First we need the ui package of laravel.
1 2 3 |
composer require laravel/ui |
- Then we will create auth with this command.
1 2 3 |
php artisan ui vue --auth |
- After running the above command you will see the Login and Register button in your home page.
- Still we need some more commands to make everything work.
- First we will install all the required node packages.
1 2 3 |
npm install |
- After installing all required node packages, run the following command.
1 2 3 |
npm run dev |
- And finally we will migrate the database, using the following command.
1 2 3 |
php artisan migrate |
- Now our authentication is done and we can do signup and login in our app.
Adding Laravel Passport
- Now let’s first require laravel passport that we will be using for our APIs.
1 2 3 |
composer require laravel/passport |
- Again migrate the database using
1 2 3 |
php artisan migrate |
- Now we need to generate required keys for passport.
1 2 3 |
php artisan passport:install |
Configuring Passport
- Open your User model class and add the following lines.
1 2 3 4 5 6 7 8 9 |
use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use Notifiable, HasApiTokens; . . |
- Now we need to call Passport::routes() in our \App\Providers\AuthServiceProvider.php class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php namespace App\Providers; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Gate; use Laravel\Passport\Passport; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ // 'App\Model' => 'App\Policies\ModelPolicy', ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); Passport::routes(); // } } |
- Now come inside config/auth.php file and here we will define passport as the driver for our apis.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', 'hash' => false, ], ], |
Now passport configurations are done, and we can create our API routes. But first we will create an AuthController.
Creating Auth Controller
- First run the following command.
1 2 3 |
php artisan make:controller AuthController |
- Now go inside AuthController.php that is generated and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
<?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\User; use Illuminate\Support\Facades\Auth; class AuthController extends Controller { public function login(Request $request){ $request->validate([ 'email' => 'required|string', 'password' => 'required|string' ]); $credentials = request(['email', 'password']); if(!Auth::attempt($credentials)){ return response()->json([ 'message'=> 'Invalid email or password' ], 401); } $user = $request->user(); $token = $user->createToken('Access Token'); $user->access_token = $token->accessToken; return response()->json([ "user"=>$user ], 200); } public function signup(Request $request){ $request->validate([ 'name' => 'required|string', 'email' => 'required|string|email|unique:users', 'password' => 'required|string|confirmed' ]); $user = new User([ 'name'=>$request->name, 'email'=>$request->email, 'password'=>bcrypt($request->password) ]); $user->save(); return response()->json([ "message" => "User registered successfully" ], 201); } public function logout(Request $request){ $request->user()->token()->revoke(); return response()->json([ "message"=>"User logged out successfully" ], 200); } public function index(){ echo "Hello World"; } } |
- Now let’s create our API routes. So open routes/api.php and write the following codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::namespace('Api')->group(function(){ Route::prefix('auth')->group(function(){ Route::post('login', 'AuthController@login'); Route::post('signup', 'AuthController@signup'); }); Route::group([ 'middleware'=>'auth:api' ], function(){ Route::get('helloworld', 'AuthController@index'); Route::post('logout', 'AuthController@logout'); }); }); |
- And you are done. You can test your APIs using POSTMAN or any other REST Client.
Deploying the Project to Server
Now if you want to deploy your project to a live server then it is also very easy. Check this video how to do it.
If you need detailed explanation then you should check all the video tutorials.
Laravel REST API Authentication Source Code
Finally if you need my source code then you can get it from here.
That is all for this tutorial friends. If you are having any problem or confusion about this Laravel REST API Authentication then feel free to comment it below. Thank You