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
okey metin2 pvp serverler metin2 pvp
ataşehir escort maltepe escort bostancı escort kadıköy escort maltepe escort ataşehir escort tuzla escort pendik escort ümraniye escort kartal escort
pendik escort
izmir escort izmir escort izmir escort izmir escort denizli escort antalya escort antalya escort antalya escort izmir escort izmir escort izmir escort izmir escort izmir escort
hatay escort nevsehir escort nigde escort kirikkale escort batman escort osmaniye escort kirklareli escort tokat escort rize escort adiyaman escort gumushane escort batman escort
cialis satış cialis fiyat cialis 20 mg cialis 100 mg cialis 5 mg fiyat

viagra fiyatı

viagra 100 mg fiyat

viagra sipariş

orjinal viagra

viagra satın al

izmir escort
ataşehir escort
kocaeli escort izmit escort bayan gebze escort izmit sınırsız escort escort bursa tuzla escort aydınlı escort orhanlı escort bursa escort escort bayan istanbul escort istanbul sınırsız escort istanbul bayan escort izmit escort izmit escort kocaeli escort sisli escort mecidiyekoy escort bursa escort bayan bursa görükle escort maltepe escort goztepe escort yakacik-yeni-escort bursa sınırsız escort sisli escort bayan taksim escort bursa escort porno izle sikiş izle atasehir escort antalya escort
ankara escort marmaris escort bursa escort mersin escort antalya escort izmir escort samsun escort bodrum escort çeşme escort kuşadası escort adana escort eskişehir escort gaziantep escort esenyurt escort pendik escort tuzla escort fatih escort ümraniye escort mecidiyeköy escort kartal escort bahçelievler escort bahçeşehir escort ataşehir escort bakırköy escort nişantaşı escort avcılar escort büyükçekmece escort kurtkoy escort konya escort beşiktaş escort taksim escort beylikdüzü escort malatya escort sakarya escort şişli escort maltepe escort kadıköy escort ataköy escort bostancı escort şirinevler escort bağcılar escort üsküdar escort etiler escort başaksehir escort ortaköy escort kağıthane escort sultangazi escort halkalı escort çekmeköy escort şaşkınbakkal escort mamak escort sincan escort keçiören escort çankaya escort beypazarı escort akyurt escort pursaklar escort kahramankazan escort göztepe escort alsancak escort bornova escort buca escort karabaglar escort karşıyaka escort konak escort narlıdere escort izmit escort başiskele escort kandira escort körfez escort karamürsel escort dilovası escort gölcük escort gebze escort kocaeli escort kayseri escort elazığ escort denizli escort diyarbakir escort adana escort ankara escort izmir escort antalya escort gaziantep escort kayseri escort konya escort mersin escort denizli escort kocaeli escort diyarbakır escort
bedava bahis