Getting started with Laravel 5 Passport to authentication API

Getting started with Laravel 5 Passport to authentication API

There are many ways to authenticate api in Laravel like sessions, jwt tokens.

Passport is a Laravel package that came up with Laravel 5.3 to authorise the external request. For example, accessing the data using API calls from the android or IOS mobile applications.

There are some protected APIs in the application that requires access token to authenticate the request because API do not maintain session state between requests. In this example, I will let you know how to get access token after user authentication via API and how will you use the access token to access a protected resource from the API.

To get access token, you must login with user credentials within the application using API.

Laravel Installation and Passport package configuration

In this first step, You will have to setup your application. Run following command using composer to get fresh Laravel application.

composer create-project --prefer-dist laravel/laravel blog "5.5.*"

To get started with Passport, you will have to require laravel/passport package with the help of composer.

composer require laravel/passport

After successfully installing the package, you will need to register the Laravel Passport service provider in the providers array of config/app.php file.

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

After register the passport service provider, you must migrate your database because it register its own database migration directory.

Run following command to migrate the database :

php artisan migrate

This will create the tables in your database to save access token of authorized users.

Next, we will run the passport:install command to create the encryption keys that will use to generate secure access tokens.

php artisan passport:install

After running above command, add the HasApiTokens trait to the App\User model.

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

Next, edit the AuthServiceProvider and call Passport::routes method within the boot method.

app/Providers/AuthServiceProvider.php
<?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();
        //
    }
}

Finally let's update the drive in config/auth.php file.

config/auth.php
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],
Add routes

Now Passport configuration has been completed. So let's start with the passport authentication process by adding following routes for APIs.

routes/api.php
<?php

/*
|--------------------------------------------------------------------------
| 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::group(['namespace'=>'Api'], function(){

	Route::post('login', 'UserController@login');

	Route::group(['middleware' => 'auth:api'], function(){
		Route::post('user-details', 'UserController@userDetails');
	});
});
Create UserController.php within the Api directory

In this last step, We will create a directory "Api" within the app/Http/Controllers directory and create a UserController.php inside it.

app/Http/Controllers/Api/UserController.php
<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;

class UserController extends Controller
{


    /**
     * login api
     *
     * @return \Illuminate\Http\Response
     */
    public function login(){
        if(auth()->attempt(['email' => request('email'), 'password' => request('password')])){
            $token =  auth()->user()->createToken('MyApp')->accessToken;
            return response()->json(['success' => $token], 200);
        }
        else{
            return response()->json(['error'=>'Unauthorised'], 401);
        }
    }

    /**
     * User details api
     *
     * @return \Illuminate\Http\Response
     */
    public function userDetails()
    {
        $user = auth()->user(); // or you can use request()->user()
        return response()->json(['success' => $user], 200);
    }
}

Now you are ready to authenticate API using passport in Laravel.

Login API

passport login

User Details API

Now to get the user details, you will have to pass access token via header :

'headers' => [
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '.$accessToken,
]

user details

Phone: (+91) 8800417876
Noida, 201301
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort otele gelen escort sapanca escort söğütlü escort taraklı escort
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort karapürçek escort karasu escort kaynarca escort kocaali escort otele gelen escort pamukova escort sapanca escort söğütlü escort taraklı escort
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort karapürçek escort karasu escort kaynarca escort kocaali escort otele gelen escort pamukova escort sapanca escort söğütlü escort taraklı escort
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort karapürçek escort karasu escort kaynarca escort kocaali escort otele gelen escort pamukova escort sapanca escort söğütlü escort taraklı escort
sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort izmit escort sakarya escort sapanca escort sakarya escort