private function getTestServer() { $storage = Bootstrap::getInstance()->getMemoryStorage(); $server = new Server($storage, array('use_openid_connect' => true)); $server->addGrantType(new AuthorizationCode($storage)); return $server; }
public function init($type) { ini_set('display_errors', 1); error_reporting(E_ALL); vendor("OAuth2.Autoloader"); $loader = new Autoloader(); $loader::register(); //数据库存储 $storage = $this->getMysqlStorage(); // Pass a storage object or array of storage objects to the OAuth2 server class if ($type == self::IMPLICIT) { $server = new Server($storage, array('allow_implicit' => true)); } else { $server = new Server($storage, array('allow_implicit' => false)); } if ($type == self::CLIENT_CREDENTIALS) { // 客户端授权类型 $server->addGrantType(new ClientCredentials($storage, array('allow_credentials_in_request_body => true'))); } elseif ($type == self::AUTHORIZATION_CODE) { // 增加授权码模式授权类型 $server->addGrantType(new AuthorizationCode($storage)); } elseif ($type == self::PASSWORD) { // 增加password模式授权类型 $server->addGrantType(new UserCredentials($storage)); } else { // 增加password模式授权类型 $server->addGrantType(new UserCredentials($storage)); // 增加授权码模式授权类型 $server->addGrantType(new AuthorizationCode($storage)); // 客户端授权类型 $server->addGrantType(new ClientCredentials($storage)); } return $server; }
/** * Authorize action (/oauth/authorize) */ public function authorizeAction() { $request = $this->getOAuth2Request(); $response = new OAuth2Response(); // validate the authorize request if (!$this->server->validateAuthorizeRequest($request, $response)) { $parameters = $response->getParameters(); $errorUri = isset($parameters['error_uri']) ? $parameters['error_uri'] : null; return new ApiProblemResponse(new ApiProblem($response->getStatusCode(), $parameters['error_description'], $errorUri, $parameters['error'])); } $authorized = $request->request('authorized', false); if (empty($authorized)) { $clientId = $request->query('client_id', false); $view = new ViewModel(array('clientId' => $clientId)); $view->setTemplate('oauth/authorize'); return $view; } $is_authorized = $authorized === 'yes'; $this->server->handleAuthorizeRequest($request, $response, $is_authorized, $this->getRequest()->getQuery('user_id', null)); if ($is_authorized) { $redirect = $response->getHttpHeader('Location'); if (!empty($redirect)) { return $this->redirect()->toUrl($redirect); } } $parameters = $response->getParameters(); $errorUri = isset($parameters['error_uri']) ? $parameters['error_uri'] : null; return new ApiProblemResponse(new ApiProblem($response->getStatusCode(), $parameters['error_description'], $errorUri, $parameters['error'])); }
private function getTestServer() { $storage = Bootstrap::getInstance()->getMemoryStorage(); $server = new Server($storage); $server->addGrantType(new UserCredentials($storage)); return $server; }
public function middleware($req, $res) { $this->app['oauth_server'] = function ($c) { $storage = new IdealistStorage(); $storage->injectApp($c); $server = new Server($storage); // password grant type $grantType = new UserCredentials($storage); $server->addGrantType($grantType); // JWT access token response type $config = $c['config']->get('oauth2'); $jwtResponseType = new JwtAccessToken($storage, $storage, null, $config); $server->addResponseType($jwtResponseType); return $server; }; $this->app['oauth_resource'] = function ($c) { $server = new Server(); // no private key is necessary for the resource server $keyStorage = new Memory(['keys' => ['public_key' => file_get_contents(INFUSE_BASE_DIR . '/jwt_pubkey.pem')]]); $storage = new JwtAccessTokenStorage($keyStorage); $server->addStorage($storage, 'access_token'); return $server; }; // attempt to authenticate the user when an API request is made if ($req->isApi()) { $this->authenticateApiRequest(); } }
/** * function to create the OAuth2 Server Object */ public function setup(Application $app) { $app['fixtures_manager'] = new FixturesManager($app); // make sure the sqlite file is initialized $sqliteFile = __DIR__ . '/../../../data/coop.sqlite'; $dbFileExists = file_exists($sqliteFile); if (!$dbFileExists) { $app['fixtures_manager']->resetDatabase(); } // create PDO-based sqlite storage $storage = new Pdo(array('dsn' => 'sqlite:' . $sqliteFile)); $app['storage'] = $storage; // if we created the db, lets put in some data if (!$dbFileExists) { $app['fixtures_manager']->populateSqliteDb(); } // create array of supported grant types // todo - update the documentation in _authentication.twig when we add more $grantTypes = array('authorization_code' => new AuthorizationCode($storage), 'client_credentials' => new ClientCredentials($storage), 'refresh_token' => new RefreshToken($storage, array('always_issue_new_refresh_token' => true))); // instantiate the oauth server $server = new OAuth2Server($storage, array('enforce_state' => false, 'allow_implicit' => true, 'access_lifetime' => 86400), $grantTypes); $app['api_actions'] = ['barn-unlock' => 'Unlock the Barn', 'toiletseat-down' => 'Put the Toilet Seat Down', 'chickens-feed' => 'Feed Your Chickens', 'eggs-collect' => 'Collect Eggs from Your Chickens', 'eggs-count' => 'Get the Number of Eggs Collected Today']; $app['scopes'] = array_merge($app['api_actions'], ['profile' => 'Access Your Profile Data']); // add scopes $memory = new Memory(array('supported_scopes' => array_keys($app['scopes']))); $server->setScopeUtil(new Scope($memory)); // add the server to the silex "container" so we can use it in our controllers (see src/OAuth2Demo/Server/Controllers/.*) $app['oauth_server'] = $server; /** * add HttpFoundataionBridge Response to the container, which returns a silex-compatible response object * @see (https://github.com/bshaffer/oauth2-server-httpfoundation-bridge) */ $app['oauth_response'] = new BridgeResponse(); }
/** * Create an OAuth2\Server instance. * * @return OAuth2Server * @throws Exception\RuntimeException */ public function __invoke() { if ($this->server) { return $this->server; } $config = $this->config; if (!isset($config['storage']) || empty($config['storage'])) { throw new Exception\RuntimeException('The storage configuration for OAuth2 is missing'); } $storagesServices = array(); if (is_string($config['storage'])) { $storagesServices[] = $config['storage']; } elseif (is_array($config['storage'])) { $storagesServices = $config['storage']; } else { throw new Exception\RuntimeException('The storage configuration for OAuth2 should be string or array'); } $storage = array(); foreach ($storagesServices as $storageKey => $storagesService) { $storage[$storageKey] = $this->services->get($storagesService); } $enforceState = isset($config['enforce_state']) ? $config['enforce_state'] : true; $allowImplicit = isset($config['allow_implicit']) ? $config['allow_implicit'] : false; $accessLifetime = isset($config['access_lifetime']) ? $config['access_lifetime'] : 3600; $audience = isset($config['audience']) ? $config['audience'] : ''; $options = isset($config['options']) ? $config['options'] : array(); $options = array_merge(array('enforce_state' => $enforceState, 'allow_implicit' => $allowImplicit, 'access_lifetime' => $accessLifetime), $options); // Pass a storage object or array of storage objects to the OAuth2 server class $server = new OAuth2Server($storage, $options); $availableGrantTypes = $config['grant_types']; if (isset($availableGrantTypes['client_credentials']) && $availableGrantTypes['client_credentials'] === true) { $clientOptions = array(); if (isset($options['allow_credentials_in_request_body'])) { $clientOptions['allow_credentials_in_request_body'] = $options['allow_credentials_in_request_body']; } // Add the "Client Credentials" grant type (it is the simplest of the grant types) $server->addGrantType(new ClientCredentials($server->getStorage('client_credentials'), $clientOptions)); } if (isset($availableGrantTypes['authorization_code']) && $availableGrantTypes['authorization_code'] === true) { // Add the "Authorization Code" grant type (this is where the oauth magic happens) $server->addGrantType(new AuthorizationCode($server->getStorage('authorization_code'))); } if (isset($availableGrantTypes['password']) && $availableGrantTypes['password'] === true) { // Add the "User Credentials" grant type $server->addGrantType(new UserCredentials($server->getStorage('user_credentials'))); } if (isset($availableGrantTypes['jwt']) && $availableGrantTypes['jwt'] === true) { // Add the "JWT Bearer" grant type $server->addGrantType(new JwtBearer($server->getStorage('jwt_bearer'), $audience)); } if (isset($availableGrantTypes['refresh_token']) && $availableGrantTypes['refresh_token'] === true) { $refreshOptions = array(); if (isset($options['always_issue_new_refresh_token'])) { $refreshOptions['always_issue_new_refresh_token'] = $options['always_issue_new_refresh_token']; } // Add the "Refresh Token" grant type $server->addGrantType(new RefreshToken($server->getStorage('refresh_token'), $refreshOptions)); } return $this->server = $server; }
/** @test */ public function getIdentity_shouldReturnTheUserCorrespondingToTheAccessToken_inQuery() { $this->oauthRequest->query['access_token'] = 'at123'; $this->oauthServer->shouldReceive('getAccessTokenData')->with($this->oauthRequest)->andReturn(['user_id' => 'jimmy']); $identity = M::mock('\\Aeris\\ZfAuth\\Identity\\IdentityInterface'); $this->identityRepository->shouldReceive('findByUsername')->with('jimmy')->andReturn($identity); $this->assertSame($identity, $this->identityProvider->getIdentity()); }
private function getTestServer($config = array()) { $storage = Bootstrap::getInstance()->getMemoryStorage(); $server = new Server($storage, $config); // Add the two types supported for authorization grant $server->addGrantType(new AuthorizationCode($storage)); return $server; }
private function getTestServer($config = array()) { $config += array('use_openid_connect' => true, 'issuer' => 'test', 'id_lifetime' => 3600, 'allow_implicit' => true); $memoryStorage = Bootstrap::getInstance()->getMemoryStorage(); $responseTypes = array('code' => $code = new AuthorizationCode($memoryStorage), 'id_token' => $idToken = new IdToken($memoryStorage, $memoryStorage, $config), 'code id_token' => new CodeIdToken($code, $idToken)); $server = new Server($memoryStorage, $config, array(), $responseTypes); $server->addGrantType(new ClientCredentials($memoryStorage)); return $server; }
private function getTestServer($config = array()) { $config += array('use_openid_connect' => true, 'issuer' => 'test', 'id_lifetime' => 3600); $memoryStorage = Bootstrap::getInstance()->getMemoryStorage(); $responseTypes = array('token' => $token = new AccessToken($memoryStorage, $memoryStorage), 'id_token' => $idToken = new IdToken($memoryStorage, $memoryStorage, $config), 'id_token token' => new IdTokenToken($token, $idToken)); $server = new Server($memoryStorage, $config, array(), $responseTypes); $server->addGrantType(new ClientCredentials($memoryStorage)); return $server; }
/** * @param mixed $config * @param mixed $name * @param Server|null $server * @return GrantTypeInterface * * @throws ConfigurationException */ public function create($config, $name = null, Server $server = null) { //If the config value is a string, assume that it's a grant type name, a class name, or a //service name if (is_string($config)) { if (class_exists($config)) { $config = array('class' => $config); } else { if ($obj = $this->resolveReference($config)) { return $obj; } else { $config = array('name' => $config); } } } //See if it's a preconfigured object or a closure if ($obj = $this->resolveReference($config)) { return $obj; } //Otherwise, try to manually instantiate a class if (is_array($config)) { //Determine name, if missing if (!isset($config['name'])) { if (is_string($name)) { $config['name'] = $name; } else { if (isset($config['class'])) { $config['name'] = $this->camelCaseToUnderscore($config['class']); } } } //Determine class, if missing if (isset($config['name']) && !isset($config['class'])) { $config['class'] = $this->grantTypeNamespace . $this->underscoreToCamelCase($config['name']); } //Call constructor with the appropriate parameters if (isset($config['class']) && class_exists($config['class'])) { $storage = null; if (isset($config['storage'])) { $storage = $this->resolveReference($config['storage']); } if (!$storage && $server && isset($config['name'])) { $storage = $server->getStorage($config['name']); } $class = $config['class']; if ($storage && isset($config['options'])) { return new $class($storage, $config['options']); } if ($storage) { return new $class($storage); } return new $class(); } } throw new ConfigurationException('Unable to find or instantiate grant type ' . $name . ' from configuration ' . print_r($config, true)); }
private function getTestServer() { $memoryStorage = Bootstrap::getInstance()->getMemoryStorage(); $storage = array('access_token' => new CryptoTokenStorage($memoryStorage), 'client' => $memoryStorage, 'client_credentials' => $memoryStorage); $server = new Server($storage); $server->addGrantType(new ClientCredentials($memoryStorage)); // make the "token" response type a CryptoToken $server->addResponseType(new CryptoToken($memoryStorage, $memoryStorage)); return $server; }
/** @return null|mixed */ protected function getIdentity() { $accessToken = $this->request->getQuery('access_token', $this->request->getPost('access_token')); if ($accessToken === null) { return null; } $oAuthRequest = OAuth2RequestFactory::create($this->request); $accessTokenData = $this->oauthServer->getAccessTokenData($oAuthRequest); return $this->identity = $this->identityStorageAdapter->findByUsername($accessTokenData['user_id']); }
private function getTestServer() { $memoryStorage = Bootstrap::getInstance()->getMemoryStorage(); $storage = array('access_token' => $memoryStorage, 'client' => $memoryStorage, 'device_code' => $memoryStorage); $server = new Server($storage); // make the "token" response type a DeviceCode response type $config = array('interval' => 5, 'verification_uri' => 'http://mysite.com/device'); $rsp = new DeviceCodeResponseType($memoryStorage, $config); $server->addResponseType($rsp); return $server; }
/** * Execute this middleware. * * @param ServerRequestInterface $request The PSR7 request. * @param ResponseInterface $response The PSR7 response. * @param callable $next The Next middleware. * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $oauth2Request = RequestBridge::toOAuth2($request); foreach ($this->scopes as $scope) { if ($this->server->verifyResourceRequest($oauth2Request, null, $scope)) { $this->container['token'] = $this->server->getResourceController()->getToken(); return $next($request, $response); } } return ResponseBridge::fromOAuth2($this->server->getResponse()); }
private function __construct() { // Database $db = (object) Config::get('database.connections.mysql'); $dsn = 'mysql:dbname=' . $db->database . ';host=' . $db->host; $pdoconfig = array('client_table' => 'oauth_clients', 'access_token_table' => 'oauth_access_tokens'); $storage = new Pdo(array('dsn' => $dsn, 'username' => $db->username, 'password' => $db->password), $pdoconfig); $this->server = new Server($storage, array('allow_implicit' => true, 'enforce_redirect' => true, 'access_lifetime' => 3600 * 24 * 365 * 2)); $this->server->addGrantType(new AuthorizationCode($storage)); $this->server->addGrantType(new RefreshToken($storage, array('always_issue_new_refresh_token' => true, 'refresh_token_lifetime' => 3600 * 24 * 31 * 2))); }
/** * Helper method to verify a resource request, allowing return early on success cases * * @param array $scopes Scopes required for authorization * * @return boolean True if the request is verified, otherwise false */ private function verify(array $scopes = [null]) { foreach ($scopes as $scope) { if (is_array($scope)) { $scope = implode(' ', $scope); } if ($this->server->verifyResourceRequest(MessageBridge::newOauth2Request($this->app->request()), null, $scope)) { return true; } } return false; }
/** * @return \OAuth2\Server */ public function __invoke() { if (null !== $this->_server) { return $this->_server; } $this->_server = $this->_factory->__invoke(); // register custom grant types $this->_server->addGrantType(new EmailCredentials($this->getServiceLocator()->get('CredentialsAdapter\\Email'))); $this->_server->addGrantType(new CodeCredentials($this->getServiceLocator()->get('CredentialsAdapter\\Code'))); $this->_server->addGrantType(new FacebookCredentials($this->getServiceLocator()->get('CredentialsAdapter\\Facebook'))); $this->_server->addGrantType(new GoogleCredentials($this->getServiceLocator()->get('CredentialsAdapter\\Google'))); return $this->_server; }
/** * {@inheritDoc} */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { try { $oauth2request = Util::convertRequestFromPsr7($request); if (!$this->server->verifyResourceRequest($oauth2request)) { return Util::convertResponseToPsr7($this->server->getResponse(), $response); } $request = $request->withAttribute('access_token', $this->server->getAccessTokenData($oauth2request)); } catch (\Exception $ex) { return new JsonResponse(['error' => $ex->getMessage(), 'error_description' => $ex->getMessage()], 500); } return $next($request, $response); }
/** * Create service * * @param ServiceLocatorInterface $serviceLocator * @throws \InvalidArgumentException * @return mixed */ public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('Config'); if (isset($config['parrot-oauth2'])) { $config = $config['parrot-oauth2']; $storage = array('user_credentials' => $serviceLocator->get('Parrot\\Oauth2\\Storage\\UserCredentials'), 'client_credentials' => $serviceLocator->get('Parrot\\Oauth2\\Storage\\ClientCredentials'), 'access_token' => $serviceLocator->get('Parrot\\Oauth2\\Storage\\AccessToken'), 'scope' => $serviceLocator->get('Parrot\\Oauth2\\Storage\\Scope')); $server = new Server($storage, $config); $server->setScopeUtil($serviceLocator->get('Parrot\\Oauth2\\Storage\\Scope')); return $server; } else { throw new InvalidArgumentException('Parrot OAuth2 requires a defined config'); } }
protected function authorize() { $authorized = false; if ($this->server->verifyResourceRequest(OAuth2Request::createFromGlobals())) { // authorized $authorized = true; } else { $request = $this->getRequest(); $token = $request->getPost('token', false); if ($token) { $authorized = $this->isGoogleAuthorized($token); } } return $authorized ? true : false; }
public function get() { $conn = ['db' => 'projekta']; $mongo = new \MongoClient('mongodb://localhost', $conn); $db = $mongo->selectDB("projekta"); $storage = new Mongo($db); $server = new OauthServer($storage); //Password Grant $passwordGrant = new UserCredentials($storage); $server->addGrantType($passwordGrant); //RefreshToken Grant $refreshTokenGrant = new RefreshToken($storage); $server->addGrantType($refreshTokenGrant); return $server; }
/** * @return OAuth2Server */ protected function bootstrap() { $db = $this->db; $config = ['user_table' => 'users']; $storage = new StoragePdo($db->getInternalHandler(), $config); // Pass a storage object or array of storage objects to the OAuth2 server class $server = new OAuth2Server($storage); // Add the "Client Credentials" grant type (it is the simplest of the grant types) $server->addGrantType(new ClientCredentials($storage)); // Add the "Authorization Code" grant type (this is where the oauth magic happens) $server->addGrantType(new AuthorizationCode($storage)); // add the grant type to your OAuth server $server->addGrantType(new UserCredentials($storage)); return $server; }
/** * Authorize action (/oauth/authorize) */ public function authorizeAction() { $server = $this->getOAuth2Server($this->params('oauth')); $request = $this->getOAuth2Request(); $response = new OAuth2Response(); // validate the authorize request $isValid = $this->server->validateAuthorizeRequest($request, $response); if (!$isValid) { return $this->getErrorResponse($response); } $authorized = $request->request('authorized', false); if (empty($authorized)) { $clientId = $request->query('client_id', false); $view = new ViewModel(['clientId' => $clientId]); $view->setTemplate('oauth/authorize'); return $view; } $isAuthorized = $authorized === 'yes'; $userIdProvider = $this->userIdProvider; $this->server->handleAuthorizeRequest($request, $response, $isAuthorized, $userIdProvider($this->getRequest())); $redirect = $response->getHttpHeader('Location'); if (!empty($redirect)) { return $this->redirect()->toUrl($redirect); } return $this->getErrorResponse($response); }
/** * Invoke this route callback. * * @param ServerRequestInterface $request Represents the current HTTP request. * @param ResponseInterface $response Represents the current HTTP response. * @param array $arguments Values for the current route’s named placeholders. * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $arguments = []) { $oauth2Request = Http\RequestBridge::toOAuth2($request); $oauth2Response = new OAuth2\Response(); if (!$this->server->validateAuthorizeRequest($oauth2Request, $oauth2Response)) { return Http\ResponseBridge::fromOAuth2($oauth2Response); } $authorized = $oauth2Request->request('authorized'); if (empty($authorized)) { $response = Http\ResponseBridge::fromOAuth2($oauth2Response); $this->view->render($response, $this->template, ['client_id' => $oauth2Request->query('client_id')]); return $response->withHeader('Content-Type', 'text/html'); } $this->server->handleAuthorizeRequest($oauth2Request, $oauth2Response, $authorized === 'yes'); return Http\ResponseBridge::fromOAuth2($oauth2Response); }
protected function authorize(OAuth2Request $request) { $response = new OAuth2Response(); $authService = $this->getAuthenticationService(); // validate the authorize request if (!$this->server->validateAuthorizeRequest($request, $response)) { return $this->handleResponse($response); } if (!$authService->hasIdentity()) { return $this->handleNoIdentity(); } $identityId = $authService->getIdentity(); //TODO request authorization from an user /** $authorized = $request->request('authorized', false); if (empty($authorized)) { $clientId = $request->query('client_id', false); $view = new ViewModel(array('clientId' => $clientId)); $view->setTemplate('oauth/authorize'); return $view; } $is_authorized = ($authorized === 'yes'); */ $is_authorized = true; $this->server->handleAuthorizeRequest($request, $response, $is_authorized, $identityId); return $this->handleResponse($response); }
public function handleTokenRequest(HttpRequest $httpRequest, HttpResponse $httpResponse) { $oauthRequest = $this->buildRequest($httpRequest); $oauthResponse = $this->server->handleTokenRequest($oauthRequest); $format = $this->determineFormat($httpRequest); return $this->buildResponse($format, $httpResponse, $oauthResponse); }
public function handleUserInfoRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null) { if ($request === null) { $request = $this->module->getRequest(); } return parent::handleUserInfoRequest($request, $response); }
/** * {@inheritDoc} */ public function authenticate(TokenInterface $token) { $oauthRequest = OAuthRequest::createFromRequest($token->request); // Not authenticated if (!$this->server->verifyResourceRequest($oauthRequest)) { throw new AuthenticationException('OAuth2 authentication failed'); } $userData = $this->server->getAccessTokenData($oauthRequest); $user = $this->userProvider->findById($userData['user_id']); $roles = $this->roleFinder->findRoleNamesByUserId($user->getId()); $user->setRoles($roles); $authenticatedToken = new OAuth2UserToken($roles); $authenticatedToken->setUser($user); $authenticatedToken->setAuthenticated(true); $authenticatedToken->setOAuthToken($token->getOAuthToken()); return $authenticatedToken; }