Answer the question
In order to leave comments, you need to log in
How to catch user login via token (laravel passport)?
It is necessary that if the user enters through the token stored in the browser, also catch his entrance.
I am using laravel passport and backend access via api.
To catch the moment when a user logs in with a password, it is enough to use the regular Laravel Passport event and add the code
'Laravel\Passport\Events\AccessTokenCreated' => [
'App\Listeners\onLogin,
],
...
Passport::routes(null, ['middleware' => 'access_log']);
<?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);
}
}
protected $routeMiddleware = [
'access_log' => \App\Http\Middleware\AccessLogMiddleware::class,
....
]
Passport::routes(null, ['middleware' => 'access_log']);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question