How to log authentication attempt using Laravel Passport (5.3)

Viewed 2430

We have a web-app consuming a Laravel REST API back-end via Ang 1.6.5 front-end.

I'm looking to log 3 different authentication request outcomes: 1. Succesful authentication. 2. Valid user account, invalid password. 3. Invalid user account.

I can't seem to figure out how to go about hooking into Passport's auth process.

I've attempted with some custom Middleware, also a custom Provider. Neither worked, though it could have been the implementation.

What's the correct approach here?

Thanks.

2 Answers

I spend my evening figuring how to do this myself in Laravel 6.

  1. I create a middleware called AccessLogMiddleware
<?php

namespace App\Http\Middleware;

use App\AccessLog;
use App\User;
use Carbon\Carbon;
use Closure;
use Illuminate\Support\Facades\Hash;


class AccessLogMiddleware
{
    public function handle($request, Closure $next)
    {
        if ($request->route()->getName() === 'passport.token'){ //this the route name of the API endpoint to get the token
            $accessLog = new AccessLog([
                'username' => $request->username,
                'ip_address' => $request->getClientIp(),
                'login_time' => Carbon::now(),
            ]);

            $user = User::query()->where([
                'username' => $request->username,
            ])->first();

            if ($user) {
                $accessLog->is_valid_username = 1;
                if (Hash::check($request->password, $user->password)){
                    $accessLog->is_valid_password = 1;
                }
            };

            $accessLog->save();
        }
        return $next($request);
    }
}
  1. Registered it to Http\Kernel
protected $routeMiddleware = [
     'access_log' => \App\Http\Middleware\AccessLogMiddleware::class,
     ....
]
  1. Apply the middleware to the Passport::routes(), in my case it's in the AuthServiceProvider:
Passport::routes(null, ['middleware' => 'access_log']);

You're all set!

Without re-writing the vendor source, you could look into After middleware, then just catch it before it returns. It's not the most elegant solution, but it might suffice.

Sorry this isn't a complete solution, I don't have enough points to leave a comment.

Related