The Practical orientation of Laravel Passport and Postman

05 Apr, 2020

If you want to develop API on Laravel, the Laravel Passport is one of the best choices for authentication. Today, I will show you practically how to install passport with laravel and then integrate on the Postman.

How to install Passport

To install passport on laravel, run the following command-

composer require laravel/passport

Then, run-

php artisan migrate

And finally, run-

php artisan passport:install

Adjustment your settings

To adjust your passport settings on laravel, first, go to the App\user model and add the HasApiTokens trait by importing the namespace Laravel\Passport\HasApiTokens.

Your model will be looks like that-

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}

Then, go to AuthServiceProvider and add Passport::routes to the boot() method. It will be like this-

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

Finally, go to config/auth.php and change driver value of api to passport. It will be like this-

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

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

Code Implementation

Now, let's write some code for that.

Define your routes

To define routes, go to api.php file and add following routes-

Route::post('/join', '[email protected]')->name('auth.join.store');
Route::post('/login', '[email protected]')->name('auth.login.store');

// This route group is protected. It cannot be accessible without login. 
Route::group(['middleware' => 'auth:api'], function() {
    Route::get('logout', '[email protected]')->name('auth.logout');
});

Complete actions in the Controller

JoinController

namespace App\Http\Controllers\Api;

use App\User;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\JoinStoreRequest;

class JoinController extends Controller
{
    public function store(JoinStoreRequest $request)
    {
        $validatedData = $request->validated();

        $validatedData['password'] = bcrypt($validatedData['password']);

        $user = User::create($validatedData);

        return response()->json([
            "message" => "User created."
        ]);
    }
}

store() method in the LoginController.

public function store(LoginStoreRequest $request)
    {
        $credentials = $request->validated();

        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);

        $user = $request->user();
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;
        $token->expires_at = Carbon::now()->addMonth(3);
        $token->save();

        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);
    }

Notice that, I have used Request here for form validation. If you want to know more, check here

logout() method in LoginController.

public function logout(Request $request)
    {
        $request->user()->token()->revoke();

        return response()->json([
            'message' => 'Successfully logged out'
        ]);
    }

Use Postman to Test.

To test the API, first of all, run-

php artisan serve

Now, I will use the postman. First of all, open the postman and create a new POST request and add the following data.

http://127.0.0.1:8000/api/join

It will be like this-

It will create a new user.

Login a User.

To login a user, create another POST request that will be like this-

http://127.0.0.1:8000/api/login

If you provide the right credential, it will return the access_token for you for accessing the protected route.

Now, let's access a protected route that required login to access. For example, logout route, in order to access the logout route, you must need to be logged in.

Let's create another GET request for logout.

http://127.0.0.1:8000/api/logout

Now, if I hit the URL, I will get the following error message.

{
    "message": "Unauthenticated."
}

It's very obvious that we need to be logged in to access this route.

Make you Logged in via access token

To make you logged in, you need to pass the access token that you have received during logged in successfully.

Now go to

  • Authorization tab > Choose Bearer Token from Type dropdown
  • And finally place the token.

It will be like this-

After providing the right access token, if you hit the URL, now you should able to get the success message like so-

{
    "message": "Successfully logged out"
}

The output will be like so-

Testing via PHP Unit.

If you want to test via PHP Unit, then follow the official documentation.

Feel free to ask me further if you have any queries.

Thank you. :)

Hello. I’m Thouhedul Islam. Some people also know me as Suchi.

I am a Full-stack Developer. I love to play with PHP specially Laravel, JavaScript, MySql and latest web technology. Currently I am working for CartX as my day time job.

At night I love to solve problem for community. I am quite active at Laracasts