feat(auth): implement token expiration for personal access tokens and update tests

This commit is contained in:
2026-07-21 10:36:40 -03:00
parent 0f36c3402b
commit c3f54c79cb
4 changed files with 30 additions and 2 deletions

View File

@@ -35,6 +35,8 @@ SESSION_ENCRYPT=false
SESSION_PATH=/ SESSION_PATH=/
SESSION_DOMAIN=null SESSION_DOMAIN=null
SANCTUM_EXPIRATION=720
BROADCAST_CONNECTION=log BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local FILESYSTEM_DISK=local
QUEUE_CONNECTION=database QUEUE_CONNECTION=database

View File

@@ -26,7 +26,12 @@ class LoginController extends Controller
]); ]);
} }
$token = $user->createToken('api-token')->plainTextToken; $expirationMinutes = (int) config('sanctum.expiration');
$token = $user->createToken(
'api-token',
['*'],
now()->addMinutes($expirationMinutes),
)->plainTextToken;
return response()->json([ return response()->json([
'message' => 'Sesion iniciada correctamente.', 'message' => 'Sesion iniciada correctamente.',

View File

@@ -50,7 +50,7 @@ return [
| |
*/ */
'expiration' => null, 'expiration' => (int) env('SANCTUM_EXPIRATION', 720),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------

View File

@@ -34,6 +34,12 @@ class LoginControllerTest extends TestCase
$this->assertIsString($response->json('token')); $this->assertIsString($response->json('token'));
$this->assertNotEmpty($response->json('token')); $this->assertNotEmpty($response->json('token'));
$accessToken = $user->tokens()->sole();
$this->assertTrue(
$accessToken->expires_at->equalTo(
$accessToken->created_at->copy()->addMinutes(config('sanctum.expiration'))
)
);
$this->withHeader('Authorization', 'Bearer '.$response->json('token')) $this->withHeader('Authorization', 'Bearer '.$response->json('token'))
->getJson('/api/me') ->getJson('/api/me')
@@ -42,6 +48,21 @@ class LoginControllerTest extends TestCase
->assertJsonPath('email', 'grace@example.com'); ->assertJsonPath('email', 'grace@example.com');
} }
public function test_personal_access_tokens_expire_after_twelve_hours(): void
{
$this->travelTo(now()->startOfSecond());
$user = User::factory()->create();
$token = $user->createToken('api-token')->plainTextToken;
$this->travel(12)->hours();
$this->travel(1)->minutes();
$this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/me')
->assertUnauthorized();
}
public function test_it_rejects_access_to_the_current_user_endpoint_without_a_token(): void public function test_it_rejects_access_to_the_current_user_endpoint_without_a_token(): void
{ {
$this->getJson('/api/me')->assertUnauthorized(); $this->getJson('/api/me')->assertUnauthorized();