Laravel 6 REST API (Login & Registration) Authentication

Laravel 6 REST API (Login & Registration) Authentication

Laravel 6 REST APIs (login & registration) authentication example. This tutorial explains, how you can create restful login, registration, get user info APIs in laravel 6 with passport authentication.

This tutorial explains, how you can install passport auth in your laravel application and how you can configure passport auth with your laravel app. Also, you will learn how you can get useful information using a token with a passport auth.

Here Step by Step for creating restful APIs in laravel application with passport authentication.

Laravel 6 REST APIs with Passport Auth

Follow the below steps and create login, registration and get user information rest APIs in your laravel apps with passport auth.

  • Install Fresh Laravel Setup
  • Install Passport Packages in Laravel
  • Run Migration and Install Passport Auth
  • Passport Configuration
  • Create APIs Route
  • Create Controller & Methods
  • Conclusion

1. Install Fresh Laravel Setup

Download Laravel fresh setup using below command, Open the command prompt and type the below command:

composer create-project --prefer-dist laravel/laravel blog

2. Install Passport Package In Laravel

In this step run the below command and install passport package :

composer require laravel/passport

After successfully install laravel passport, register providers. Open config/app.php . and put the bellow code :

  // config/app.php

'providers' =>[
Laravel\Passport\PassportServiceProvider::class,
],

Before you run migration command, go to the app/providers/AppServiceProvider.php and put the two line of code inside a boot method :

 Use Schema; 
public function boot() {
Schema::defaultStringLength(191);
}

3. Run Migration and Install Passport Auth

We need to do migration using the bellow command. This command creates tables in the database :

php artisan migrate

We need to install laravel to generate passport encryption keys. This command will create the encryption keys needed to generate secure access tokens. like secret key and secret id.

php artisan passport:install

4. Laravel Passport Configuration

Configuration of some files. Next open App/User.php file and put the below code on App/User.php File

use Laravel\Passport\HasApiTokens;

use HasApiTokens,
App/User.php
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
use HasApiTokens, Notifiable;
/**
The attributes that are mass assignable.
*
@var array
/protected $fillable = ['name', 'email', 'password',];/*
The attributes that should be hidden for arrays.
*
@var array
*/
protected $hidden = [
'password', 'remember_token',
];
}

Next Register passport routes in App/Providers/AuthServiceProvider.php, Go to App/Providers/AuthServiceProvider.php and put this => Register Passport::routes(); inside of boot method :

<?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 
{ 
    /** 
     * 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(); 
    } 
}

config/auth.php

Next, go to config/auth.php and Change the API driver to the session to passport. Put this code ‘driver’ => ‘passport’, in API :


[
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],

5. Create APIs Route

In this step, we will create rest API routes in the laravel app.

Go to api.php inside route folder and create below routes here :

 Route::prefix('v1')->group(function(){
  Route::post('login', 'Api\[email protected]');
  Route::post('register', 'Api\[email protected]');
  Route::group(['middleware' => 'auth:api'], function(){
  Route::post('getUser', 'Api\[email protected]');
  });
 });

6. Create Controller

Now will create a controller name AuthController. Use the below command and create a controller :

 php artisan make:controller Api\AuthController

After that, we will create some methods in AuthController. You can see the login, registration and get user info methods in this controller.

<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\User; 
use Illuminate\Support\Facades\Auth; 
use Validator;
class AuthController extends Controller 
{
 public $successStatus = 200;
 
 public function register(Request $request) {    
 $validator = Validator::make($request->all(), 
              [ 
              'name' => 'required',
              'email' => 'required|email',
              'password' => 'required',  
              'c_password' => 'required|same:password', 
             ]);   
 if ($validator->fails()) {          
       return response()->json(['error'=>$validator->errors()], 401);                        }    
 $input = $request->all();  
 $input['password'] = bcrypt($input['password']);
 $user = User::create($input); 
 $success['token'] =  $user->createToken('AppName')->accessToken;
 return response()->json(['success'=>$success], $this->successStatus); 
}
 
  
public function login(){ 
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
   $user = Auth::user(); 
   $success['token'] =  $user->createToken('AppName')-> accessToken; 
    return response()->json(['success' => $success], $this-> successStatus); 
  } else{ 
   return response()->json(['error'=>'Unauthorised'], 401); 
   } 
}
 
public function getUser() {
 $user = Auth::user();
 return response()->json(['success' => $user], $this->successStatus); 
 }
} 
 Lets got terminal & run the command :

 php artisan serve

Now Test Laravel REST API in Postman

Laravel Register Rest API :
laravel register api
laravel register api
Login API :
laravel passport login api
laravel passport login api

Next Step, we will call getUser API, In this API you have to set two headers follows:

 
Call login or register apis put $accessToken.

‘headers’ => [
‘Accept’ => ‘application/json’,
‘Authorization’ => ‘Bearer ‘.$accessToken,

]

Pass header in login/register rest API. it is necessary to passport authentication in laravel app

Conclusion

Laravel passport – We have successfully installed a laravel passport authentication package and also configuration passport package in laravel application. Using the laravel passport package we have successfully created rest login authentication API, register API and get user info API.

You may like

  1. Laravel 6 Twitter Login Example Using Socialite Package
  2. Laravel 6 Linkedin Login Tutorial With Live Demo
  3. Login with Facebook In Laravel 6 -Example
  4. Laravel 6 Socialite Google Login Example
  5. Github Login in laravel with Example
  6. Laravel 6 Multi Auth( Authentication) Example Tutorial
  7. Laravel 6 Custom Login Registration Example Tutorial

If you have any questions or thoughts to share, use the comment form below to reach us.

One reply to Laravel 6 REST API (Login & Registration) Authentication

  1. What about refresh token?

Leave a Reply

Your email address will not be published. Required fields are marked *