Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
8 changes: 7 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,19 @@
"illuminate/encryption": "^11.35|^12.0",
"illuminate/http": "^11.35|^12.0",
"illuminate/support": "^11.35|^12.0",
"league/oauth2-server": "^9.2",
"league/oauth2-server": "dev-master-token-revocation-introspection",
"php-http/discovery": "^1.20",
"phpseclib/phpseclib": "^3.0",
"psr/http-factory-implementation": "*",
"symfony/console": "^7.1",
"symfony/psr-http-message-bridge": "^7.1"
},
"repositories": [
{
"type": "vcs",
"url": "https://github.com/hafezdivandari/oauth2-server"
}
],
"require-dev": {
"mockery/mockery": "^1.6",
"orchestra/testbench": "^9.9|^10.0",
Expand Down
16 changes: 16 additions & 0 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,22 @@
]);
}

if (Passport::$tokenRevocationEnabled) {
Route::post('/revoke', [
'uses' => 'RevokeTokenController',
'as' => 'revoke',
'middleware' => 'throttle',
]);
}

if (Passport::$tokenIntrospectionEnabled) {
Route::post('/introspect', [
'uses' => 'IntrospectTokenController',
'as' => 'introspect',
'middleware' => 'throttle',
]);
}

$guard = config('passport.guard', null);

Route::middleware(['web', $guard ? 'auth:'.$guard : 'auth'])->group(function () {
Expand Down
33 changes: 33 additions & 0 deletions src/Http/Controllers/IntrospectTokenController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace Laravel\Passport\Http\Controllers;

use League\OAuth2\Server\TokenServer;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\HttpFoundation\Response;

class IntrospectTokenController
{
use ConvertsPsrResponses, HandlesOAuthErrors;

/**
* Create a new controller instance.
*/
public function __construct(
protected TokenServer $server,
) {
}

/**
* Introspect a token.
*/
public function __invoke(ServerRequestInterface $psrRequest, ResponseInterface $psrResponse): Response
{
return $this->withErrorHandling(
fn () => $this->convertResponse(
$this->server->respondToTokenIntrospectionRequest($psrRequest, $psrResponse)
)
);
}
}
33 changes: 33 additions & 0 deletions src/Http/Controllers/RevokeTokenController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace Laravel\Passport\Http\Controllers;

use League\OAuth2\Server\TokenServer;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\HttpFoundation\Response;

class RevokeTokenController
{
use ConvertsPsrResponses, HandlesOAuthErrors;

/**
* Create a new controller instance.
*/
public function __construct(
protected TokenServer $server,
) {
}

/**
* Revoke a token.
*/
public function __invoke(ServerRequestInterface $psrRequest, ResponseInterface $psrResponse): Response
{
return $this->withErrorHandling(
fn () => $this->convertResponse(
$this->server->respondToTokenRevocationRequest($psrRequest, $psrResponse)
)
);
}
}
26 changes: 26 additions & 0 deletions src/Passport.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@ class Passport
*/
public static bool $passwordGrantEnabled = false;

/**
* Indicates if the token introspection is enabled.
*/
public static bool $tokenIntrospectionEnabled = false;

/**
* Indicates if the token revocation is enabled.
*/
public static bool $tokenRevocationEnabled = false;

/**
* The default scope.
*/
Expand Down Expand Up @@ -191,6 +201,22 @@ public static function enablePasswordGrant(): void
static::$passwordGrantEnabled = true;
}

/**
* Enable the token introspection.
*/
public static function enableTokenIntrospection(): void
{
static::$tokenIntrospectionEnabled = true;
}

/**
* Enable the token revocation.
*/
public static function enableTokenRevocation(): void
{
static::$tokenRevocationEnabled = true;
}

/**
* Set the default scope(s). Multiple scopes may be an array or specified delimited by spaces.
*
Expand Down
16 changes: 16 additions & 0 deletions src/PassportServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
use League\OAuth2\Server\Grant\RefreshTokenGrant;
use League\OAuth2\Server\ResourceServer;
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
use League\OAuth2\Server\TokenServer;

class PassportServiceProvider extends ServiceProvider
{
Expand Down Expand Up @@ -116,6 +117,7 @@ public function register(): void
$this->registerResponseBindings();
$this->registerAuthorizationServer();
$this->registerResourceServer();
$this->registerTokenServer();
$this->registerGuard();
}

Expand Down Expand Up @@ -278,6 +280,20 @@ protected function registerResourceServer(): void
));
}

/**
* Register the token server.
*/
protected function registerTokenServer(): void
{
$this->app->singleton(TokenServer::class, fn ($container) => new TokenServer(
$container->make(Bridge\ClientRepository::class),
$container->make(Bridge\AccessTokenRepository::class),
$container->make(Bridge\RefreshTokenRepository::class),
$this->makeCryptKey('public'),
Passport::tokenEncryptionKey($container->make('encrypter'))
));
}

/**
* Create a CryptKey instance.
*/
Expand Down
129 changes: 129 additions & 0 deletions tests/Feature/TokenIntrospectionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?php

namespace Laravel\Passport\Tests\Feature;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Contracts\Auth\Authenticatable;
use Laravel\Passport\Client;
use Laravel\Passport\Database\Factories\ClientFactory;
use Laravel\Passport\Passport;
use Orchestra\Testbench\Concerns\WithLaravelMigrations;
use Workbench\Database\Factories\UserFactory;

class TokenIntrospectionTest extends PassportTestCase
{
use WithLaravelMigrations;

protected function setUp(): void
{
Passport::enableTokenIntrospection();

parent::setUp();

Passport::tokensCan([
'create' => 'Create',
'read' => 'Read',
'update' => 'Update',
'delete' => 'Delete',
]);

Passport::authorizationView(fn ($params) => $params);
}

public function testIntrospectToken()
{
$client = ClientFactory::new()->create();
$user = UserFactory::new()->create();

$token = $this->requestToken($user, $client);

$json = $this->post('/oauth/introspect', [
'token' => $token['access_token'],
'client_id' => $client->getKey(),
'client_secret' => $client->plainSecret,
])->assertOk()->json();

$jwt = JWT::decode($token['access_token'], new Key(file_get_contents(self::PUBLIC_KEY), 'RS256'));

$this->assertTrue($json['active']);
$this->assertSame('create read delete', $json['scope']);
$this->assertSame($client->getKey(), $json['client_id']);
$this->assertSame('Bearer', $json['token_type']);
$this->assertEquals($user->getAuthIdentifier(), $json['sub']);
$this->assertArrayHasKey('aud', $json);
$this->assertSame($jwt->jti, $json['jti']);
$this->assertSame((int) $jwt->exp, $json['exp']);
$this->assertSame((int) $jwt->iat, $json['iat']);
$this->assertSame((int) $jwt->nbf, $json['nbf']);

$json = $this->post('/oauth/introspect', [
'token' => $token['refresh_token'],
'client_id' => $client->getKey(),
'client_secret' => $client->plainSecret,
])->assertOk()->json();

$this->assertTrue($json['active']);
$this->assertSame('create read delete', $json['scope']);
$this->assertSame($client->getKey(), $json['client_id']);
$this->assertEquals($user->getAuthIdentifier(), $json['sub']);
$this->assertArrayHasKey('jti', $json);
$this->assertEqualsWithDelta(31536000, $json['exp'] - time(), 5);
}

public function testInvalidClient(): void
{
$client1 = ClientFactory::new()->create();
$client2 = ClientFactory::new()->create();
$user = UserFactory::new()->create();

$token = $this->requestToken($user, $client1);

$this->assertFalse($this->post('/oauth/introspect', [
'token' => $token['access_token'],
'client_id' => $client2->getKey(),
'client_secret' => $client2->plainSecret,
])->assertOk()->json('active'));

$this->assertTrue($this->post('/oauth/introspect', [
'token' => $token['access_token'],
'client_id' => $client1->getKey(),
'client_secret' => $client1->plainSecret,
])->assertOk()->json('active'));

$this->assertFalse($this->post('/oauth/introspect', [
'token' => $token['refresh_token'],
'client_id' => $client2->getKey(),
'client_secret' => $client2->plainSecret,
])->assertOk()->json('active'));

$this->assertTrue($this->post('/oauth/introspect', [
'token' => $token['refresh_token'],
'client_id' => $client1->getKey(),
'client_secret' => $client1->plainSecret,
])->assertOk()->json('active'));
}

private function requestToken(Authenticatable $user, Client $client)
{
$this->actingAs($user, 'web');

$authToken = $this->get('/oauth/authorize?'.http_build_query([
'client_id' => $client->getKey(),
'redirect_uri' => $redirect = $client->redirect_uris[0],
'response_type' => 'code',
'scope' => 'create read delete',
]))->assertOk()->json('authToken');

$redirectUrl = $this->post('/oauth/authorize', ['auth_token' => $authToken])->headers->get('Location');
parse_str(parse_url($redirectUrl, PHP_URL_QUERY), $params);

return $this->post('/oauth/token', [
'grant_type' => 'authorization_code',
'client_id' => $client->getKey(),
'client_secret' => $client->plainSecret,
'redirect_uri' => $redirect,
'code' => $params['code'],
])->assertOK()->json();
}
}
Loading