Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More granular control over token validation #275

Merged
merged 5 commits into from
Apr 30, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Release Notes

## [Unreleased](https://github.com/laravel/sanctum/compare/v2.10.0...2.x)

### Added
- `Sanctum::$validateCallback` callback for more granular control over access token validation ([#275](https://github.com/laravel/sanctum/pull/275))

## [v2.10.0 (2021-04-20)](https://github.com/laravel/sanctum/compare/v2.9.4...v2.10.0)

Expand Down
25 changes: 21 additions & 4 deletions src/Guard.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,7 @@ public function __invoke(Request $request)

$accessToken = $model::findToken($token);

if (! $accessToken ||
($this->expiration &&
$accessToken->created_at->lte(now()->subMinutes($this->expiration))) ||
! $this->hasValidProvider($accessToken->tokenable)) {
if (! $this->isValidAccessToken($accessToken)) {
return;
}

Expand Down Expand Up @@ -107,4 +104,24 @@ protected function hasValidProvider($tokenable)

return $tokenable instanceof $model;
}

/**
* Determine if the provided access token is valid.
*
* @param mixed $accessToken
* @return bool
*/
protected function isValidAccessToken($accessToken): bool
{
$is_valid = $accessToken && (
($this->expiration && $accessToken->created_at->gt(now()->subMinutes($this->expiration)))
|| $this->hasValidProvider($accessToken->tokenable)
);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check doesn't read the same to me. The access token must be not null and then you specify it MUST also have an explicit expiration date. But, I don't think we required tokens to have an expiration date before this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right. I tried to inverse the statement to prevent a double negation back to valid. But in the process I did end up changing the behavior. Was more intent on keeping the tests working. It's fixed now. Hope it makes more sense this way.

Also added an early return on a missing $accessToken. Because without it we can't deduce a User so it makes sense to short-circuit there.


if (is_callable(Sanctum::$validateCallback)) {
$is_valid = (bool) (Sanctum::$validateCallback)($accessToken, $is_valid);
}

return $is_valid;
}
}
10 changes: 10 additions & 0 deletions src/Sanctum.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ class Sanctum
*/
public static $runsMigrations = true;

/**
* A callback that can add to the validation of the access token.
* Receives 2 parameters:
* - (object) The provided access token model.
* - (bool) Whether the guard deemed the access token valid.
*
* @var callable|null
*/
public static $validateCallback = null;

/**
* Set the current user for the application with the given abilities.
*
Expand Down
40 changes: 40 additions & 0 deletions tests/GuardTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Laravel\Sanctum\Guard;
use Laravel\Sanctum\HasApiTokens;
use Laravel\Sanctum\PersonalAccessToken;
use Laravel\Sanctum\Sanctum;
use Laravel\Sanctum\SanctumServiceProvider;
use Mockery;
use Orchestra\Testbench\TestCase;
Expand Down Expand Up @@ -230,6 +231,45 @@ public function test_authentication_is_successful_with_token_if_user_provider_is
$this->assertInstanceOf(EloquentUserProvider::class, $requestGuard->getProvider());
}

public function test_authentication_fails_if_callback_returns_false()
{
$this->loadLaravelMigrations(['--database' => 'testbench']);
$this->artisan('migrate', ['--database' => 'testbench'])->run();

config(['auth.guards.sanctum.provider' => 'users']);
config(['auth.providers.users.model' => User::class]);

$factory = $this->app->make(AuthFactory::class);
$requestGuard = $factory->guard('sanctum');

$request = Request::create('/', 'GET');
$request->headers->set('Authorization', 'Bearer test');

$user = User::forceCreate([
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',
'remember_token' => Str::random(10),
]);

$token = PersonalAccessToken::forceCreate([
'tokenable_id' => $user->id,
'tokenable_type' => get_class($user),
'name' => 'Test',
'token' => hash('sha256', 'test'),
]);

Sanctum::$validateCallback = function ($accessToken, bool $is_valid) {
$this->assertInstanceOf(PersonalAccessToken::class, $accessToken);
$this->assertTrue($is_valid);

return false;
};

$user = $requestGuard->setRequest($request)->user();
$this->assertNull($user);
}

protected function getPackageProviders($app)
{
return [SanctumServiceProvider::class];
Expand Down