Ejemplo n.º 1
0
 public function token()
 {
     $request = Request::createFromGlobals();
     // Handle a request for an OAuth2.0 Access Token and send the response to the client
     $tr = $this->server->handleTokenRequest($request);
     $tr->send();
 }
Ejemplo n.º 2
0
 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 handleTokenRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null)
 {
     if ($request === null) {
         $request = $this->module->getRequest();
     }
     return parent::handleTokenRequest($request, $response);
 }
Ejemplo n.º 4
0
 public function providerAction()
 {
     $services = $this->getServiceLocator()->get('ServiceManager');
     $config = $services->get('Configuration');
     // Make sure the provider is enabled, else 404
     $provider = $this->params('provider');
     if (!in_array(strtolower($provider), $this->getEnabledProviders($config))) {
         return $this->notFoundAction();
     }
     try {
         // try to authenticate with the selected provider
         $adapter = $this->hybrid->authenticate($provider);
         // then grab the user profile
         $user_profile = $adapter->getUserProfile();
         // then grab the user profile
         $access_token = $adapter->getAccessToken();
     } catch (Exception $e) {
         echo "Error: please try again!";
         echo "Original error message: " . $e->getMessage();
     }
     $pdo = $services->get('ZF\\OAuth2\\Adapter\\PdoAdapter');
     $user = $pdo->getUser($user_profile->displayName);
     if (!$user) {
         $pdo->setUser($user_profile->displayName, $this->generatePassword(), $user_profile->firstName, $user_profile->lastName);
         $pdo->setUserProvider($provider, $user_profile->identifier, $user_profile->displayName);
     } else {
         $pdo->setUserProvider($provider, $user_profile->identifier, $user_profile->displayName);
         $pdo->setUserProviderAccessToken($access_token['access_token'], $provider, $user_profile->identifier, $user_profile->displayName);
     }
     //from here on it is oauth time
     if (!isset($config['zf-oauth2']['storage']) || empty($config['zf-oauth2']['storage'])) {
         throw new Exception\RuntimeException('The storage configuration [\'zf-oauth2\'][\'storage\'] for OAuth2 is missing');
     }
     $oauth2request = $this->getOAuth2Request($user_profile->displayName, $provider, $user_profile->identifier, $access_token['access_token']);
     $response = $this->server->handleTokenRequest($oauth2request);
     if ($response->isClientError()) {
         $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']));
     }
     //Get Access token from OAuth response
     $parameters = $response->getParameters();
     $access_token = $parameters['access_token'];
     return $this->redirect()->toUrl($config['social-oauth2']['redirect_endpoint'] . '/' . $user_profile->displayName . '?access_token=' . $access_token);
 }
Ejemplo n.º 5
0
 /**
  * This is the client authorize endpoint.
  * Requires a route like so:
  * {
  *      "url":			"/api/authorize",
  *      "controller":	"<NameOfYourController>",
  *      "action":		"getOAuth2Token"
  * }
  * 
  * Then the client would post to http(s)://<yourdomain.com>/api/authorize/ 
  * with data appropriate for the grant type to get an access_token for use 
  * in subsequent calls (defined in your controller).
  * 
  * @see initOAth2
  * @documen nodoc
  */
 public function getOAuth2Token()
 {
     if ($this->oauthServer === null) {
         $this->respondError("OAuth2 is not enabled for this web service.");
     } else {
         // Respond with a new token
         $this->oauthServer->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send();
     }
 }
 /**
  * Token Action (/oauth)
  */
 public function tokenAction()
 {
     $request = $this->getRequest();
     if (!$request instanceof HttpRequest) {
         // not an HTTP request; nothing left to do
         return;
     }
     if ($request->isOptions()) {
         // OPTIONS request.
         // This is most likely a CORS attempt; as such, pass the response on.
         return $this->getResponse();
     }
     $oauth2request = $this->getOAuth2Request();
     $response = $this->server->handleTokenRequest($oauth2request);
     if ($response->isClientError()) {
         $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']));
     }
     return $this->setHttpResponse($response);
 }
 /**
  * This method inspects the request and routes the data
  * to the correct method
  *
  * @return void
  */
 public function create($data)
 {
     $usersTable = $this->getUsersTable();
     $user = $usersTable->getByUsername($data['username']);
     $bcrypt = new Bcrypt();
     if (!empty($user) && $bcrypt->verify($data['password'], $user->password)) {
         $storage = new Pdo($usersTable->adapter->getDriver()->getConnection()->getConnectionParameters());
         $server = new Server($storage);
         $server->addGrantType(new ClientCredentials($storage));
         $response = $server->handleTokenRequest(Request::createFromGlobals());
         if (!$response->isSuccessful()) {
             $result = new JsonModel(array('result' => false, 'errors' => 'Invalid oauth'));
         }
         return new JsonModel($response->getParameters());
     } else {
         $result = new JsonModel(array('result' => false, 'errors' => 'Invalid Username or password'));
     }
     return $result;
 }
Ejemplo n.º 8
0
 /**
  * Handle an OAuth token request
  *
  * (Implements the "Resource Owner Password Credentials" grant type
  * or Part 3 of the "Authorization Code" grant type)
  *
  * Note: Expects input as POST variables, not JSON request body
  *
  * @link http://tools.ietf.org/html/rfc6749#section-4.3.2 Access Token Request
  * @param  Request $request
  * @return Response
  */
 public function token(Request $request)
 {
     $bridgeResponse = new BridgeResponse();
     $oauthRequest = OAuthRequest::createFromRequest($request);
     $response = $this->server->handleTokenRequest($oauthRequest, $bridgeResponse);
     if ($response->isOk()) {
         $user = $this->userService->findById($response->getParameter('user_id'));
         if (!$user) {
             return $this->createInvalidCredentialResponse();
         }
         if (!$user->getEnabled()) {
             return $this->createInvalidCredentialResponse();
         }
         // If enabled in config, check that user is verified
         if ($this->requireVerification && !$user->getVerified()) {
             return $this->createSimpleResponse(422, 'Unverified user');
         }
         $userId = $response->getParameter('user_id');
         $this->setLastLogin($userId);
         $this->session->set('user', $userId);
     }
     return $response;
 }
Ejemplo n.º 9
0
 public function testCustomClientAssertionType()
 {
     $request = TestRequest::createPost(array('grant_type' => 'authorization_code', 'client_id' => 'Test Client ID', 'code' => 'testcode'));
     // verify the mock clientAssertionType was called as expected
     $clientAssertionType = $this->getMock('OAuth2\\ClientAssertionType\\ClientAssertionTypeInterface', array('validateRequest', 'getClientId'));
     $clientAssertionType->expects($this->once())->method('validateRequest')->will($this->returnValue(true));
     $clientAssertionType->expects($this->once())->method('getClientId')->will($this->returnValue('Test Client ID'));
     // create mock storage
     $storage = Bootstrap::getInstance()->getMemoryStorage();
     $server = new Server(array($storage), array(), array(), array(), null, null, $clientAssertionType);
     $server->handleTokenRequest($request, $response = new Response());
 }
Ejemplo n.º 10
0
 public function testCanReceiveAccessTokenUsingPasswordGrantTypeWithoutClientSecret()
 {
     // add the test parameters in memory
     $storage = Bootstrap::getInstance()->getMemoryStorage();
     $server = new Server($storage);
     $server->addGrantType(new UserCredentials($storage));
     $request = TestRequest::createPost(array('grant_type' => 'password', 'client_id' => 'Test Client ID For Password Grant', 'username' => 'johndoe', 'password' => 'password'));
     $server->handleTokenRequest($request, $response = new Response());
     $this->assertTrue($response instanceof Response);
     $this->assertEquals(200, $response->getStatusCode(), var_export($response, 1));
     $this->assertNull($response->getParameter('error'));
     $this->assertNull($response->getParameter('error_description'));
     $this->assertNotNull($response->getParameter('access_token'));
     $this->assertNotNull($response->getParameter('expires_in'));
     $this->assertNotNull($response->getParameter('token_type'));
 }
Ejemplo n.º 11
0
 public function testEnforceScope()
 {
     $storage = Bootstrap::getInstance()->getMemoryStorage();
     $server = new Server($storage);
     $server->addGrantType(new ClientCredentials($storage));
     $scope = new Scope(array('default_scope' => false, 'supported_scopes' => array('testscope')));
     $server->setScopeUtil($scope);
     $request = TestRequest::createPost(array('grant_type' => 'client_credentials', 'client_id' => 'Test Client ID', 'client_secret' => 'TestSecret'));
     $response = $server->handleTokenRequest($request);
     $this->assertEquals($response->getStatusCode(), 400);
     $this->assertEquals($response->getParameter('error'), 'invalid_scope');
     $this->assertEquals($response->getParameter('error_description'), 'This application requires you specify a scope parameter');
 }
 /**
  * Handle an OAuth2 Token request.
  * https://github.com/bshaffer/oauth2-demo-php/blob/master/src/OAuth2Demo/Server/Controllers/Token.php
  *
  * @param HttpFoundation\Request $request
  * @return \OAuth2\Response|\OAuth2\ResponseInterface
  */
 public function postToken(HttpFoundation\Request $request)
 {
     $this->log->addDebug(print_r($request, true), ['namespace' => 'HackTheDinos\\Controllers\\OAuth', 'method' => 'postToken', 'type' => 'request']);
     //Make sure to pass in the HttpFoundationBridge\Response otherwise you'll get back 200s instead of 400s
     return $this->server->handleTokenRequest(HttpFoundationBridge\Request::createFromRequest($request), new HttpFoundationBridge\Response());
 }
Ejemplo n.º 13
0
 /**
  * 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 RequestInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $arguments = [])
 {
     return ResponseBridge::fromOAuth2($this->server->handleTokenRequest(RequestBridge::toOAuth2($request)));
 }
Ejemplo n.º 14
0
 public function __invoke()
 {
     $request = MessageBridge::newOAuth2Request($this->slim->request());
     MessageBridge::mapResponse($this->server->handleTokenRequest($request), $this->slim->response());
 }
Ejemplo n.º 15
0
 /**
  * Stage 3: Client directly calls this api to exchange access token
  *
  * It can then use this access token to make calls to protected api
  *
  * @format JsonFormat,UploadFormat
  */
 public function postGrant()
 {
     static::$server->handleTokenRequest(static::$request)->send();
     exit;
 }