/** * {@inheritdoc} */ public function authenticate(TokenInterface $token) { if (!$this->supports($token)) { return null; } try { $tokenString = $token->getToken(); if ($accessToken = $this->serverService->verifyAccessToken($tokenString)) { $scope = $accessToken->getScope(); $user = $accessToken->getUser(); $roles = null !== $user ? $user->getRoles() : array(); if (!empty($scope)) { foreach (explode(' ', $scope) as $role) { $roles[] = 'ROLE_' . strtoupper($role); } } $token = new OAuthToken($roles); $token->setAuthenticated(true); $token->setToken($tokenString); if (null !== $user) { $token->setUser($user); } return $token; } } catch (OAuth2ServerException $e) { throw new AuthenticationException('OAuth2 authentication failed', null, 0, $e); } throw new AuthenticationException('OAuth2 authentication failed'); }
/** * Creates and returns access token for a user * @param AdvancedUserInterface $user [description] * @return [type] [description] */ public function generateAccessToken(AdvancedUserInterface $user) { if (is_null($user->getOAuthClient()->getId())) { throw new \Exception('User must have an OAuth Client', 500); } // Search valid token $oauth_access_token = $this->oauth_manipulator->getValidTokenForClient($user->getOAuthClient()); if (!is_null($oauth_access_token)) { return $oauth_access_token->getToken(); } // Or else, creates a new one // Forge request to satisfy OAuth2 server $request = new Request(); $request->query->add(['client_id' => $user->getOAuthClient()->getPublicId(), 'response_type' => OAuth2::RESPONSE_TYPE_ACCESS_TOKEN, 'redirect_uri' => $user->getOAuthClient()->getRedirectUris()[0]]); $response = $this->oauth2->finishClientAuthorization(true, $user, $request, null); if ($response instanceof Response) { $location = str_replace('#', '?', $response->headers->get('location')); $query_string = parse_url($location, PHP_URL_QUERY); parse_str($query_string, $queries); if (isset($queries['access_token'])) { $access_token = $queries['access_token']; return $access_token; } } else { throw new Exception("Token creation ; unknown response type : " . get_class($response), 500); } }
/** * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event The event. */ public function handle(GetResponseEvent $event) { $request = $event->getRequest(); if (null === ($oauthToken = $this->serverService->getBearerToken($event->getRequest(), true))) { //if it's null, then we try to regular authentication... $token = $this->handleCookie($event); if ($token) { $this->securityContext->setToken($token); return; } } $token = new OAuthToken(); $token->setToken($oauthToken); $returnValue = $this->authenticationManager->authenticate($token); try { $returnValue = $this->authenticationManager->authenticate($token); if ($returnValue instanceof TokenInterface) { return $this->securityContext->setToken($returnValue); } if ($returnValue instanceof Response) { return $event->setResponse($returnValue); } } catch (AuthenticationException $e) { if (null !== ($p = $e->getPrevious())) { $event->setResponse($p->getHttpResponse()); } } }
/** * @param Request $request * @return type */ public function tokenAction(Request $request) { try { return $this->server->grantAccessToken($request); } catch (OAuth2ServerException $e) { return $e->getHttpResponse(); } }
/** * {@inheritdoc} */ public function authenticate(TokenInterface $token) { if (!$this->supports($token)) { return; } try { $tokenString = $token->getToken(); if ($accessToken = $this->serverService->verifyAccessToken($tokenString)) { $scope = $accessToken->getScope(); $user = $accessToken->getUser(); if (null !== $user) { try { $this->userChecker->checkPreAuth($user); } catch (AccountStatusException $e) { throw new OAuth2AuthenticateException(OAuth2::HTTP_UNAUTHORIZED, OAuth2::TOKEN_TYPE_BEARER, $this->serverService->getVariable(OAuth2::CONFIG_WWW_REALM), 'access_denied', $e->getMessage()); } $token->setUser($user); } $roles = null !== $user ? $user->getRoles() : array(); /* * This is the only modification from the base class. * We only add scopes if we're not connected as user. * Otherwise, if we support the scope admin, everyone will be admin if no scope are requested because fos-oauth2-lib * doesn't support different scope by clients (https://github.com/FriendsOfSymfony/FOSOAuthServerBundle/issues/201) * This way, we can bypass this by creating 2 clients: 1 wich grant the password (and refresh) types * (and will require a user authentication) * One that grant pretty much all the rest. */ if (!$user) { if (!empty($scope)) { foreach (explode(' ', $scope) as $role) { $roles[] = 'ROLE_' . strtoupper($role); } } } $roles = array_unique($roles, SORT_REGULAR); $token = new OAuthToken($roles); $token->setAuthenticated(true); $token->setToken($tokenString); if (null !== $user) { try { $this->userChecker->checkPostAuth($user); } catch (AccountStatusException $e) { throw new OAuth2AuthenticateException(OAuth2::HTTP_UNAUTHORIZED, OAuth2::TOKEN_TYPE_BEARER, $this->serverService->getVariable(OAuth2::CONFIG_WWW_REALM), 'access_denied', $e->getMessage()); } $token->setUser($user); } return $token; } } catch (OAuth2ServerException $e) { if (!method_exists('Symfony\\Component\\Security\\Core\\Exception\\AuthenticationException', 'setToken')) { // Symfony 2.1 throw new AuthenticationException('OAuth2 authentication failed', null, 0, $e); } throw new AuthenticationException('OAuth2 authentication failed', 0, $e); } throw new AuthenticationException('OAuth2 authentication failed'); }
/** * If the user is logged generates the access token and sets into response creating a cookie. * * @param \Kreta\Bundle\UserBundle\Event\AuthorizationEvent $event The authorization event */ public function onAuthorizationEvent(AuthorizationEvent $event) { $client = $this->clientManager->findClientBy(['secret' => $this->clientSecret]); $session = $event->getRequest()->getSession(); $request = new Request(); $request->query->add(['grant_type' => 'password', 'client_secret' => $this->clientSecret, 'client_id' => sprintf('%s_%s', $client->getId(), $client->getRandomId()), 'username' => $session->get('_email'), 'password' => $session->get('_password')]); $response = $this->oauthServer->grantAccessToken($request); $token = json_decode($response->getContent(), true); $event->getRequest()->getSession()->remove('_email'); $event->getRequest()->getSession()->remove('_password'); $event->getRequest()->getSession()->replace(['access_token' => $token['access_token'], 'refresh_token' => $token['refresh_token']]); }
public function testErrorResponseContainsExtraHeaders() { $config = array(OAuth2::CONFIG_RESPONSE_EXTRA_HEADERS => array("Access-Control-Allow-Origin" => "http://www.foo.com", "X-Extra-Header-1" => "Foo-Bar")); $stub = new OAuth2GrantUserStub(); $stub->addClient(new OAuth2Client('cid', 'cpass')); $stub->addUser('foo', 'bar'); $stub->setAllowedGrantTypes(array('authorization_code', 'password')); $oauth2 = new OAuth2($stub, $config); $response = $oauth2->grantAccessToken(new Request(array('grant_type' => 'password', 'client_id' => 'cid', 'client_secret' => 'cpass', 'username' => 'foo', 'password' => 'bar'))); $this->assertSame("http://www.foo.com", $response->headers->get("Access-Control-Allow-Origin")); $this->assertSame("Foo-Bar", $response->headers->get("X-Extra-Header-1")); }
/** * Tests OAuth2->grantAccessToken() with successful Auth code grant, but without redreict_uri in the input */ public function testGrantAccessTokenWithGrantAuthCodeSuccessWithoutRedirect() { $request = new Request(array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'my_little_app', 'client_secret' => 'b', 'code' => 'foo')); $storedToken = new OAuth2AuthCode('my_little_app', '', time() + 60, null, null, 'http://www.example.com'); $mockStorage = $this->createBaseMock('OAuth2\\IOAuth2GrantCode'); $mockStorage->expects($this->any())->method('getAuthCode')->will($this->returnValue($storedToken)); $this->fixture = new OAuth2($mockStorage); $this->fixture->setVariable(OAuth2::CONFIG_ENFORCE_INPUT_REDIRECT, false); $response = $this->fixture->grantAccessToken($request); // Successful token grant will return a JSON encoded token: $this->assertRegexp('/{"access_token":".*","expires_in":\\d+,"token_type":"bearer"/', $response->getContent()); }
/** * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event The event. */ public function handle(GetResponseEvent $event) { $request = $event->getRequest(); if (null === ($oauthToken = $this->serverService->getBearerToken($event->getRequest(), true))) { if ($this->tryCookieAuth($event)) { return; } if ($this->tryHTTPAuth($event)) { return; } $this->authenticateAnonymous(); } else { $this->tryOauthAuth($event, $oauthToken); } }
/** * Tests OAuth2->grantAccessToken() with implicit * */ public function testRejectedAccessTokenWithGrantImplicit() { //$this->fixture->grantAccessToken(/* parameters */); $stub = new OAuth2ImplicitStub(); $stub->addClient(new OAuth2Client('blah', 'foo', array('http://www.example.com/'))); $oauth2 = new OAuth2($stub); $data = new \stdClass(); try { $response = $oauth2->finishClientAuthorization(false, $data, new Request(array('client_id' => 'blah', 'redirect_uri' => 'http://www.example.com/?foo=bar', 'state' => '42', 'response_type' => 'token'))); $this->fail('The expected exception OAuth2ServerException was not thrown'); } catch (OAuth2ServerException $e) { $this->assertSame('access_denied', $e->getMessage()); $this->assertSame('The user denied access to your application', $e->getDescription()); $this->assertSame(array('Location' => 'http://www.example.com/?foo=bar#error=access_denied&error_description=The+user+denied+access+to+your+application&state=42'), $e->getResponseHeaders()); } }
/** * {@inheritdoc} */ public function authenticate(TokenInterface $token) { if (!$this->supports($token)) { return; } try { $tokenString = $token->getToken(); if ($accessToken = $this->serverService->verifyAccessToken($tokenString)) { $scope = $accessToken->getScope(); $user = $accessToken->getUser(); if (null !== $user) { try { $this->userChecker->checkPreAuth($user); } catch (AccountStatusException $e) { throw new OAuth2AuthenticateException(OAuth2::HTTP_UNAUTHORIZED, OAuth2::TOKEN_TYPE_BEARER, $this->serverService->getVariable(OAuth2::CONFIG_WWW_REALM), 'access_denied', $e->getMessage()); } $token->setUser($user); } $roles = null !== $user ? $user->getRoles() : array(); if (!empty($scope)) { foreach (explode(' ', $scope) as $role) { $roles[] = 'ROLE_' . strtoupper($role); } } $roles = array_unique($roles); $token = new OAuthToken($roles); $token->setAuthenticated(true); $token->setToken($tokenString); if (null !== $user) { try { $this->userChecker->checkPostAuth($user); } catch (AccountStatusException $e) { throw new OAuth2AuthenticateException(OAuth2::HTTP_UNAUTHORIZED, OAuth2::TOKEN_TYPE_BEARER, $this->serverService->getVariable(OAuth2::CONFIG_WWW_REALM), 'access_denied', $e->getMessage()); } $token->setUser($user); } return $token; } } catch (OAuth2ServerException $e) { if (!method_exists('Symfony\\Component\\Security\\Core\\Exception\\AuthenticationException', 'setToken')) { // Symfony 2.1 throw new AuthenticationException('OAuth2 authentication failed', null, 0, $e); } throw new AuthenticationException('OAuth2 authentication failed', 0, $e); } throw new AuthenticationException('OAuth2 authentication failed'); }
public function session() { if (Request::segment(2) == 'facebook') { $provider = OAuth2::provider('facebook', array('id' => '494491330565385', 'secret' => '1dd38781d55ed1825724e433ef1ce6e3')); } // if(Request::segment(2) == 'twitter'){ // $provider = OAuth2::provider('twitter', array( // 'id' => '494491330565385', // 'secret' => '1dd38781d55ed1825724e433ef1ce6e3', // )); // } if (Request::segment(2) == 'google') { $provider = OAuth2::provider('google', array('id' => '406188381495-cil9u3fcb7jtu3hq2idinp3s92qvr8f6.apps.googleusercontent.com', 'secret' => 'ZOGyJqHOl5xMfGVQ-wTInqUs')); } if (Request::segment(2) == 'github') { $provider = OAuth2::provider('github', array('id' => '67d050b4c06ad12d95be', 'secret' => '4a03507448e3ffd9904eaa7b6fc7d3d75c373739', 'scope' => 'user:email')); } // if(Request::segment(2) == 'stackexchange'){ // $provider = OAuth2::provider('stackexchange', array( // 'id' => '494491330565385', // 'secret' => '1dd38781d55ed1825724e433ef1ce6e3', // )); // } if (!isset($_GET['code'])) { // By sending no options it'll come back here return $provider->authorize(); } else { // Howzit? try { $params = $provider->access($_GET['code']); $token = new Token_Access(array('access_token' => $params->access_token)); $data = $provider->get_user_info($token); // Here you should use this information to A) look for a user B) help a new user sign up with existing data. // If you store it all in a cookie and redirect to a registration page this is crazy-simple. // return $data; $user_id = $this->checkAndSave($data); if ($user_id == false) { return Redirect::back()->with('error', 'Your email was not public. Please join with another provider.'); //return Response::json(array()); } } catch (OAuth2_Exception $e) { show_error('That didnt work: ' . $e); } } // return Redirect::to('auth/signin')->with('oauth', $data); // return Response::json(array('success' => Lang::get('auth/message.signin.success'))); // return Redirect::to('devs/'.$user_id); // return Redirect::back(); //breaks some times //check for any pending posts and assign then to the signed in user $redirect = All::completePosting(); $redirect = !empty($redirect) ? $redirect : Session::get('loginRedirect', 'account'); return Redirect::to($redirect); // so you can complete creating the post you were creating. temp solutin }
function it_listens_interactive_login(InteractiveLoginEvent $interactiveLoginEvent, TokenInterface $token, UserInterface $user, Request $request, SessionInterface $session, ParameterBagInterface $parameterBag, ClientManagerInterface $clientManager, ClientInterface $client, OAuth2 $oauthServer, Response $response) { $interactiveLoginEvent->getAuthenticationToken()->shouldBeCalled()->willReturn($token); $token->getUser()->shouldBeCalled()->willReturn($user); $interactiveLoginEvent->getRequest()->shouldBeCalled()->willReturn($request); $parameterBag->get('_username')->shouldBeCalled()->willReturn('*****@*****.**'); $parameterBag->get('_password')->shouldBeCalled()->willReturn('123456'); $request->request = $parameterBag; $request->getSession()->shouldBeCalled()->willReturn($session); $session->set('_email', '*****@*****.**')->shouldBeCalled(); $session->set('_password', '123456')->shouldBeCalled(); $clientManager->findClientBy(['secret' => 'client-secret'])->shouldBeCalled()->willReturn($client); $client->getId()->shouldBeCalled()->willReturn('the-id'); $client->getRandomId()->shouldBeCalled()->willReturn('random-id'); $session->get('_email')->shouldBeCalled()->willReturn('*****@*****.**'); $session->get('_password')->shouldBeCalled()->willReturn('123456'); $oauthServer->grantAccessToken(Argument::type('Symfony\\Component\\HttpFoundation\\Request'))->shouldBeCalled()->willReturn($response); $response->getContent()->shouldBeCalled()->willReturn('the response content'); $session->remove('_email')->shouldBeCalled()->willReturn('*****@*****.**'); $session->remove('_password')->shouldBeCalled()->willReturn('123456'); $session->replace(['access_token' => null, 'refresh_token' => null])->shouldBeCalled(); $this->onInteractiveLogin($interactiveLoginEvent); }
/** * @dataProvider getTestGetBearerTokenData */ public function testGetBearerToken(Request $request, $token, $remove = false, $exception = null, $exceptionMessage = null, $headers = null, $body = null) { $mock = $this->getMock('OAuth2\\IOAuth2Storage'); $oauth2 = new OAuth2($mock); try { $this->assertSame($token, $oauth2->getBearerToken($request, $remove)); if ($exception) { $this->fail('The expected exception OAuth2ServerException was not thrown'); } if ($remove) { $this->assertNull($request->headers->get('AUTHORIZATION')); $this->assertNull($request->query->get('access_token')); $this->assertNull($request->request->get('access_token')); } } catch (\Exception $e) { if (!$exception || !$e instanceof $exception) { throw $e; } $this->assertSame($headers, $e->getResponseHeaders()); $this->assertSame($body, $e->getResponseBody()); } }
<?php /** * @file * Sample token endpoint. * * Obviously not production-ready code, just simple and to the point. * * In reality, you'd probably use a nifty framework to handle most of the crud for you. */ use OAuth2\OAuth2; use OAuth2\OAuth2ServerException; require 'lib/bootstrap.php'; $oauth = new OAuth2(new OAuth2StoragePDO(newPDO())); try { $response = $oauth->grantAccessToken(); $response->send(); } catch (OAuth2ServerException $oauthError) { $oauthError->getHttpResponse()->send(); }
<?php /** * @file * Sample protected resource. * * Obviously not production-ready code, just simple and to the point. * * In reality, you'd probably use a nifty framework to handle most of the crud for you. */ use OAuth2\OAuth2; use OAuth2\OAuth2ServerException; require 'lib/bootstrap.php'; $oauth = new OAuth2(new OAuth2StoragePDO(newPDO())); try { $token = $oauth->getBearerToken(); $oauth->verifyAccessToken($token); } catch (OAuth2ServerException $oauthError) { $oauthError->sendHttpResponse(); } // With a particular scope, you'd do: // $oauth->verifyAccessToken("scope_name"); ?> <html> <head> <title>Hello!</title> </head> <body> <p>This is a secret.</p> </body>
use OAuth2\OAuth2ServerException; require 'lib/bootstrap.php'; // Clickjacking prevention (supported by IE8+, FF3.6.9+, Opera10.5+, Safari4+, Chrome 4.1.249.1042+) header('X-Frame-Options: DENY'); /* * You would need to authenticate the user before authorization. * * Below is some psudeo-code to show what you might do: * session_start(); if (!isLoggedIn()) { redirectToLoginPage(); exit(); } */ $oauth = new OAuth2(new OAuth2StoragePDO(newPDO())); if ($_POST) { $userId = 123; // Use whatever method you have for identifying users. try { $response = $oauth->finishClientAuthorization($_POST["accept"] == "Yep", $userId); $response->send(); } catch (OAuth2ServerException $e) { $e->getHttpResponse()->send(); } exit; } try { $auth_params = $oauth->getAuthorizeParams(); } catch (OAuth2ServerException $oauthError) { $oauthError->sendHttpResponse();
public function testUse() { $client = $this->storage->getClient(1); $access_token = $this->oauth2->createAccessToken($client, array()); $a = $this->oauth2->verifyAccessToken($access_token['access_token']); $this->assertInstanceOf('\\ebussola\\oauth\\AccessToken', $a); }