/**
  * @param $route
  * @param $request
  * @param null $scope
  * @return null|BridgeResponse
  */
 public function filter($route, $request, $scope = null)
 {
     $beforeAccessResult = $this->dispatcher->until('oauth.access.before', array($scope));
     if ($beforeAccessResult) {
         return null;
     }
     /** @var BridgeRequest $bridgeRequest */
     $bridgeRequest = BridgeRequest::createFromRequest($request);
     $bridgeResponse = new BridgeResponse();
     $resController = $this->server->getResourceController();
     if (!$resController->verifyResourceRequest($bridgeRequest, $bridgeResponse, $scope)) {
         $this->dispatcher->fire('oauth.access.failed');
         return $bridgeResponse;
     }
     $token = $resController->getAccessTokenData($bridgeRequest, $bridgeResponse);
     $client = $this->clientRepo->find($token['client_id']);
     $tokenScope = $token['scope'];
     $user = null;
     if (isset($token['user_id'])) {
         $user = $this->userProvider->retrieveById($token['user_id']);
     }
     if ($tokenScope) {
         $tokenScope = explode(' ', $tokenScope);
     }
     $eventPayload = array($client, $user, $tokenScope);
     $this->dispatcher->fire('oauth.access.valid', $eventPayload);
 }
示例#2
0
 public function __invoke(Request $request)
 {
     $request = BridgeRequest::createFromRequest($request);
     $response = new BridgeResponse();
     $this->oauth2TokenController->handleTokenRequest($request, $response);
     return $response;
 }
 /**
  * @param \Psr\Http\Message\ServerRequestInterface $request
  * @param \Psr\Http\Message\ResponseInterface      $response
  * @param array                                    $args
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function token(Request $request, Response $response, $args)
 {
     $this->logger->info(substr(strrchr(rtrim(__CLASS__, '\\'), '\\'), 1) . ': ' . __FUNCTION__);
     // convert a request from PSR7 to hhtpFoundation
     $httpFoundationFactory = new HttpFoundationFactory();
     $symfonyRequest = $httpFoundationFactory->createRequest($request);
     $bridgeRequest = BridgeRequest::createFromRequest($symfonyRequest);
     $this->oAuth2server->handleTokenRequest($bridgeRequest)->send();
 }
 public function postAuthorize()
 {
     $bridgeRequest = BridgeRequest::createFromRequest($this->request);
     $bridgeResponse = new BridgeResponse();
     $userId = $this->onPostAuthorized();
     $isAuthorized = (bool) $userId;
     $this->server->handleAuthorizeRequest($bridgeRequest, $bridgeResponse, $isAuthorized, $userId);
     return $bridgeResponse;
 }
 /**
  * Converts the BrowserKit request to a HttpKernel request.
  *
  * @param DomRequest $request A Request instance
  *
  * @return Request A Request instance
  */
 protected function filterRequest(DomRequest $request)
 {
     $httpRequest = Request::create($request->getUri(), $request->getMethod(), $request->getParameters(), $request->getCookies(), $request->getFiles(), $request->getServer(), $request->getContent());
     /** this happens so we can send oauth2 tokens in the header */
     if (isset($this->server['HTTP_AUTHORIZATION'])) {
         $httpRequest->headers->add(array('HTTP_AUTHORIZATION' => $this->server['HTTP_AUTHORIZATION']));
     }
     $httpRequest->files->replace($this->filterFiles($httpRequest->files->all()));
     return $httpRequest;
 }
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     //        return $next($request);
     $bridgedRequest = Request::createFromRequest($request);
     $bridgedResponse = new Response();
     if (App::make('oauth2')->verifyResourceRequest($bridgedRequest, $bridgedResponse)) {
         return $next($request);
     } else {
         return response()->json(array('error' => 'Unauthorized'), $bridgedResponse->getStatusCode());
     }
 }
 public function __invoke(Application $app, Request $request)
 {
     $token = $app['security']->getToken();
     $user = null;
     if ($token instanceof TokenInterface) {
         $user = $token->getUser()->getUsername();
     }
     $request = BridgeRequest::createFromRequest($request);
     $response = new BridgeResponse();
     $this->oauth2AuthorizeController->handleAuthorizeRequest($request, $response, (bool) $request->request->get('authorize'), $user);
     return $response;
 }
 /**
  * This function will take the client_id, client_secret, refresh_token, grant_type=refresh_token
  * and then return the token.
  * @param Request $request
  * @return new access token for user
  */
 public function newAccessToken(Request $request)
 {
     //added it to post as not injecting direclty in Request object
     $_POST['client_secret'] = env('APP_KEY');
     $bridgedRequest = \OAuth2\HttpFoundationBridge\Request::createFromGlobals($request->instance());
     $bridgedRequest->headers->add(['client_secret' => env('APP_KEY')]);
     $bridgedResponse = new \OAuth2\HttpFoundationBridge\Response();
     $bridgedResponse = \App::make('oauth2')->grantAccessToken($bridgedRequest, $bridgedResponse);
     if ($bridgedResponse) {
         return response(['data' => ['access_token' => $bridgedResponse['access_token'], 'refresh_token' => $bridgedResponse['refresh_token'], 'expires_in' => $bridgedResponse['expires_in']], 'message' => 'New access token', 'flag' => true], 201);
     }
     return response(['message' => 'Invalid refresh token', 'flag' => false], 500);
 }
 public function __invoke(Application $app, Request $request)
 {
     $request = BridgeRequest::createFromRequest($request);
     $response = new BridgeResponse();
     if (!$this->oauth2AuthorizeController->validateAuthorizeRequest($request, $response)) {
         return $response;
     }
     $token = $app['security.token_storage']->getToken();
     $user = null;
     if ($token instanceof TokenInterface) {
         $user = $token->getUser();
     }
     return $this->authorizeRenderer->render($this->urlGenerator->generate('oauth2_authorize_handler', $request->query->all()), $request->query->get('client_id'), $request->query->get('response_type'), $user);
 }
 /**
  * Handles basic authentication.
  *
  * @param GetResponseEvent $event A GetResponseEvent instance
  */
 public function handle(GetResponseEvent $event)
 {
     $request = BridgeRequest::createFromRequest($event->getRequest());
     $response = new BridgeResponse();
     if (!$this->oauth2Server->verifyResourceRequest($request, $response)) {
         return;
     }
     try {
         $token = $this->oauth2Server->getAccessTokenData($request);
         $token = $this->authenticationManager->authenticate(new OAuth2Token($token['client_id'], $token['user_id'], $token['access_token'], $this->providerKey, [], explode(" ", $token['scope'])));
         $this->tokenStorage->setToken($token);
     } catch (AuthenticationException $failed) {
         $this->handleAuthenticationError($event, $request, $failed);
     }
 }
示例#11
0
文件: Token.php 项目: rachid804/oauth
 /**
  * Provide a form in the browser for the user to submit an authorization code.
  * If the request is valid, an access token will be returned
  */
 public function tokenGet(Application $app)
 {
     // render the proper view based on the supplied "grant_type" parameter
     switch ($app['request']->query->get('grant_type')) {
         case 'client_credentials':
             $subRequest = Request::create('/token', 'POST', $app['request']->query->all());
             $response = $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
             if (!($token = $response->getParameter('access_token'))) {
                 throw new \Exception('failed to get access token from client credentials');
             }
             return $app['twig']->render('token/client_credentials.twig', ['token' => $token, 'client_id' => $app['request']->query->get('client_id'), 'user_id' => $response->getParameter('user_id')]);
         default:
             throw new NotFoundHttpException('Unsupported grant type');
     }
 }
 /**
  * @param \Psr\Http\Message\ServerRequestInterface $request
  * @param \Psr\Http\Message\ResponseInterface      $response
  * @param array                                    $next
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function validateToken($request)
 {
     $this->logger->info(substr(strrchr(rtrim(__CLASS__, '\\'), '\\'), 1) . ': ' . __FUNCTION__);
     // convert a request from PSR7 to hhtpFoundation
     $httpFoundationFactory = new HttpFoundationFactory();
     $symfonyRequest = $httpFoundationFactory->createRequest($request);
     $bridgeRequest = BridgeRequest::createFromRequest($symfonyRequest);
     if (!$this->oAuth2server->verifyResourceRequest($bridgeRequest)) {
         $this->oAuth2server->getResponse()->send();
         die;
     }
     // store the user_id
     $token = $this->oAuth2server->getAccessTokenData($bridgeRequest);
     $this->user = $token['user_id'];
     return TRUE;
 }
示例#13
0
 /**
  * {@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;
 }
 /**
  * Validates a request and takes a scope value that could result
  * in a user id being put into the request if it's valid.
  *
  * @param HttpFoundation\Request $request
  * @param string $scope
  * @return null|HttpFoundation\Response
  */
 public function validateRequest(HttpFoundation\Request $request, $scope)
 {
     $this->log->addDebug(print_r($request, true), ['namespace' => 'HackTheDinos\\Controllers\\OAuth', 'method' => 'validateRequest', 'type' => 'request', 'scope' => $scope]);
     $bridgeRequest = HttpFoundationBridge\Request::createFromRequest($request);
     if ($this->server->verifyResourceRequest($bridgeRequest, null, $scope)) {
         //Put the userId into the request if we're validating at the user scope
         if ($scope === 'user') {
             $token = $this->server->getAccessTokenData($bridgeRequest);
             $request->request->set('userId', $token['user_id']);
         } else {
             //Set the userId to 0 which should make any
             //searches relying on this being valid to fail.
             $request->request->set('userId', 0);
         }
         return null;
     }
     $this->log->addWarning('Failed to validate request', ['namespace' => 'HackTheDinos\\Controllers\\OAuth', 'method' => 'validateRequest', 'scope' => $scope]);
     return new HttpFoundation\Response('Not Authorized', 401);
 }
示例#15
0
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     return $next($request);
     if (!$request->has('access_token')) {
         return Api::genMessage('access token not found', true, "oauth error");
     }
     $req = Request::createFromGlobals();
     $brigedRequest = OauthRequest::createFromRequest($req);
     $brigedResponse = new \OAuth2\HttpFoundationBridge\Response();
     if (!($token = App::make('oauth2')->getAccessTokenData($brigedRequest, $brigedResponse))) {
         $response = App::make('oauth2')->getResponse();
         if ($response->isClientError() && $response->getParameter('error')) {
             if ($response->getParameter('error') == 'expired_token') {
                 return Api::genMessage('the access token provided has expired', true);
             }
             return Api::genMessage('the access token provided is invalid', true, "oauth error");
         }
     } else {
         $request['user_id'] = $token['user_id'];
     }
     return $next($request);
 }
示例#16
0
 /**
  * Validates a request and takes a scope value that could result
  * in a user id being put into the request if it's valid. The
  * passThrough flag will allow the request to continue when it
  * would otherwise fail with a 401 response.
  *
  * @param HttpFoundation\Request $request
  * @param string $scope
  * @param bool $passThrough
  * @return null|HttpFoundation\Response
  */
 public function validateRequest(HttpFoundation\Request $request, $scope, $passThrough = false)
 {
     $this->log->addDebug(print_r($request, true), ['namespace' => 'Alerts\\Controllers\\OAuth2', 'method' => 'validateRequest', 'type' => 'request', 'scope' => $scope]);
     $bridgeRequest = HttpFoundationBridge\Request::createFromRequest($request);
     if ($this->server->verifyResourceRequest($bridgeRequest, null, $scope)) {
         //Put the user into the request if we're validating at the user scope
         if ($scope === 'user') {
             $token = $this->server->getAccessTokenData($bridgeRequest);
             $request->request->set('user', $this->usersRepo->getById($token['user_id']));
         } else {
             //Set the user to null which should make any
             //searches relying on this being valid to fail.
             $request->request->set('user', null);
         }
         return null;
         //If the request shouldn't hard fail. This should only have a few specific use cases.
     } elseif ($passThrough) {
         $this->log->addInfo('OAuth Pass Through', ['namespace' => 'Alerts\\Controllers\\OAuth2', 'method' => 'validateRequest', 'type' => 'request', 'scope' => $scope, 'passThrough' => true]);
         return null;
     }
     $this->log->addInfo('Failed to validate request', ['namespace' => 'Alerts\\Controllers\\OAuth2', 'method' => 'validateRequest', 'scope' => $scope]);
     return new HttpFoundation\Response('Not Authorized', 401);
 }
 /**
  * Handles basic authentication.
  *
  * @param GetResponseEvent $event A GetResponseEvent instance
  */
 public function handle(GetResponseEvent $event)
 {
     $request = BridgeRequest::createFromRequest($event->getRequest());
     $response = new BridgeResponse();
     if (!$this->oauth2Server->verifyResourceRequest($request, $response)) {
         return;
     }
     try {
         $token = $this->authenticationManager->authenticate(new OAuth2Token([]));
         $this->securityContext->setToken($token);
     } catch (AuthenticationException $failed) {
         $token = $this->securityContext->getToken();
         if ($token instanceof OAuth2Token) {
             $this->securityContext->setToken(null);
         }
         if (null !== $this->logger) {
             $this->logger->info(sprintf('Authentication request failed for user "%s": %s', $username, $failed->getMessage()));
         }
         if ($this->ignoreFailure) {
             return;
         }
         $event->setResponse($this->authenticationEntryPoint->start($request, $failed));
     }
 }
 public function isAuthenticated(Request $request)
 {
     $oauthRequest = OAuthRequest::createFromRequest($request);
     return $this->server->verifyResourceRequest($oauthRequest);
 }
示例#19
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;
 }
示例#20
0
文件: index.php 项目: rachid804/oauth
<?php

use OAuth2\HttpFoundationBridge\Request;
$app = (require_once __DIR__ . '/../bootstrap.php');
/*
 * Repeated in the client
 *
 * A big hack. In Behat, I was seeing that Guzzle was making requests to
 * localhost:9002 (the host I was using locally). But when it hit the application,
 * the HTTP_HOST header was "localhost" instead of "localhost:9002", which
 * caused the port to be wrong on all generated links. This hacks around
 * whatever bug (on my end or another) that caused that.
 */
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;
$port = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : null;
if (!in_array($port, array('80', '443')) && false === ($pos = strrpos($host, ':'))) {
    $_SERVER['HTTP_HOST'] .= ':' . $port;
}
$request = Request::createFromGlobals();
$app->run($request);