/** * {@inheritdoc} */ public function generateResponse() { $macKey = SecureKey::generate(); $this->server->getMacStorage()->create($macKey, $this->getParam('access_token')); $response = ['access_token' => $this->getParam('access_token'), 'token_type' => 'mac', 'expires_in' => $this->getParam('expires_in'), 'mac_key' => $macKey, 'mac_algorithm' => 'hmac-sha-256']; return $response; }
/** * 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); }; }
/** * 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(); }
/** * Complete the client credentials grant * @param null|array $inputParams * @return array */ public function completeFlow($authParams = null) { // Remove any old sessions the user might have $this->authServer->getStorage('session')->deleteSession($authParams['client_id'], 'user', $authParams['user_id']); // Generate a new access token $accessToken = SecureKey::make(); // Compute expiry time $accessTokenExpires = time() + $this->authServer->getAccessTokenTTL(); // Create a new session $sessionId = $this->authServer->getStorage('session')->createSession($authParams['client_id'], 'user', $authParams['user_id']); // Create an access token $accessTokenId = $this->authServer->getStorage('session')->associateAccessToken($sessionId, $accessToken, $accessTokenExpires); // Associate scopes with the access token foreach ($authParams['scopes'] as $scope) { $this->authServer->getStorage('session')->associateScope($accessTokenId, $scope['id']); } $response = array('access_token' => $accessToken); return $response; }
/** * Complete the password grant. * * @throws * * @return array */ public function completeFlow() { // Get the required params $clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser()); if (is_null($clientId)) { throw new Exception\InvalidRequestException('client_id'); } $clientSecret = $this->server->getRequest()->request->get('client_secret', $this->server->getRequest()->getPassword()); 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(); } $userId = $this->server->getRequest()->request->get('user_id', null); if (is_null($userId)) { throw new Exception\InvalidRequestException('user_id'); } // Create a new session $session = new SessionEntity($this->server); $session->setOwner('user', $userId); $session->associateClient($client); // Generate an access token $accessToken = new AccessTokenEntity($this->server); $accessToken->setId(SecureKey::generate()); $accessToken->setExpireTime($this->getAccessTokenTTL() + time()); $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()); } // Save everything $session->save(); $accessToken->setSession($session); $accessToken->save(); if ($this->server->hasGrantType('refresh_token')) { $refreshToken->setAccessToken($accessToken); $refreshToken->save(); } return $this->server->getTokenType()->generateResponse(); }
/** * Complete the password grant * * @return array * * @throws */ public function completeFlow() { // Get the required params $clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser()); if (is_null($clientId)) { throw new Exception\InvalidRequestException('client_id'); } $clientSecret = $this->server->getRequest()->request->get('client_secret', $this->server->getRequest()->getPassword()); 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(); } $username = $this->server->getRequest()->request->get('username', null); if (is_null($username)) { throw new Exception\InvalidRequestException('username'); } $password = $this->server->getRequest()->request->get('password', null); if (is_null($password)) { throw new Exception\InvalidRequestException('password'); } // Check if user's username and password are correct $userId = call_user_func($this->getVerifyCredentialsCallback(), $username, $password); if ($userId === false) { $this->server->getEventEmitter()->emit(new Event\UserAuthenticationFailedEvent($this->server->getRequest())); throw new Exception\InvalidCredentialsException(); } // 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('user', $userId); $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); } $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()); } // Save everything $session->save(); $accessToken->setSession($session); $accessToken->save(); if ($this->server->hasGrantType('refresh_token')) { $refreshToken->setAccessToken($accessToken); $refreshToken->save(); } return $this->server->getTokenType()->generateResponse(); }
/** * {@inheritdoc} */ public function completeFlow() { $clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser()); if (is_null($clientId)) { throw new Exception\InvalidRequestException('client_id'); } $clientSecret = $this->server->getRequest()->request->get('client_secret', $this->server->getRequest()->getPassword()); 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(); } $oldRefreshTokenParam = $this->server->getRequest()->request->get('refresh_token', null); if ($oldRefreshTokenParam === null) { throw new Exception\InvalidRequestException('refresh_token'); } // Validate refresh token $oldRefreshToken = $this->server->getRefreshTokenStorage()->get($oldRefreshTokenParam); if ($oldRefreshToken instanceof RefreshTokenEntity === false) { throw new Exception\InvalidRefreshException(); } // Ensure the old refresh token hasn't expired if ($oldRefreshToken->isExpired() === true) { throw new Exception\InvalidRefreshException(); } $oldAccessToken = $oldRefreshToken->getAccessToken(); // Get the scopes for the original session $session = $oldAccessToken->getSession(); $scopes = $this->formatScopes($session->getScopes()); // Get and validate any requested scopes $requestedScopesString = $this->server->getRequest()->request->get('scope', ''); $requestedScopes = $this->validateScopes($requestedScopesString, $client); // If no new scopes are requested then give the access token the original session scopes if (count($requestedScopes) === 0) { $newScopes = $scopes; } else { // The OAuth spec says that a refreshed access token can have the original scopes or fewer so ensure // the request doesn't include any new scopes foreach ($requestedScopes as $requestedScope) { if (!isset($scopes[$requestedScope->getId()])) { throw new Exception\InvalidScopeException($requestedScope->getId()); } } $newScopes = $requestedScopes; } // Generate a new access token and assign it the correct sessions $newAccessToken = new AccessTokenEntity($this->server); $newAccessToken->setId(SecureKey::generate()); $newAccessToken->setExpireTime($this->getAccessTokenTTL() + time()); $newAccessToken->setSession($session); foreach ($newScopes as $newScope) { $newAccessToken->associateScope($newScope); } // Expire the old token and save the new one $oldAccessToken->expire(); $newAccessToken->save(); $this->server->getTokenType()->setSession($session); $this->server->getTokenType()->setParam('access_token', $newAccessToken->getId()); $this->server->getTokenType()->setParam('expire_access_token', $this->getAccessTokenTTL() + time()); if ($this->shouldRotateRefreshTokens()) { // Expire the old refresh token $oldRefreshToken->expire(); // Generate a new refresh token $newRefreshToken = new RefreshTokenEntity($this->server); $newRefreshToken->setId(SecureKey::generate()); $newRefreshToken->setExpireTime($this->getRefreshTokenTTL() + time()); $newRefreshToken->setAccessToken($newAccessToken); $newRefreshToken->save(); $this->server->getTokenType()->setParam('refresh_token', $newRefreshToken->getId()); $this->server->getTokenType()->setParam('expire_refresh_token', $newRefreshToken->getExpireTime()); } else { $this->server->getTokenType()->setParam('refresh_token', $oldRefreshToken->getId()); $this->server->getTokenType()->setParam('expire_refresh_token', $oldRefreshToken->getExpireTime()); } return $this->server->getTokenType()->generateResponse(); }
public function testGetScopes() { $accessToken = SecureKey::make(); $clientId = 999; $scopeId = 123; $scope = 'foo'; $scopeId2 = 124; $scope2 = 'foo2'; // Set up the test fixture // Add scopes $stmt = $this->getDbal()->prepare('INSERT INTO oauth_scopes (id, scope) VALUES (:scopeId, :scope)'); $stmt->execute(array(':scopeId' => $scopeId, ':scope' => $scope)); $stmt->execute(array(':scopeId' => $scopeId2, ':scope' => $scope2)); // Add session and access token. $sessionId = $this->store->createSession($clientId, 'user', 'xyz'); $accessTokenId = $this->store->associateAccessToken($sessionId, $accessToken, time() + 3600); // Associate scopes with access token. $this->store->associateScope($accessTokenId, $scopeId); $this->store->associateScope($accessTokenId, $scopeId2); // Get scopes and compare them. $result = $this->store->getScopes($accessToken); $this->assertInternalType('array', $result); $this->assertContains($scope, $result[0]); $this->assertContains($scope2, $result[1]); // Test that an empty array is returned if no scopes are found. $result = $this->store->getScopes('invalid-access-token'); $this->assertInternalType('array', $result); $this->assertEmpty($result); }
/** * 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(); }
/** * Complete the password grant * @param null|array $inputParams * @return array */ public function completeFlow($inputParams = null) { // Get the required params $authParams = $this->authServer->getParam(array('client_id', 'client_secret', 'username', 'password'), 'post', $inputParams); if (is_null($authParams['client_id'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_id'), 0); } if (is_null($authParams['client_secret'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_secret'), 0); } // Validate client credentials $clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret'], null, $this->identifier); if ($clientDetails === false) { throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_client'), 8); } $authParams['client_details'] = $clientDetails; if (is_null($authParams['username'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'username'), 0); } if (is_null($authParams['password'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'password'), 0); } // Check if user's username and password are correct $userId = call_user_func($this->getVerifyCredentialsCallback(), $authParams['username'], $authParams['password']); if ($userId === false) { throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_credentials'), 0); } // Validate any scopes that are in the request $scope = $this->authServer->getParam('scope', 'post', $inputParams, ''); $scopes = explode($this->authServer->getScopeDelimeter(), $scope); for ($i = 0; $i < count($scopes); $i++) { $scopes[$i] = trim($scopes[$i]); if ($scopes[$i] === '') { unset($scopes[$i]); } // Remove any junk scopes } if ($this->authServer->scopeParamRequired() === true && $this->authServer->getDefaultScope() === null && count($scopes) === 0) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'scope'), 0); } elseif (count($scopes) === 0 && $this->authServer->getDefaultScope() !== null) { if (is_array($this->authServer->getDefaultScope())) { $scopes = $this->authServer->getDefaultScope(); } else { $scopes = array($this->authServer->getDefaultScope()); } } $authParams['scopes'] = array(); foreach ($scopes as $scope) { $scopeDetails = $this->authServer->getStorage('scope')->getScope($scope, $authParams['client_id'], $this->identifier); if ($scopeDetails === false) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_scope'), $scope), 4); } $authParams['scopes'][] = $scopeDetails; } // Generate an access token $accessToken = SecureKey::make(); $accessTokenExpiresIn = $this->accessTokenTTL !== null ? $this->accessTokenTTL : $this->authServer->getAccessTokenTTL(); $accessTokenExpires = time() + $accessTokenExpiresIn; // Create a new session $sessionId = $this->authServer->getStorage('session')->createSession($authParams['client_id'], 'user', $userId); // Associate an access token with the session $accessTokenId = $this->authServer->getStorage('session')->associateAccessToken($sessionId, $accessToken, $accessTokenExpires); // Associate scopes with the access token foreach ($authParams['scopes'] as $scope) { $this->authServer->getStorage('session')->associateScope($accessTokenId, $scope['id']); } $response = array('access_token' => $accessToken, 'token_type' => 'Bearer', 'expires' => $accessTokenExpires, 'expires_in' => $accessTokenExpiresIn); // Associate a refresh token if set if ($this->authServer->hasGrantType('refresh_token')) { $refreshToken = SecureKey::make(); $refreshTokenTTL = time() + $this->authServer->getGrantType('refresh_token')->getRefreshTokenTTL(); $this->authServer->getStorage('session')->associateRefreshToken($accessTokenId, $refreshToken, $refreshTokenTTL, $authParams['client_id']); $response['refresh_token'] = $refreshToken; } return $response; }
} else { $new_user->location = $body->location; } if (!isset($body->website) || strlen($body->website) < 4 || !filter_var($body->email, FILTER_VALIDATE_URL)) { $new_user->website = ''; } else { $new_user->website = $body->website; } if (!User::isValidPassword($body->password)) { throw new InvalidField('password'); } $new_user->setPassword($body->password); $new_user->active = false; $new_user->save(); $validationToken = new ValidationToken(); $validationToken->token = SecureKey::generate(); $validationToken->user_id = $new_user->id; $validationToken->save(); $mailer = new Mailer(); $mailer->sendMail('confirm_email.html', [$new_user->email], 'Please confirm your email account', ['user' => $new_user->toArray(), 'validation_token' => $validationToken->token]); }); /** * Deletes the GLPi account on user request */ $user_delete_account = Tool::makeEndpoint(function () use($app, $resourceServer) { OAuthHelper::needsScopes(['user']); $body = Tool::getBody(); $user = OAuthHelper::currentlyAuthed(); // Ensures acceptable // password was given // so we don't do hash
/** * Complete the auth code grant * @param null|array $inputParams * @return array */ public function completeFlow($inputParams = null) { // Get the required params $authParams = $this->authServer->getParam(array('client_id', 'client_secret', 'redirect_uri', 'code'), 'post', $inputParams); if (is_null($authParams['client_id'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_id'), 0); } if (is_null($authParams['client_secret'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_secret'), 0); } if (is_null($authParams['redirect_uri'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'redirect_uri'), 0); } // Validate client ID and redirect URI $clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret'], $authParams['redirect_uri'], $this->identifier); if ($clientDetails === false) { throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_client'), 8); } $authParams['client_details'] = $clientDetails; // Validate the authorization code if (is_null($authParams['code'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'code'), 0); } // Verify the authorization code matches the client_id and the request_uri $authCodeDetails = $this->authServer->getStorage('session')->validateAuthCode($authParams['client_id'], $authParams['redirect_uri'], $authParams['code']); //dd($authCodeDetails); if (!$authCodeDetails) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_grant'), 'code'), 9); } // Get any associated scopes $scopes = $this->authServer->getStorage('session')->getAuthCodeScopes($authCodeDetails['authcode_id']); //dd($scopes); // A session ID was returned so update it with an access token and remove the authorisation code $accessToken = SecureKey::make(); $accessTokenExpiresIn = $this->accessTokenTTL !== null ? $this->accessTokenTTL : $this->authServer->getAccessTokenTTL(); $accessTokenExpires = time() + $accessTokenExpiresIn; // Remove the auth code $this->authServer->getStorage('session')->removeAuthCode($authCodeDetails['session_id']); // Create an access token $accessTokenId = $this->authServer->getStorage('session')->associateAccessToken($authCodeDetails['session_id'], $accessToken, $accessTokenExpires); /* iss: Issuer Identifier for the Issuer of the response sub: Subject identifier. A locally unique and never reassigned identifier within the Issuer for the End-User, which is intended to be consumed by the Client aud: Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value exp: Expiration time on or after which the ID Token MUST NOT be accepted for processing iat: Time at which the JWT was issued acr:0 nonce: */ //Create ID Token here, for OpenID Connect $id_token = array("iss" => \Config::get('app.url'), "sub" => \User::where('id', $this->authServer->getStorage('session')->validateAccessToken($accessToken)['owner_id'])->first()->pid, "aud" => $clientDetails['metadata']['website'], "iat" => time(), "exp" => $accessTokenExpires, "acr" => 0, "nonce" => \Cache::get($authParams['code'])); \Cache::forget($authParams['code']); // Associate scopes with the access token if (count($scopes) > 0) { foreach ($scopes as $scope) { $this->authServer->getStorage('session')->associateScope($accessTokenId, $scope['scope_id']); } } $response = array('access_token' => $accessToken, 'token_type' => 'Bearer', 'expires' => $accessTokenExpires, 'expires_in' => $accessTokenExpiresIn, 'id_token' => $id_token); // Associate a refresh token if set if ($this->authServer->hasGrantType('refresh_token')) { $refreshToken = SecureKey::make(); $refreshTokenTTL = time() + $this->authServer->getGrantType('refresh_token')->getRefreshTokenTTL(); $this->authServer->getStorage('session')->associateRefreshToken($accessTokenId, $refreshToken, $refreshTokenTTL, $authParams['client_id']); $response['refresh_token'] = $refreshToken; } return $response; }
public function setRandomSecret() { $this->secret = SecureKey::generate(); }
/** * Complete the password grant. * * @return array * * @throws */ public function completeFlow() { $client = $this->getClient(); $userId = $this->getUserId($this->server->getRequest(), $this->getVerifyCredentialsCallback()); if ($userId === false) { $this->server->getEventEmitter()->emit(new UserAuthenticationFailedEvent($this->server->getRequest())); throw new InvalidCredentialsException(); } // Create a new session $session = new SessionEntity($this->server); $session->setOwner('user', $userId); $session->associateClient($client); // Generate an access token $accessToken = new AccessTokenEntity($this->server); $accessToken->setId(SecureKey::generate()); $accessToken->setExpireTime($this->getAccessTokenTTL() + time()); $this->server->getTokenType()->setSession($session); $this->server->getTokenType()->setParam('access_token', $accessToken->getId()); $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL()); // Save everything $session->save(); $accessToken->setSession($session); $accessToken->save(); // 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()); $refreshToken->setAccessToken($accessToken); $refreshToken->save(); } return $this->server->getTokenType()->generateResponse(); }
/** * It creates an access token, a session, and links * scopes mentionned in $scopes to the session and * access token, it finally returns the new access token * * It associates the 'webapp' app */ public static function createAccessTokenFromUserId($user_id, $scopes, $ttl = 3600) { $user = User::where('id', '=', $user_id)->first(); if (!$user) { return false; } $session = new Session(); $session->owner_type = 'user'; $session->owner_id = $user->id; $session->app_id = 'webapp'; $session->save(); $accessToken = new AccessToken(); $accessToken->session_id = $session->id; $accessToken->token = SecureKey::generate(); $accessToken->expire_time = DB::raw('FROM_UNIXTIME(' . ($ttl + time()) . ')'); $accessToken->save(); foreach ($scopes as $_scope) { $scope = Scope::where('identifier', '=', $_scope)->first(); if ($scope) { $session->scopes()->attach($scope); $accessToken->scopes()->attach($scope); } } $refreshToken = new RefreshToken(); $refreshToken->access_token_id = $accessToken->id; $refreshToken->token = SecureKey::generate(); $refreshToken->expire_time = DB::raw('FROM_UNIXTIME(' . (604800 + time()) . ')'); $refreshToken->save(); return ["token" => $accessToken->token, "refresh_token" => $refreshToken->token, "ttl" => $ttl]; }
/** * Complete the password grant * * @return array * * @throws */ public function completeFlow() { // Get the required params $clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser()); if (is_null($clientId)) { throw new Exception\InvalidRequestException('client_id'); } $clientSecret = $this->server->getRequest()->request->get('client_secret', $this->server->getRequest()->getPassword()); 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(); } $twitter_token = $this->server->getRequest()->request->get('twitter_token', null); $client_id = $this->server->getRequest()->request->get('client_id', null); $userId = createOrUpdateTwCustomer($twitter_token, $client_id); //If not integer means error in the helper function, return it FOR DEBUGGING ONLY if (!is_int($userId)) { return $userId; } if ($userId === false) { $this->server->getEventEmitter()->emit(new Event\UserAuthenticationFailedEvent($this->server->getRequest())); throw new Exception\InvalidCredentialsException(); } // 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('user', $userId); $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); } $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()); } // Save everything $session->save(); $accessToken->setSession($session); $accessToken->save(); if ($this->server->hasGrantType('refresh_token')) { $refreshToken->setAccessToken($accessToken); $refreshToken->save(); } return $this->server->getTokenType()->generateResponse(); }
/** * Set token ID * * @param string $id Token ID * * @return self */ public function setId($id = null) { $this->id = $id !== null ? $id : SecureKey::generate(); return $this; }
/** * Complete the refresh token grant * @param null|array $inputParams * @return array */ public function completeFlow($inputParams = null) { // Get the required params $authParams = $this->authServer->getParam(array('client_id', 'client_secret', 'refresh_token', 'scope'), 'post', $inputParams); if (is_null($authParams['client_id'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_id'), 0); } if (is_null($authParams['client_secret'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_secret'), 0); } // Validate client ID and client secret $clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret'], null, $this->identifier); if ($clientDetails === false) { throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_client'), 8); } $authParams['client_details'] = $clientDetails; if (is_null($authParams['refresh_token'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'refresh_token'), 0); } // Validate refresh token $accessTokenId = $this->authServer->getStorage('session')->validateRefreshToken($authParams['refresh_token'], $authParams['client_id']); if ($accessTokenId === false) { throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_refresh'), 0); } // Get the existing access token $accessTokenDetails = $this->authServer->getStorage('session')->getAccessToken($accessTokenId); // Get the scopes for the existing access token $scopes = $this->authServer->getStorage('session')->getScopes($accessTokenDetails['access_token']); // Generate new tokens and associate them to the session $accessToken = SecureKey::make(); $accessTokenExpiresIn = $this->accessTokenTTL !== null ? $this->accessTokenTTL : $this->authServer->getAccessTokenTTL(); $accessTokenExpires = time() + $accessTokenExpiresIn; // Associate the new access token with the session $newAccessTokenId = $this->authServer->getStorage('session')->associateAccessToken($accessTokenDetails['session_id'], $accessToken, $accessTokenExpires); if ($this->rotateRefreshTokens === true) { // Generate a new refresh token $refreshToken = SecureKey::make(); $refreshTokenExpires = time() + $this->getRefreshTokenTTL(); // Revoke the old refresh token $this->authServer->getStorage('session')->removeRefreshToken($authParams['refresh_token']); // Associate the new refresh token with the new access token $this->authServer->getStorage('session')->associateRefreshToken($newAccessTokenId, $refreshToken, $refreshTokenExpires, $authParams['client_id']); } // There isn't a request for reduced scopes so assign the original ones (or we're not rotating scopes) if (!isset($authParams['scope'])) { foreach ($scopes as $scope) { $this->authServer->getStorage('session')->associateScope($newAccessTokenId, $scope['id']); } } elseif (isset($authParams['scope']) && $this->rotateRefreshTokens === true) { // The request is asking for reduced scopes and rotate tokens is enabled $reqestedScopes = explode($this->authServer->getScopeDelimeter(), $authParams['scope']); for ($i = 0; $i < count($reqestedScopes); $i++) { $reqestedScopes[$i] = trim($reqestedScopes[$i]); if ($reqestedScopes[$i] === '') { unset($reqestedScopes[$i]); } // Remove any junk scopes } // Check that there aren't any new scopes being included $existingScopes = array(); foreach ($scopes as $s) { $existingScopes[] = $s['scope']; } foreach ($reqestedScopes as $reqScope) { if (!in_array($reqScope, $existingScopes)) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'scope'), 0); } // Associate with the new access token $scopeDetails = $this->authServer->getStorage('scope')->getScope($reqScope, $authParams['client_id'], $this->identifier); $this->authServer->getStorage('session')->associateScope($newAccessTokenId, $scopeDetails['id']); } } $response = array('access_token' => $accessToken, 'token_type' => 'Bearer', 'expires' => $accessTokenExpires, 'expires_in' => $accessTokenExpiresIn); if ($this->rotateRefreshTokens === true) { $response['refresh_token'] = $refreshToken; } return $response; }
/** * Complete the auth code grant * @param null|array $inputParams * @return array */ public function completeFlow($inputParams = null) { // Get the required params $authParams = $this->authServer->getParam(array('client_id', 'client_secret', 'redirect_uri', 'code'), 'post', $inputParams); if (is_null($authParams['client_id'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_id'), 0); } if (is_null($authParams['client_secret'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_secret'), 0); } if (is_null($authParams['redirect_uri'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'redirect_uri'), 0); } // Validate client ID and redirect URI $clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret'], $authParams['redirect_uri'], $this->identifier); if ($clientDetails === false) { throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_client'), 8); } $authParams['client_details'] = $clientDetails; // Validate the authorization code if (is_null($authParams['code'])) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'code'), 0); } // Verify the authorization code matches the client_id and the request_uri $authCodeDetails = $this->authServer->getStorage('session')->validateAuthCode($authParams['client_id'], $authParams['redirect_uri'], $authParams['code']); if ( ! $authCodeDetails) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_grant'), 'code'), 9); } // Get any associated scopes $scopes = $this->authServer->getStorage('session')->getAuthCodeScopes($authCodeDetails['authcode_id']); // A session ID was returned so update it with an access token and remove the authorisation code $accessToken = SecureKey::make(); $accessTokenExpiresIn = ($this->accessTokenTTL !== null) ? $this->accessTokenTTL : $this->authServer->getAccessTokenTTL(); $accessTokenExpires = time() + $accessTokenExpiresIn; // Remove the auth code $this->authServer->getStorage('session')->removeAuthCode($authCodeDetails['session_id']); // Create an access token $accessTokenId = $this->authServer->getStorage('session')->associateAccessToken($authCodeDetails['session_id'], $accessToken, $accessTokenExpires); // Associate scopes with the access token if (count($scopes) > 0) { foreach ($scopes as $scope) { $this->authServer->getStorage('session')->associateScope($accessTokenId, $scope['scope_id']); } } $response = array( 'access_token' => $accessToken, 'token_type' => 'bearer', 'expires' => $accessTokenExpires, 'expires_in' => $accessTokenExpiresIn ); // Associate a refresh token if set if ($this->authServer->hasGrantType('refresh_token')) { $refreshToken = SecureKey::make(); $refreshTokenTTL = time() + $this->authServer->getGrantType('refresh_token')->getRefreshTokenTTL(); $this->authServer->getStorage('session')->associateRefreshToken($accessTokenId, $refreshToken, $refreshTokenTTL, $authParams['client_id']); $response['refresh_token'] = $refreshToken; } return $response; }
/** * Complete the client credentials grant * @param null|array $inputParams * @return array */ public function completeFlow($inputParams = null) { // Get the required params $authParams = $this->authServer->getParam(array('client_id', 'client_secret'), 'post', $inputParams); if (is_null($authParams['client_id'])) { throw new Exception\ClientException(sprintf(Authorization::getExceptionMessage('invalid_request'), 'client_id'), 0); } if (is_null($authParams['client_secret'])) { throw new Exception\ClientException(sprintf(Authorization::getExceptionMessage('invalid_request'), 'client_secret'), 0); } // Validate client ID and client secret $clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret'], null, $this->identifier); if ($clientDetails === false) { throw new Exception\ClientException(Authorization::getExceptionMessage('invalid_client'), 8); } $authParams['client_details'] = $clientDetails; // Validate any scopes that are in the request $scope = $this->authServer->getParam('scope', 'post', $inputParams, ''); $scopes = explode($this->authServer->getScopeDelimeter(), $scope); for ($i = 0; $i < count($scopes); $i++) { $scopes[$i] = trim($scopes[$i]); if ($scopes[$i] === '') { unset($scopes[$i]); } // Remove any junk scopes } if ($this->authServer->scopeParamRequired() === true && $this->authServer->getDefaultScope() === null && count($scopes) === 0) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'scope'), 0); } elseif (count($scopes) === 0 && $this->authServer->getDefaultScope() !== null) { if (is_array($this->authServer->getDefaultScope())) { $scopes = $this->authServer->getDefaultScope(); } else { $scopes = array($this->authServer->getDefaultScope()); } } $authParams['scopes'] = array(); foreach ($scopes as $scope) { $scopeDetails = $this->authServer->getStorage('scope')->getScope($scope, $authParams['client_id'], $this->identifier); if ($scopeDetails === false) { throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_scope'), $scope), 4); } $authParams['scopes'][] = $scopeDetails; } // Generate an access token $accessToken = SecureKey::make(); $accessTokenExpiresIn = $this->accessTokenTTL !== null ? $this->accessTokenTTL : $this->authServer->getAccessTokenTTL(); $accessTokenExpires = time() + $accessTokenExpiresIn; // Create a new session $sessionId = $this->authServer->getStorage('session')->createSession($authParams['client_id'], 'client', $authParams['client_id']); // Add the access token $accessTokenId = $this->authServer->getStorage('session')->associateAccessToken($sessionId, $accessToken, $accessTokenExpires); // Associate scopes with the new session foreach ($authParams['scopes'] as $scope) { $this->authServer->getStorage('session')->associateScope($accessTokenId, $scope['id']); } $response = array('access_token' => $accessToken, 'token_type' => 'Bearer', 'expires' => $accessTokenExpires, 'expires_in' => $accessTokenExpiresIn); return $response; }
/** * 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))); }