/**
  * Do authorization.
  *
  * @param  \Illuminate\Http\Request $request
  * @return \Illuminate\Http\Response
  */
 public function postIndex(Request $request)
 {
     $server = new AuthorizationServer();
     $server->setSessionStorage(new SessionStorage());
     $server->setAccessTokenStorage(new AccessTokenStorage());
     $server->setClientStorage(new ClientStorage());
     $server->setScopeStorage(new ScopeStorage());
     $server->setRefreshTokenStorage(new RefreshTokenStorage());
     $server->addGrantType(new ClientCredentials());
     $server->addGrantType(new RefreshToken());
     $server->setTokenType(new Bearer());
     try {
         $accessToken = $server->issueAccessToken();
         $response = new Response($accessToken, 200, ['Cache-Control' => 'no-store', 'Pragma' => 'no-store']);
     } catch (OAuthException $e) {
         $response = new Response(['error' => $e->errorType, 'message' => $e->getMessage()], $e->httpStatusCode, $e->getHttpHeaders());
     } catch (\Exception $e) {
         $response = new Response(['error' => $e->getCode(), 'message' => $e->getMessage()], 500);
     } finally {
         // Return the response
         $response->headers->set('Content-type', 'application/json');
         return $response;
     }
     // TO DO: Remove previous active access token for current client
 }
 /**
  * @throws AbortException
  */
 public function actionAuthorize()
 {
     if (!$this->getHttpRequest()->isMethod(IRequest::GET)) {
         $body = $this->createStream();
         $body->write('Method not allowed');
         $this->sendResponse($this->createResponse()->withStatus(IResponse::S405_METHOD_NOT_ALLOWED)->withBody($body));
     }
     $response = $this->createResponse();
     try {
         $this->getSession(self::SESSION_NAMESPACE)->authorizationRequest = $this->authorizationRequestSerializer->serialize($this->authorizationServer->validateAuthorizationRequest($this->createServerRequest()));
         if (!$this->getUser()->isLoggedIn()) {
             $this->redirect(...$this->redirectConfig->getLoginDestination());
         }
         $this->redirect(...$this->redirectConfig->getApproveDestination());
     } catch (AbortException $e) {
         throw $e;
     } catch (OAuthServerException $e) {
         $this->sendResponse($e->generateHttpResponse($response));
     } catch (\Exception $e) {
         if ($this->logger) {
             $this->logger->error($e->getMessage(), ['exception' => $e]);
         }
         $body = $this->createStream();
         $body->write('Unknown error');
         $this->sendResponse($response->withStatus(IResponse::S500_INTERNAL_SERVER_ERROR)->withBody($body));
     }
 }
 public function enableAllGrants()
 {
     if (!$this->authorize) {
         $this->initAuthorizationServer();
     }
     foreach ($this->grants as $type => $grantName) {
         $type = new $grantName();
         $this->authorize->addGrantType($type);
         if ($type instanceof \League\OAuth2\Server\Grant\PasswordGrant) {
             $type->setVerifyCredentialsCallback(function ($username, $password) {
                 //$user = \Users::findFirstByUsername($username);
                 if (!isset($_POST['targetdb'])) {
                     $user = \Users::findFirstByUsername($username);
                     if ($user && $this->security->checkHash($password, $user->password)) {
                         return $user->username;
                     }
                 } else {
                     switch ($_POST['targetdb']) {
                         case "NiuGame":
                             $user = \NiuUsrInfo::findFirstById($username);
                             $this->totp->setSecret($user->gasecret);
                             $this->totp->setWindow(31);
                             //31(sec) == (15s forward and backward)
                             if ($user && $this->totp->validate($password)) {
                                 return $user->id;
                             }
                             break;
                     }
                 }
                 return false;
             });
         }
     }
 }
Exemplo n.º 4
0
 /**
  * Complete the client credentials grant
  *
  * @return array
  *
  * @throws
  */
 public function completeFlow()
 {
     $selfClient = app('selfClient');
     // Get the required params
     if (is_null($selfClient)) {
         throw new Exception\InvalidClientException();
     }
     // Validate client ID and client secret
     $client = $this->server->getClientStorage()->get($selfClient->id, $selfClient->secret, null, $this->getIdentifier());
     if ($client instanceof ClientEntity === false) {
         $this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest()));
         throw new Exception\InvalidClientException();
     }
     // Create a new session
     $session = new SessionEntity($this->server);
     $session->setOwner('client', $client->getId());
     $session->associateClient($client);
     // Generate an access token
     $accessToken = new AccessTokenEntity($this->server);
     $accessToken->setId(SecureKey::generate());
     $accessToken->setExpireTime($this->getAccessTokenTTL() + time());
     foreach ($session->getScopes() as $scope) {
         $accessToken->associateScope($scope);
     }
     // Save everything
     $session->save();
     $accessToken->setSession($session);
     $accessToken->save();
     $oauthClient = new GenericProvider(['clientId' => $selfClient->id, 'clientSecret' => $selfClient->secret, 'redirectUri' => null, 'urlAuthorize' => null, 'urlAccessToken' => null, 'urlResourceOwnerDetails' => null]);
     $accessToken = new AccessToken(['access_token' => $accessToken->getId(), 'expires' => $accessToken->getExpireTime()]);
     return function ($method, $url, $options = []) use($oauthClient, $accessToken) {
         return $oauthClient->getAuthenticatedRequest($method, $url, $accessToken, $options);
     };
 }
Exemplo n.º 5
0
 /**
  * POST /oauth/access_token
  *
  * @param Request $request
  *
  * @return JsonResponse
  */
 public function issueAccessToken(Request $request)
 {
     try {
         $response = $this->server->issueAccessToken();
         return $this->respond($response);
     } catch (\Exception $e) {
         return $this->setStatusCode($e->httpStatusCode)->respond(['error' => $e->errorType, 'message' => $e->getMessage()], $e->getHttpHeaders());
     }
 }
Exemplo n.º 6
0
 public function testInvoke()
 {
     $this->server->shouldReceive('issueAccessToken')->once()->andReturn(['accessToken' => 'foo']);
     $action = $this->action;
     /** @var Response $response */
     $response = $action($this->newTonisRequest('/'), $this->newTonisResponse());
     $this->assertInstanceOf(Response::class, $response);
     $this->assertSame(200, $response->getStatusCode());
     $this->assertContains('foo', (string) $response->getBody());
 }
 /**
  * Handle an incoming request.
  *
  * @param \Illuminate\Http\Request $request
  * @param \Closure                 $next
  * @param int                      $limit
  * @param int                      $time
  *
  * @throws \League\OAuth2\Server\Exception\OAuthServerException
  *
  * @return mixed
  */
 public function handle($request, Closure $next, $limit = 10, $time = 60)
 {
     try {
         $response = $this->server->respondToAccessTokenRequest($request, $response);
     } catch (OAuthServerException $exception) {
         return $exception->generateHttpResponse($response);
     } catch (Exception $exception) {
         return (new OAuthServerException($exception->getMessage(), 0, 'unknown_error', 500))->generateHttpResponse($response);
     }
     return $next($request);
 }
Exemplo n.º 8
0
 /**
  * Authenticate via the Access Token Grant
  *
  * @return JsonResponse
  */
 public function accessToken()
 {
     try {
         $response = $this->server->issueAccessToken();
         return response()->json($response);
     } catch (OAuthException $e) {
         $error = $e->errorType;
         $message = $e->getMessage();
         $code = $e->httpStatusCode;
         $headers = $e->getHttpHeaders();
         return response()->json(compact('error', 'message'), $code, $headers);
     }
 }
Exemplo n.º 9
0
 /**
  * handle
  */
 public function handle()
 {
     $clientRepository = new ClientRepository();
     $scopeRepository = new ScopeRepository();
     $accessTokenRepository = new AccessTokenRepository();
     $config = Yii::$container->get(ConfigInterface::class);
     $privateKey = $config->get('privateKeyPath');
     $publicKey = $config->get('publicKeyPath');
     $server = new AuthorizationServer($clientRepository, $accessTokenRepository, $scopeRepository, $privateKey, $publicKey);
     $accessTokenTTL = $config->get('accessTokenTTL', 'PT1H');
     $server->enableGrantType(new ClientCredentialsGrant(), new \DateInterval($accessTokenTTL));
     return $server;
 }
Exemplo n.º 10
0
 /**
  * @param \Psr\Http\Message\ServerRequestInterface $request
  *
  * @return \Illuminate\Http\Response
  */
 public function issueToken(ServerRequestInterface $request)
 {
     $response = $this->withErrorHandling(function () use($request) {
         return $this->server->respondToAccessTokenRequest($request, new Psr7Response());
     });
     if ($response->getStatusCode() < 200 || $response->getStatusCode() > 299) {
         return $response;
     }
     $payload = json_decode($response->getBody()->__toString(), true);
     if (isset($payload['access_token'])) {
         $this->revokeOtherAccessTokens($payload);
     }
     return $response;
 }
Exemplo n.º 11
0
 /**
  * @Route("/", methods={"POST"})
  */
 public function loginAction(Request $request)
 {
     $request->request->set('grant_type', 'password');
     $request->request->set('client_id', $this->clientId);
     $request->request->set('client_secret', $this->clientSecret);
     $this->server->setRequest($request);
     try {
         $response = $this->server->issueAccessToken();
         $request->getSession()->set('oauth_data', $response);
         return new Response();
     } catch (OAuthException $e) {
         return new Response('', Response::HTTP_BAD_REQUEST);
     }
 }
 /**
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  * @param callable               $next
  *
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     try {
         $response = $this->server->respondToAccessTokenRequest($request, $response);
     } catch (OAuthServerException $exception) {
         return $exception->generateHttpResponse($response);
         // @codeCoverageIgnoreStart
     } catch (\Exception $exception) {
         return (new OAuthServerException($exception->getMessage(), 0, 'unknown_error', 500))->generateHttpResponse($response);
         // @codeCoverageIgnoreEnd
     }
     // Pass the request and response on to the next responder in the chain
     return $next($request, $response);
 }
Exemplo n.º 13
0
 /**
  * @param string $authGrant Grant type
  * @return bool|\Cake\Network\Response|void
  */
 public function checkAuthParams($authGrant)
 {
     $controller = $this->_registry->getController();
     try {
         return $this->Server->getGrantType($authGrant)->checkAuthorizeParams();
     } catch (\OAuthException $e) {
         if ($e->shouldRedirect()) {
             return $controller->redirect($e->getRedirectUri());
         }
         $controller->RequestHandler->renderAs($this, 'json');
         $controller->response->statusCode($e->httpStatusCode);
         $controller->response->header($e->getHttpHeaders());
         $controller->set('response', $e);
         return false;
     }
 }
Exemplo n.º 14
0
 /**
  * Create a new OAuth2 authorization server
  * @return self
  */
 public function __construct()
 {
     // Set Bearer as the default token type
     $this->setTokenType(new Bearer());
     parent::__construct();
     return $this;
 }
Exemplo n.º 15
0
 /**
  * Store handler.
  *
  * @return \Illuminate\Http\Response
  */
 public function store()
 {
     return $this->withErrorHandling(function () use($request) {
         $authRequest = $this->getAuthRequestFromSession($request);
         return $this->server->completeAuthorizationRequest($authRequest, new Psr7Response());
     });
 }
Exemplo n.º 16
0
 /**
  * handle
  */
 public function handle()
 {
     $clientRepository = new ClientRepository();
     $scopeRepository = new ScopeRepository();
     $accessTokenRepository = new AccessTokenRepository();
     $userRepository = new UserRepository();
     $refreshTokenRepository = new RefreshTokenRepository();
     $config = Yii::$container->get(ConfigInterface::class);
     $privateKey = $config->get('privateKeyPath');
     $publicKey = $config->get('publicKeyPath');
     $server = new AuthorizationServer($clientRepository, $accessTokenRepository, $scopeRepository, $privateKey, $publicKey);
     $refreshTokenTTL = $config->get('refreshTokenTTL', 'P1M');
     $accessTokenTTL = $config->get('accessTokenTTL', 'PT1H');
     $grant = new PasswordGrant($userRepository, $refreshTokenRepository);
     $grant->setRefreshTokenTTL(new \DateInterval($refreshTokenTTL));
     $server->enableGrantType($grant, new \DateInterval($accessTokenTTL));
     return $server;
 }
Exemplo n.º 17
0
 /**
  * enable RefreshTokenGrant.
  *
  * @param $options
  *
  * @return RefreshTokenGrant
  */
 public function enableRefreshTokenGrant($options)
 {
     // Init our repositories
     $refreshTokenRepository = new RefreshTokenRepository();
     $grant = new RefreshTokenGrant($refreshTokenRepository);
     $grant->setRefreshTokenTTL($this->getDateInterval($options['refresh_token_ttl']));
     // Enable the refresh token grant on the server
     $this->authorizationServer->enableGrantType($grant, $this->getDateInterval($options['access_token_ttl']));
     return $grant;
 }
 /**
  * Save the session
  *
  * @return void
  */
 public function save()
 {
     // Save the session and get an identifier
     $id = $this->server->getSessionStorage()->create($this->getOwnerType(), $this->getOwnerId(), $this->getClient()->getId(), $this->getClient()->getRedirectUri());
     $this->setId($id);
     // Associate the scope with the session
     foreach ($this->getScopes() as $scope) {
         $this->server->getSessionStorage()->associateScope($this, $scope);
     }
 }
Exemplo n.º 19
0
 private function completeAuthorizationRequest()
 {
     $this->session->getSection(OAuth2Presenter::SESSION_NAMESPACE)->remove();
     $response = $this->createResponse();
     try {
         $this->onResponse($this->authorizationServer->completeAuthorizationRequest($this->authorizationRequest, $response));
     } catch (AbortException $e) {
         throw $e;
     } catch (OAuthServerException $e) {
         $this->onResponse($e->generateHttpResponse($response));
     } catch (\Exception $e) {
         if ($this->logger) {
             $this->logger->error($e->getMessage(), ['exception' => $e]);
         }
         $body = $this->createStream();
         $body->write('Unknown error');
         $this->onResponse($response->withStatus(HttpResponse::S500_INTERNAL_SERVER_ERROR)->withBody($body));
     }
 }
 /**
  * Complete the client credentials grant
  *
  * @return array
  *
  * @throws
  */
 public function completeFlow()
 {
     // Get the required params
     $clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
     //$clientId= 'client1';
     if (is_null($clientId)) {
         throw new Exception\InvalidRequestException('client_id');
     }
     $clientSecret = $this->server->getRequest()->request->get('client_secret', $this->server->getRequest()->getPassword());
     //$clientSecret = 'test1';
     if (is_null($clientSecret)) {
         throw new Exception\InvalidRequestException('client_secret');
     }
     // Validate client ID and client secret
     $client = $this->server->getClientStorage()->get($clientId, $clientSecret, null, $this->getIdentifier());
     if ($client instanceof ClientEntity === false) {
         $this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest()));
         throw new Exception\InvalidClientException();
     }
     // Validate any scopes that are in the request
     $scopeParam = $this->server->getRequest()->request->get('scope', '');
     $scopes = $this->validateScopes($scopeParam, $client);
     // Create a new session
     $session = new SessionEntity($this->server);
     $session->setOwner('client', $client->getId());
     $session->associateClient($client);
     // Generate an access token
     $accessToken = new AccessTokenEntity($this->server);
     $accessToken->setId(SecureKey::generate());
     $accessToken->setExpireTime($this->getAccessTokenTTL() + time());
     // Associate scopes with the session and access token
     foreach ($scopes as $scope) {
         $session->associateScope($scope);
     }
     foreach ($session->getScopes() as $scope) {
         $accessToken->associateScope($scope);
     }
     // Save everything
     $session->save();
     $accessToken->setSession($session);
     $accessToken->save();
     $this->server->getTokenType()->setSession($session);
     $this->server->getTokenType()->setParam('access_token', $accessToken->getId());
     $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
     return $this->server->getTokenType()->generateResponse();
 }
Exemplo n.º 21
0
 /**
  * Set up an OAuth2 Authorization Server.
  */
 protected function setAuthorizationServer()
 {
     $this->authorisationServer = new AuthorizationServer();
     // Storage
     $this->authorisationServer->setSessionStorage(new Storage\SessionStorage());
     $this->authorisationServer->setAccessTokenStorage(new Storage\AccessTokenStorage());
     $this->authorisationServer->setClientStorage(new Storage\ClientStorage());
     $this->authorisationServer->setScopeStorage(new Storage\ScopeStorage());
     $this->authorisationServer->setRefreshTokenStorage(new Storage\RefreshTokenStorage());
     // Grants
     $this->authorisationServer->addGrantType(new RefreshTokenGrant());
     // Events
     $this->authorisationServer->addEventListener('error.auth.client', [$this, 'eventErrorAuthClient']);
     $this->authorisationServer->addEventListener('error.auth.user', [$this, 'eventErrorAuthUser']);
     $this->authorisationServer->addEventListener('session.owner', [$this, 'eventSessionOwner']);
 }
 /**
  * Generate the redirect URI for the Implicit grant
  * @param $ownerType
  * @param $ownerId
  * @param $params
  * @return string
  * @throws Exception\InvalidClientException
  * @throws Exception\InvalidRequestException
  */
 public function getRedirectUri($ownerType, $ownerId, $params)
 {
     // Get required params
     if (!isset($params['client']) || $params['client'] instanceof ClientEntity === false) {
         $this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest()));
         throw new Exception\InvalidClientException();
     }
     $client = $params['client'];
     if (!isset($params['redirect_uri']) || is_null($params['redirect_uri'])) {
         throw new Exception\InvalidRequestException('redirect_uri');
     }
     $redirectUri = $params['redirect_uri'];
     // Create a new session
     $session = new SessionEntity($this->server);
     $session->setOwner($ownerType, $ownerId);
     $session->associateClient($client);
     // Generate the access token
     $accessToken = new AccessTokenEntity($this->server);
     $accessToken->setId(SecureKey::generate());
     $accessToken->setExpireTime($this->getAccessTokenTTL() + time());
     if (isset($params['scopes'])) {
         foreach ($params['scopes'] as $implicitScope) {
             $session->associateScope($implicitScope);
         }
         foreach ($session->getScopes() as $scope) {
             $accessToken->associateScope($scope);
         }
     }
     $this->server->getTokenType()->setSession($session);
     $this->server->getTokenType()->setParam('access_token', $accessToken->getId());
     $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
     // Save all the things
     $session->save();
     $accessToken->setSession($session);
     $accessToken->save();
     $token = $this->server->getTokenType()->generateResponse();
     if (isset($params['state']) && $params['state']) {
         $token['state'] = $params['state'];
     }
     return $params['redirect_uri'] . '#' . join('&', array_map(function ($v, $k) {
         return $k . '=' . $v;
     }, $token, array_keys($token)));
 }
 function it_sets_the_request_to_the_issuer_and_checker(AuthorizationServer $issuer, ResourceServer $checker, Request $request)
 {
     $issuer->setRequest($request)->shouldBeCalled();
     $checker->setRequest($request)->shouldBeCalled();
     $this->setRequest($request);
 }
 /**
  * Register the Authorization server with the IoC container
  * @return void
  */
 public function registerAuthorizer()
 {
     $this->app->bindShared('oauth2-server.authorizer', function ($app) {
         $config = $app['config']->get('oauth2');
         $limitClientsToGrants = $config['limit_clients_to_grants'];
         $limitClientsToScopes = $config['limit_clients_to_scopes'];
         // Authorization server
         $issuer = new AuthorizationServer();
         $issuer->setSessionStorage(new SessionStorage($app['db']));
         $issuer->setAccessTokenStorage(new AccessTokenStorage($app['db']));
         $issuer->setRefreshTokenStorage(new RefreshTokenStorage($app['db']));
         $issuer->setClientStorage(new ClientStorage($app['db'], $limitClientsToGrants));
         $issuer->setScopeStorage(new ScopeStorage($app['db'], $limitClientsToScopes, $limitClientsToGrants));
         $issuer->setAuthCodeStorage(new AuthCodeStorage($app['db']));
         $issuer->requireScopeParam($config['scope_param']);
         $issuer->setDefaultScope($config['default_scope']);
         $issuer->requireStateParam($config['state_param']);
         $issuer->setScopeDelimiter($config['scope_delimiter']);
         $issuer->setAccessTokenTTL($config['access_token_ttl']);
         // add the supported grant types to the authorization server
         foreach ($config['grant_types'] as $grantIdentifier => $grantParams) {
             $grant = new $grantParams['class']();
             $grant->setAccessTokenTTL($grantParams['access_token_ttl']);
             if (array_key_exists('callback', $grantParams)) {
                 $grant->setVerifyCredentialsCallback($grantParams['callback']);
             }
             if (array_key_exists('auth_token_ttl', $grantParams)) {
                 $grant->setAuthTokenTTL($grantParams['auth_token_ttl']);
             }
             if (array_key_exists('refresh_token_ttl', $grantParams)) {
                 $grant->setRefreshTokenTTL($grantParams['refresh_token_ttl']);
             }
             $issuer->addGrantType($grant);
         }
         // Resource server
         $sessionStorage = new SessionStorage($app['db']);
         $accessTokenStorage = new AccessTokenStorage($app['db']);
         $clientStorage = new ClientStorage($app['db'], $limitClientsToGrants);
         $scopeStorage = new ScopeStorage($app['db'], $limitClientsToScopes, $limitClientsToGrants);
         $checker = new ResourceServer($sessionStorage, $accessTokenStorage, $clientStorage, $scopeStorage);
         $authorizer = new Authorizer($issuer, $checker);
         $authorizer->setRequest($app['request']);
         $authorizer->setTokenType($app->make($config['token_type']));
         $app->refresh('request', $authorizer, 'setRequest');
         return $authorizer;
     });
     $this->app->bind('Rapiro\\OAuth2Server\\Authorizer', function ($app) {
         return $app['oauth2-server.authorizer'];
     });
 }
 /**
  * Configures the grant types for the authorization server instance.
  *
  * @param AuthorizationServer $authorizationServer
  * @param array               $config
  *
  * @throws InvalidArgument
  */
 protected function configureGrantTypes(AuthorizationServer $authorizationServer, array $config)
 {
     // TODO: Support configuring of the remaining grant types
     foreach ($config as $name => $params) {
         if (!isset($params['class']) || !class_exists($params['class'])) {
             continue;
         }
         /** @var AbstractGrant $grantType */
         $grantType = new $params['class']();
         if (isset($params['access_token_ttl'])) {
             $grantType->setAccessTokenTTL($params['access_token_ttl']);
         }
         if ($grantType instanceof PasswordGrant) {
             /** @var PasswordGrant $grantType */
             if (isset($params['callback'])) {
                 $grantType->setVerifyCredentialsCallback($params['callback']);
             }
         }
         if ($grantType instanceof RefreshTokenGrant) {
             /** @var RefreshTokenGrant $grantType */
             if (isset($params['refresh_token_rotate'])) {
                 $grantType->setRefreshTokenRotation($params['refresh_token_rotate']);
             }
             if (isset($params['refresh_token_ttl'])) {
                 $grantType->setRefreshTokenTTL($params['refresh_token_ttl']);
             }
         }
         $authorizationServer->addGrantType($grantType);
     }
 }
Exemplo n.º 26
0
 /**
  * @return array
  * @throws \League\OAuth2\Server\Exception\InvalidRequestException
  * @throws \League\OAuth2\Server\Exception\UnsupportedGrantTypeException
  */
 public function issueAccessToken()
 {
     return $this->authorizationServer->issueAccessToken();
 }
Exemplo n.º 27
0
 /**
  * Set the token type to use.
  *
  * @param \League\OAuth2\Server\TokenType\TokenTypeInterface $tokenType
  */
 public function setTokenType(TokenTypeInterface $tokenType)
 {
     $this->issuer->setTokenType($tokenType);
     $this->checker->setTokenType($tokenType);
 }
Exemplo n.º 28
0
 /**
  * Complete the auth code grant
  *
  * @return array
  *
  * @throws
  */
 public function completeFlow()
 {
     // Get the required params
     $clientId = $this->server->getRequest()->query->get('client_id', $this->server->getRequest()->getUser());
     if (is_null($clientId)) {
         throw new Exception\InvalidRequestException('client_id');
     }
     $clientSecret = $this->server->getRequest()->query->get('client_secret', $this->server->getRequest()->getPassword());
     if ($this->shouldRequireClientSecret() && is_null($clientSecret)) {
         throw new Exception\InvalidRequestException('client_secret');
     }
     $redirectUri = $this->server->getRequest()->query->get('redirect_uri', null);
     if (is_null($redirectUri)) {
         throw new Exception\InvalidRequestException('redirect_uri');
     }
     // Validate client ID and client secret
     $client = $this->server->getClientStorage()->get($clientId, $clientSecret, $redirectUri, $this->getIdentifier());
     if ($client instanceof ClientEntity === false) {
         $this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest()));
         throw new Exception\InvalidClientException();
     }
     // Validate the auth code
     $authCode = $this->server->getRequest()->query->get('code', null);
     if (is_null($authCode)) {
         throw new Exception\InvalidRequestException('code');
     }
     // $code: AuthCodeEntity
     $code = $this->server->getAuthCodeStorage()->get($authCode);
     if ($code instanceof AuthCodeEntity === false) {
         throw new Exception\InvalidRequestException('code');
     }
     // Ensure the auth code hasn't expired
     if ($code->isExpired() === true) {
         throw new Exception\InvalidRequestException('code');
     }
     // Check redirect URI presented matches redirect URI originally used in authorize request
     if ($code->getRedirectUri() !== $redirectUri) {
         throw new Exception\InvalidRequestException('redirect_uri');
     }
     // $session: SessionEntity
     $session = $code->getSession();
     $session->associateClient($client);
     // $authCodeScopes: [ScopeEntity]
     $authCodeScopes = $code->getScopes();
     // Generate the access token
     $accessToken = new AccessTokenEntity($this->server);
     $accessToken->setId(SecureKey::generate());
     $accessToken->setExpireTime($this->getAccessTokenTTL() + time());
     foreach ($authCodeScopes as $authCodeScope) {
         $session->associateScope($authCodeScope);
     }
     foreach ($session->getScopes() as $scope) {
         $accessToken->associateScope($scope);
     }
     $this->server->getTokenType()->setSession($session);
     $this->server->getTokenType()->setParam('access_token', $accessToken->getId());
     $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
     // Associate a refresh token if set
     if ($this->server->hasGrantType('refresh_token')) {
         $refreshToken = new RefreshTokenEntity($this->server);
         $refreshToken->setId(SecureKey::generate());
         $refreshToken->setExpireTime($this->server->getGrantType('refresh_token')->getRefreshTokenTTL() + time());
         $this->server->getTokenType()->setParam('refresh_token', $refreshToken->getId());
     }
     // Expire the auth code
     $code->expire();
     // Save all the things
     $accessToken->setSession($session);
     $accessToken->save();
     if (isset($refreshToken) && $this->server->hasGrantType('refresh_token')) {
         $refreshToken->setAccessToken($accessToken);
         $refreshToken->save();
     }
     return $this->server->getTokenType()->generateResponse();
 }
Exemplo n.º 29
0
require_once 'vendor/autoload.php';
use League\OAuth2\Server\ResourceServer;
use League\OAuth2\Server\AuthorizationServer;
use Lib\Model;
use Models\Host;
use Lib\OAuth2\Storage;
use Lib\OAuth2\OAuth2;
$app = new \Slim\Slim(array('debug' => true));
$app->response->headers->set('Content-Type', 'application/json');
// Set up the OAuth 2.0 resource server
$sessionStorage = new Storage\SessionStorage();
$accessTokenStorage = new Storage\AccessTokenStorage();
$clientStorage = new Storage\ClientStorage();
$scopeStorage = new Storage\ScopeStorage();
$refreshTokenStorage = new Storage\RefreshTokenStorage();
$authorizationServer = new \League\OAuth2\Server\AuthorizationServer();
$authorizationServer->setSessionStorage($sessionStorage);
$authorizationServer->setAccessTokenStorage($accessTokenStorage);
$authorizationServer->setClientStorage($clientStorage);
$authorizationServer->setScopeStorage($scopeStorage);
$authorizationServer->setRefreshTokenStorage($refreshTokenStorage);
//$clientCredentials = new \League\OAuth2\Server\Grant\ClientCredentialsGrant();
//$server->addGrantType($clientCredentials);
$refreshTokenGrant = new \League\OAuth2\Server\Grant\RefreshTokenGrant();
$authorizationServer->addGrantType($refreshTokenGrant);
$resourceServer = new ResourceServer($sessionStorage, $accessTokenStorage, $clientStorage, $scopeStorage, $refreshTokenStorage);
$passwordGrant = new \League\OAuth2\Server\Grant\PasswordGrant();
$authorizationServer->addGrantType($passwordGrant);
$passwordGrant->setVerifyCredentialsCallback(function ($username, $password) use($app) {
    // implement logic here to validate a username and password, return an ID if valid, otherwise return false
    $host = new Host();
 /**
  * Register the Authorisation Server
  *
  * @return void
  */
 private function authorisation()
 {
     $this->app->singleton('League\\OAuth2\\Server\\AuthorizationServer', function ($app) {
         $server = new AuthorizationServer();
         $server->setSessionStorage(new SessionStorage($app->make('db')));
         $server->setAccessTokenStorage(new AccessTokenStorage($app->make('db')));
         $server->setRefreshTokenStorage(new RefreshTokenStorage($app->make('db')));
         $server->setClientStorage(new ClientStorage($app->make('db')));
         $server->setScopeStorage(new ScopeStorage($app->make('db')));
         $server->setAuthCodeStorage(new AuthCodeStorage($app->make('db')));
         $passwordGrant = new PasswordGrant();
         $passwordGrant->setVerifyCredentialsCallback(function ($user, $pass) {
             return true;
         });
         $server->addGrantType($passwordGrant);
         $refreshTokenGrant = new RefreshTokenGrant();
         $server->addGrantType($refreshTokenGrant);
         $server->setRequest($app['request']);
         return $server;
     });
 }