Laravel Passport - Create REST API with authentication

Today, in this tutorial we are share with you hhow to use laravel passport authentication in your laravel application. Laravel already provide simple auth system for web. but what about APIs? APIs basically use token for authentication. when any user login thenn generate one tocken and it is use for authentication purpose. so, laravel provide Passport for APIs authentication.

How to use Passport in laravel for built RESTful APIs and how to configure in laravel application. here we are expain all things in step by step in very easy way and with example.

In this tutorial we are built following APIs service using Passpost

1. Register API
2. Login API
3. Get User Details API

Simply follow this step and you can easyly integrate Passport in your laravel application.

Step - 1 : Installation

First we need to install laravel's Passport package in your application using run following command


composer require laravel/passport

Step - 2 : Configure Pacckage

After install successfully Passport package in our application we need to set their Service Provider. so, open your config/app.php file and add following provider in it.


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

Step - 3 : Run Migration And Install

After set service provider then run migration. passport migration tables use for store client and tokens.

 
php artisan migrate

Next to you should install passport, because generate encryption keys needs to usse in create passport token.

 
php artisan passport:install

Step - 4 : Passport Configure

After done above proccess then we need to make some changes for configure passport setting.

1. In model we added HasApiTokens class of Passport,
2. In AuthServiceProvider we added "Passport::routes()",
3. In auth.php, we added api auth configuration.

1. app/User.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',
    ];
}

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

3. config/auth.php


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

Step - 5 : Create Route

Next, create following route in routes/api.php file. this route file generally use for create APIs route.


Route::post('login', 'API\PassportController@login');
Route::post('register', 'API\PassportController@register');

Route::group(['middleware' => 'auth:api'], function(){
	Route::post('get-details', 'API\PassportController@getDetails');
});

Step - 6 : Create Controller

Next, we should create one PassportController.php controller in app/Http/Controllers/API/ root.

We are create one API folder in Controllers for store all APIs controller in it.

app/Http/Controllers/API/PassportController.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 PassportController extends Controller
{

    public $successStatus = 200;

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

    /**
     * Register api
     *
     * @return \Illuminate\Http\Response
     */
    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('MyApp')->accessToken;
        $success['name'] =  $user->name;

        return response()->json(['success'=>$success], $this->successStatus);
    }

    /**
     * details api
     *
     * @return \Illuminate\Http\Response
     */
    public function getDetails()
    {
        $user = Auth::user();
        return response()->json(['success' => $user], $this->successStatus);
    }
}

Allright, our APIs creation proccess done now we are testing it. so simple run laravel app by following command


php artisan serve

Step - 7 : APIs Testing

Now, we are test all API in any API testing tool, we are use Postman for testing APIs

1. Register API

2. Login API

3. Get Detailss API

Now, we will test details api, In this api you have to set two header as listed bellow:


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

We are hope this tutorial help you....

 Prev post

Next post