Postman Auth for Laravel: API and web

Dec 28, 2021 3 minutes read
Laravel and Postman logos

Postman is a great tool for testing app routes. It is designed mostly for testing stateless APIs, but lets check how to access Laravel web routes protected by session driver (cookie based authentication).

To achieve that we will create a simple console command. This command will take one mandatory argument: guard (api or web). For api it will generate Laravel Sanctum API token, and for web it will create pre-requests scripts for Postman (with cookies and session included). The final usage of that command would be it:

# generates token for auth:api
php artisan dev:postman api

# generates script for auth:web
php artisan dev:postman web

Create command

php artisan make:command DevPostman

Copy/Paste command

<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Contracts\Http\Kernel as HttpKernel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

class DevPostmanCommand extends Command
{
    protected $signature = 'dev:postman {guard} {user?}';
    protected $description = 'Generating access for Postman.';

    public function handle()
    {
        if (!App::environment('local')) {
            $this->warn("It works only in local environment.");
            return 1;
        }
        if (!User::query()->count()) {
            $this->warn("Users table is empty.");
            return 1;
        }

        $user = $this->argument('user')
            ? User::query()->findOrFail($this->argument('user'))
            : User::query()->firstOrFail()
        ;
        
        if ($this->argument('guard') === "api") {
            $this->output->writeln($user->createToken('test')->plainTextToken);
            return 0;
        }

        Route::get('/dev-login', function () use ($user) {
            Auth::login($user);
            return response("Hello mevelix.");
        })->middleware('web');

        $request = Request::create('/dev-login');
        $kernel = app()->make(HttpKernel::class);
        $response = $kernel->handle($request);
        $cookies = $response->headers->getCookies('array');
        $cookie1 = $cookies[""]["/"]['laravel_session'];
        $cookie2 = $cookies[""]["/"]['XSRF-TOKEN'];
        $laravelSession = $cookie1->getValue();
        $xsrfToken = $cookie2->getValue();

        $result = '
            pm.request.addHeader({key: "Cookie", value: "laravel_session='.$laravelSession.'"});
            pm.request.addHeader({key: "X-XSRF-TOKEN", value: "'.$xsrfToken.'"});
        ';

        $this->output->writeln($result);
        return 0;
    }
}

Accessing web protected routes in Postman

We need to update pre-requests scripts in Postman collection. It means all requests send from Postman will attach Authorization headers and cookies this is because routes defined in web.php are by default in web middleware and they need that to retrieve the user.

php artisan dev:postman web
# generates long script
pm.request.addHeader({key: "Cookie", value: "laravel_session=VeryLongKey..."});
pm.request.addHeader({key: "X-XSRF-TOKEN", value: "VeryLongKey..."});

In Pre-requests Scripts tab paste the command output and click “Update”

postman pre requests scripts

And here it is. Since now all requests will be decorated with cookies and session.

Accessing api protected routes in Postman

php artisan dev:postman api 1
# generates token for user: 1
|gRoIvs9SUKNbxY8W5nEc05URAM

In Authorization tab select Bearer token, paste the token and click Update

bearer token authentication in postman

Summary

With this command you can use Postman even for secured endpoints in the web middleware. But remember that usually any asynchronous requests should be created in api middleware or as long as stateless endpoint is enough.

The above command should only be used for development purposes, never in a staging or production environment. Remember that in order to test the application, it is always better to do automated testing  (e.g. http or e2e).

Disclaimer: The opinions expressed here are my own and do not necessarily represent those of current or past employers.
Comments (0)