Skip to content

Commit

Permalink
Ensure device has not been logged out
Browse files Browse the repository at this point in the history
This adds a middleware to check that the password has in session is the same as the current users password.

This fixes a security issue where an attacker can keep sending requests to an API using the sanctum auth after the password has been changed.
  • Loading branch information
patrickomeara committed Aug 10, 2023
1 parent 7f4d571 commit 9392ec9
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/Http/Middleware/EnsureDeviceHasNotBeenLoggedOut.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Laravel\Sanctum\Http\Middleware;

use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Auth\Factory as AuthFactory;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureDeviceHasNotBeenLoggedOut
{
public function __construct(protected AuthFactory $auth)
{
}

/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (! $request->hasSession() || ! $request->user()) {
return $next($request);
}

if ($request->session()->get('password_hash_'.$this->auth->getDefaultDriver()) !== $request->user()->getAuthPassword()) {
$this->logout($request);

throw new AuthenticationException('Unauthenticated.', [$this->auth->getDefaultDriver()]);
}

return $next($request);
}

protected function logout(Request $request)
{
$this->auth->logoutCurrentDevice();

$request->session()->flush();
}
}
1 change: 1 addition & 0 deletions src/Http/Middleware/EnsureFrontendRequestsAreStateful.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ protected function frontendMiddleware()
\Illuminate\Session\Middleware\StartSession::class,
config('sanctum.middleware.validate_csrf_token'),
config('sanctum.middleware.verify_csrf_token', \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class),
config('sanctum.middleware.ensure_not_logged_out', EnsureDeviceHasNotBeenLoggedOut::class),
])));

array_unshift($middleware, function ($request, $next) {
Expand Down

0 comments on commit 9392ec9

Please sign in to comment.