14

Laravel REST API Authentication using Passport

 3 years ago
source link: https://www.simplifiedcoding.net/laravel-rest-api-authentication/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Laravel REST API Authentication using Passport

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.

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.
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.
php artisan serve
Serving Laravel Project
  • 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.
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.
composer require laravel/ui
  • Then we will create auth with this command.
php artisan ui vue --auth
  • After running the above command you will see the Login and Register button in your home page.
Laravel Auth
  • Still we need some more commands to make everything work.
  • First we will install all the required node packages.
npm install
  • After installing all required node packages, run the following command.
npm run dev
  • And finally we will migrate the database, using the following command.
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.
composer require laravel/passport
  • Again migrate the database using
php artisan migrate
  • Now we need to generate required keys for passport.
php artisan passport:install

Configuring Passport

  • Open your User model class and add the following lines.
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.
<?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.
    '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.
php artisan make:controller AuthController
  • Now go inside AuthController.php that is generated and write the following code.
<?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.
<?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

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.

Checkout these tutorials as well:

  • Android Paging Library Tutorial using Retrofit
  • Dagger 2 Android Example using Retrofit : Injecting Dependency
  • Building an Android Wallpaper App with Admin Panel using Firebase
  • Android MVVM Tutorial - Build an App using MVVM Design Pattern
  • Bottom Navigation Android Example using Fragments
  • Android ViewModel using Retrofit - ✅ A Simple Tutorial

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK