Skip to content

Instantly share code, notes, and snippets.

@jeffsrepoaccount
Created April 10, 2018 17:56
Show Gist options
  • Save jeffsrepoaccount/11579df0efa890af5ae9ebcc8c727bdd to your computer and use it in GitHub Desktop.
Save jeffsrepoaccount/11579df0efa890af5ae9ebcc8c727bdd to your computer and use it in GitHub Desktop.
Sub-class of League\OAuth2\Server\Grant\AbstractGrant that overrides League\OAuth2\Server\Grant\ClientCredentialsGrant so that clients with an assigned user_id using this grant can have that claim inserted into the JWT.
<?php namespace My\Space;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\UserEntityInterface;
use Laravel\Passport\ClientRepository;
use Laravel\Passport\Bridge\User;
use League\OAuth2\Server\RequestEvent;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Grant\AbstractGrant;
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* Client credentials grant class.
*/
class ClientCredentialsGrant extends AbstractGrant
{
/**
* {@inheritdoc}
*/
public function respondToAccessTokenRequest(
ServerRequestInterface $request,
ResponseTypeInterface $responseType,
\DateInterval $accessTokenTTL
) {
// Validate request
$client = $this->validateClient($request);
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request));
$user = $this->validateUser($request, $client);
// Finalize the requested scopes
$scopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client);
// Issue and persist access token
$accessToken = $this->issueAccessToken(
$accessTokenTTL,
$client,
($user ? $user->getIdentifier() : null),
$scopes
);
// Inject access token into response type
$responseType->setAccessToken($accessToken);
return $responseType;
}
/**
* @see League\OAuth2\Server\Grant\PasswordGrant::validateUser
*/
protected function validateUser(ServerRequestInterface $request, ClientEntityInterface $client)
{
$clientRecord = app()->make(ClientRepository::class)->findActive($client->getIdentifier());
if(!$clientRecord->user_id) {
return null;
}
$user = new User($clientRecord->user_id);
if ($user instanceof UserEntityInterface === false) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidCredentials();
}
return $user;
}
/**
* {@inheritdoc}
*/
public function getIdentifier()
{
return 'client_credentials';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment