public function issueAuthCode(Request $request) { $authParams = $this->service('session')->get('authParams'); $this->service('session')->remove('authParams'); $this->service('session')->remove('redirectTo'); if ($request->get('authorization') === 'Approve') { $user = $this->identityProvider->getCurrentUser(); $redirectUri = $this->server->getGrantType('authorization_code')->newAuthorizeRequest('user', $user->id, $authParams); return $this->setStatusCode(Response::HTTP_FOUND)->respond('', ['Location' => $redirectUri]); } else { $error = new AccessDeniedException(); $redirectUri = RedirectUri::make($authParams['redirect_uri'], ['error' => $error->errorType, 'message' => $error->getMessage()]); return $this->setStatusCode(Response::HTTP_FOUND)->respond('', ['Location' => $redirectUri]); } }
/** * @param string $authGrant Grant type * @return bool|\Cake\Network\Response|void */ public function checkAuthParams($authGrant) { $controller = $this->_registry->getController(); try { return $this->Server->getGrantType($authGrant)->checkAuthorizeParams(); } catch (\OAuthException $e) { if ($e->shouldRedirect()) { return $controller->redirect($e->getRedirectUri()); } $controller->RequestHandler->renderAs($this, 'json'); $controller->response->statusCode($e->httpStatusCode); $controller->response->header($e->getHttpHeaders()); $controller->set('response', $e); return false; } }
/** * Authorization code grant. * * @param Request $request * * @return Response */ public function grantAuthorisationCode(Request $request) { $this->authorisationServer->setRequest($request); try { // Ensure the parameters in the query string are correct $authParams = $this->authorisationServer->getGrantType('authorization_code')->checkAuthorizeParams(); // Everything is okay, save $authParams to the a session and // redirect the user to sign-in $this->storeAuthParams($authParams); return new Response('', 302, ['Location' => '/signin']); } catch (OAuthException $e) { if ($e->shouldRedirect()) { return new Response('', 302, ['Location' => $e->getRedirectUri()]); } return $this->getExceptionResponse($e); } }
/** * Do client authorization based on user login. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ protected function completeAuthorizationFlow(Request $request, User $user) { // First create OAuth Auth Code $server = new AuthorizationServer(); $server->setSessionStorage(new SessionStorage()); $server->setAccessTokenStorage(new AccessTokenStorage()); $server->setClientStorage(new ClientStorage()); $server->setScopeStorage(new ScopeStorage()); $server->setAuthCodeStorage(new AuthCodeStorage()); $server->setRefreshTokenStorage(new RefreshTokenStorage()); $server->addGrantType(new AuthCode()); $server->addGrantType(new RefreshToken()); $server->setTokenType(new Bearer()); $identifiedOAuth = $request->get('identified_oauth'); $authParams = ['client' => $identifiedOAuth['client'], 'redirect_uri' => $identifiedOAuth['client']->getRedirectUri(), 'scopes' => $identifiedOAuth['scopes'], 'state' => time()]; $redirectUri = $server->getGrantType('authorization_code')->newAuthorizeRequest('user', $user->id, $authParams); parse_str(parse_url($redirectUri, PHP_URL_QUERY), $queryStr); // Complete the OAuth Auth flow $server->getRequest()->request->set('grant_type', 'authorization_code'); $server->getRequest()->request->set('client_id', $identifiedOAuth['client']->getId()); $server->getRequest()->request->set('client_secret', $identifiedOAuth['client']->getSecret()); $server->getRequest()->request->set('redirect_uri', $identifiedOAuth['client']->getRedirectUri()); $server->getRequest()->request->set('code', $queryStr['code']); try { $accessToken = $server->issueAccessToken(); $response = new Response($accessToken, 200, ['Cache-Control' => 'no-store', 'Pragma' => 'no-store']); } catch (OAuthException $e) { $response = new Response(['error' => $e->errorType, 'message' => $e->getMessage()], $e->httpStatusCode, $e->getHttpHeaders()); } catch (\Exception $e) { $response = new Response(['error' => $e->getCode(), 'message' => $e->getMessage()], 500); } finally { // Return the response $response->headers->set('Content-type', 'application/json'); return $response; } // TO DO: Remove previous active access token for current client }
/** * Issue an auth code. * * @param string $ownerType the auth code owner type * @param string $ownerId the auth code owner id * @param array $params additional parameters to merge * * @return string the auth code redirect url */ public function issueAuthCode($ownerType, $ownerId, $params = []) { $params = array_merge($this->authCodeRequestParams, $params); return $this->issuer->getGrantType('authorization_code')->newAuthorizeRequest($ownerType, $ownerId, $params); }
/** * 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(); }
function it_issues_an_auth_code(AuthorizationServer $issuer, AuthCodeGrant $authCodeGrant) { $authCodeGrant->newAuthorizeRequest('user', '1', ['foo' => 'bar'])->willReturn('baz')->shouldBeCalled(); $issuer->getGrantType('authorization_code')->willReturn($authCodeGrant)->shouldBeCalled(); $this->issueAuthCode('user', '1', ['foo' => 'bar'])->shouldReturn('baz'); }
/** * The route responsible for giving auth code * * @param Router $router * @param AuthorizationServer $authorizationServer * @return \Response */ private function authorizeRoute(Router $router, AuthorizationServer $authorizationServer) { $router->get(Config::get('laravel-oauth2-server.authorize_path'), function () use($authorizationServer) { try { $authParams = $authorizationServer->getGrantType('authorization_code')->checkAuthorizeParams(); if (Auth::check()) { $redirectUri = $authorizationServer->getGrantType('authorization_code')->newAuthorizeRequest('user', Auth::id(), $authParams); if (Request::input('target_url')) { $redirectUri .= '&target_url=' . Request::input('target_url'); } return redirect($redirectUri); } if (Request::input('auth_checkup') && Request::input('target_url')) { return redirect(Request::input('target_url')); } if (Config::get('laravel-oauth2-server.login_is_route')) { return redirect(route(Config::get('laravel-oauth2-server.login_route')) . '?target_url=' . Request::input('target_url')); } return redirect(Config::get('laravel-oauth2-server.login_path') . '?target_url=' . Request::input('target_url')); } catch (Exception $e) { die('Wrong authorize parameters!'); } }); }