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

[9.x] Initial support for multiple providers #1220

Merged
merged 16 commits into from
Apr 28, 2020
Merged
Show file tree
Hide file tree
Changes from 8 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
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jobs:
coverage: none

- name: Install dependencies
run: composer require "illuminate/contracts=${{ matrix.laravel }}" --prefer-dist --no-interaction --no-suggest
run: composer require "illuminate/contracts=${{ matrix.laravel }}" --prefer-dist --no-interaction

- name: Execute tests
run: vendor/bin/phpunit --verbose
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public function up()
$table->unsignedBigInteger('user_id')->nullable()->index();
$table->string('name');
$table->string('secret', 100)->nullable();
$table->string('provider')->nullable();
$table->text('redirect');
$table->boolean('personal_access_client');
$table->boolean('password_client');
Expand Down
20 changes: 14 additions & 6 deletions src/Bridge/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,30 @@ class Client implements ClientEntityInterface
*/
protected $identifier;

/**
* The client's provider.
*
* @var string
*/
public $provider;

/**
* Create a new client instance.
*
* @param string $identifier
* @param string $name
* @param string $redirectUri
* @param bool $isConfidential
* @return void
* @param string $identifier
* @param string $name
* @param string $redirectUri
* @param bool $isConfidential
* @param string|null $provider
*/
public function __construct($identifier, $name, $redirectUri, $isConfidential = false)
public function __construct($identifier, $name, $redirectUri, $isConfidential = false, $provider = null)
{
$this->setIdentifier((string) $identifier);

$this->name = $name;
$this->isConfidential = $isConfidential;
$this->redirectUri = explode(',', $redirectUri);
$this->provider = $provider;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Bridge/ClientRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function getClientEntity($clientIdentifier)
}

return new Client(
$clientIdentifier, $record->name, $record->redirect, $record->confidential()
$clientIdentifier, $record->name, $record->redirect, $record->confidential(), $record->provider
);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Bridge/UserRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function __construct(HashManager $hasher)
*/
public function getUserEntityByUserCredentials($username, $password, $grantType, ClientEntityInterface $clientEntity)
{
$provider = config('auth.guards.api.provider');
$provider = $clientEntity->provider ?: config('auth.guards.api.provider');

if (is_null($model = config('auth.providers.'.$provider.'.model'))) {
throw new RuntimeException('Unable to determine authentication model from configuration.');
Expand Down
13 changes: 12 additions & 1 deletion src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Laravel\Passport;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class Client extends Model
{
Expand Down Expand Up @@ -49,7 +50,7 @@ class Client extends Model
public function user()
{
return $this->belongsTo(
config('auth.providers.'.config('auth.guards.api.provider').'.model')
config('auth.providers.'.$this->provider ?: config('auth.guards.api.provider').'.model')
);
}

Expand Down Expand Up @@ -102,4 +103,14 @@ public function confidential()
{
return ! empty($this->secret);
}

/**
* Get the client's provider.
*
* @return mixed
*/
public function getProvider()
{
return $this->provider ? Auth::createUserProvider($this->provider) : null;
}
}
29 changes: 16 additions & 13 deletions src/ClientRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,21 +101,23 @@ public function personalAccessClient()
/**
* Store a new client.
*
* @param int $userId
* @param string $name
* @param string $redirect
* @param bool $personalAccess
* @param bool $password
* @param bool $confidential
* @param int $userId
* @param string $name
* @param string $redirect
* @param string|null $provider
* @param bool $personalAccess
* @param bool $password
* @param bool $confidential
* @return \Laravel\Passport\Client
*/
public function create($userId, $name, $redirect, $personalAccess = false, $password = false, $confidential = true)
public function create($userId, $name, $redirect, $provider = null, $personalAccess = false, $password = false, $confidential = true)
{
$client = Passport::client()->forceFill([
'user_id' => $userId,
'name' => $name,
'secret' => ($confidential || $personalAccess) ? Str::random(40) : null,
'redirect' => $redirect,
'provider' => $provider,
'personal_access_client' => $personalAccess,
'password_client' => $password,
'revoked' => false,
Expand All @@ -136,7 +138,7 @@ public function create($userId, $name, $redirect, $personalAccess = false, $pass
*/
public function createPersonalAccessClient($userId, $name, $redirect)
{
return tap($this->create($userId, $name, $redirect, true), function ($client) {
return tap($this->create($userId, $name, $redirect, null, true), function ($client) {
$accessClient = Passport::personalAccessClient();
$accessClient->client_id = $client->id;
$accessClient->save();
Expand All @@ -146,14 +148,15 @@ public function createPersonalAccessClient($userId, $name, $redirect)
/**
* Store a new password grant client.
*
* @param int $userId
* @param string $name
* @param string $redirect
* @param int $userId
* @param string $name
* @param string $redirect
* @param string|null $provider
* @return \Laravel\Passport\Client
*/
public function createPasswordGrantClient($userId, $name, $redirect)
public function createPasswordGrantClient($userId, $name, $redirect, $provider = null)
{
return $this->create($userId, $name, $redirect, false, true);
return $this->create($userId, $name, $redirect, $provider, false, true);
}

/**
Expand Down
13 changes: 11 additions & 2 deletions src/Console/ClientCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class ClientCommand extends Command
{--password : Create a password grant client}
{--client : Create a client credentials grant client}
{--name= : The name of the client}
{--provider= : The name of the provider}
{--redirect_uri= : The URI to redirect to after authorization }
{--user_id= : The user ID the client should be assigned to }
{--public : Create a public client (Auth code grant type only) }';
Expand Down Expand Up @@ -83,8 +84,16 @@ protected function createPasswordClient(ClientRepository $clients)
config('app.name').' Password Grant Client'
);

$providers = array_keys(config('auth.providers'));

$provider = $this->option('provider') ?: $this->choice(
'What provider should be used?',
$providers,
in_array('users', $providers) ? 'users' : null
);

$client = $clients->createPasswordGrantClient(
null, $name, 'http://localhost'
null, $name, 'http://localhost', $provider
);

$this->info('Password grant client created successfully.');
Expand Down Expand Up @@ -136,7 +145,7 @@ protected function createAuthCodeClient(ClientRepository $clients)
);

$client = $clients->create(
$userId, $name, $redirect, false, false, ! $this->option('public')
$userId, $name, $redirect, null, false, false, ! $this->option('public')
);

$this->info('New client created successfully.');
Expand Down
3 changes: 2 additions & 1 deletion src/Console/InstallCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ class InstallCommand extends Command
*/
public function handle()
{
$provider = in_array('users', array_keys(config('auth.providers'))) ? 'users' : null;
$this->call('passport:keys', ['--force' => $this->option('force'), '--length' => $this->option('length')]);
$this->call('passport:client', ['--personal' => true, '--name' => config('app.name').' Personal Access Client']);
$this->call('passport:client', ['--password' => true, '--name' => config('app.name').' Password Grant Client']);
$this->call('passport:client', ['--password' => true, '--name' => config('app.name').' Password Grant Client', '--provider' => $provider]);
}
}
22 changes: 22 additions & 0 deletions src/Guards/TokenGuard.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,24 @@ public function __construct(ResourceServer $server,
$this->encrypter = $encrypter;
}

/**
* Determine if the requested provider matches the client's provider.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function validateProvider(Request $request)
{
$client = $this->client($request);

// If not client provider is defined, fallback to old behavior.
if ($client && empty($client->getProvider())) {
return true;
}

return $client && $this->provider == $client->getProvider();
}

/**
* Get the user for the incoming request.
*
Expand All @@ -90,6 +108,10 @@ public function __construct(ResourceServer $server,
*/
public function user(Request $request)
{
if (! $this->validateProvider($request)) {
return;
}

if ($request->bearerToken()) {
return $this->authenticateViaBearerToken($request);
} elseif ($request->cookie(Passport::cookie())) {
Expand Down
2 changes: 1 addition & 1 deletion src/Http/Middleware/CheckCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ protected function validate($psr, $scopes)
abstract protected function validateCredentials($token);

/**
* Validate token credentials.
* Validate token scopes.
*
* @param \Laravel\Passport\Token $token
* @param array $scopes
Expand Down
2 changes: 2 additions & 0 deletions tests/BridgeClientRepositoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,8 @@ class BridgeClientRepositoryTestClientStub

public $password_client = false;

public $provider = null;

public $grant_types;

public function firstParty()
Expand Down
21 changes: 21 additions & 0 deletions tests/TokenGuardTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public function test_user_can_be_pulled_via_bearer_token()
$userProvider->shouldReceive('retrieveById')->with(1)->andReturn(new TokenGuardTestUser);
$tokens->shouldReceive('find')->once()->with('token')->andReturn($token = m::mock());
$clients->shouldReceive('revoked')->with(1)->andReturn(false);
$clients->shouldReceive('findActive')->with(1)->andReturn(new TokenGuardTestClient);

$user = $guard->user($request);

Expand Down Expand Up @@ -90,13 +91,18 @@ public function test_null_is_returned_if_no_user_is_found()
$clients = m::mock(ClientRepository::class);
$encrypter = m::mock(Encrypter::class);

$clients->shouldReceive('findActive')
->with(1)
->andReturn(new TokenGuardTestClient);

$guard = new TokenGuard($resourceServer, $userProvider, $tokens, $clients, $encrypter);

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

$resourceServer->shouldReceive('validateAuthenticatedRequest')->andReturn($psr = m::mock());
$psr->shouldReceive('getAttribute')->with('oauth_user_id')->andReturn(1);
$psr->shouldReceive('getAttribute')->with('oauth_client_id')->andReturn(1);
$userProvider->shouldReceive('retrieveById')->with(1)->andReturn(null);

$this->assertNull($guard->user($request));
Expand All @@ -110,6 +116,10 @@ public function test_users_may_be_retrieved_from_cookies_with_csrf_token_header(
$clients = m::mock(ClientRepository::class);
$encrypter = new Encrypter(str_repeat('a', 16));

$clients->shouldReceive('findActive')
->with(1)
->andReturn(new TokenGuardTestClient);

$guard = new TokenGuard($resourceServer, $userProvider, $tokens, $clients, $encrypter);

$request = Request::create('/');
Expand Down Expand Up @@ -138,6 +148,10 @@ public function test_users_may_be_retrieved_from_cookies_with_xsrf_token_header(
$clients = m::mock(ClientRepository::class);
$encrypter = new Encrypter(str_repeat('a', 16));

$clients->shouldReceive('findActive')
->with(1)
->andReturn(new TokenGuardTestClient);

$guard = new TokenGuard($resourceServer, $userProvider, $tokens, $clients, $encrypter);

$request = Request::create('/');
Expand Down Expand Up @@ -270,6 +284,10 @@ public function test_csrf_check_can_be_disabled()
$clients = m::mock(ClientRepository::class);
$encrypter = new Encrypter(str_repeat('a', 16));

$clients->shouldReceive('findActive')
->with(1)
->andReturn(new TokenGuardTestClient);

$guard = new TokenGuard($resourceServer, $userProvider, $tokens, $clients, $encrypter);

Passport::ignoreCsrfToken();
Expand Down Expand Up @@ -396,4 +414,7 @@ class TokenGuardTestUser

class TokenGuardTestClient
{
public function getProvider()
{
}
}