private function getRequest() { if ($this->request === NULL) { $this->request = Request::createFromGlobals(); } return $this->request; }
public function __invoke($request, $response, $next) { $params = $request->getQueryParams(); if ($params['handler'] === "oauth" | ($params['handler'] === "api" && !isset($params['page'])) | ($params['handler'] === "api" && $params['page'] === "doc") | ($params['handler'] === "api" && $params['page'] === "doc/swagger") | ($params['handler'] === "api" && $params['page'] === "users/me/login_token")) { $response = $next($request, $response); return $response; } $factory = new AuthenticationServerFactory(); $server = $factory->getServer(); if (!$server->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) { $response = $response->withStatus(403); $response = $response->withHeader('Content-type', 'application/json'); return $response->write(json_encode(array('status' => 403, 'error' => 'invalid_access_token', 'pretty_error' => 'You did not supply an OAuth access token or the token is invalid.'), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); } $token = $server->getAccessTokenData(\OAuth2\Request::createFromGlobals()); $user = get_user($token['user_id']); if (!$user) { $response = $response->withStatus(403); $response = $response->withHeader('Content-type', 'application/json'); return $response->write(json_encode(array('status' => 403, 'error' => 'invalid_access_token', 'pretty_error' => 'You did not supply an OAuth access token or the token is invalid.'), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); } if (!login($user)) { $response = $response->withStatus(403); $response = $response->withHeader('Content-type', 'application/json'); return $response->write(json_encode(array('status' => 403, 'error' => 'could_not_login', 'pretty_error' => 'Could not login the user associated with this token. Probably the account is banned.'), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); } $response = $next($request, $response); return $response; }
public function authorize() { $request = \OAuth2\Request::createFromGlobals(); $response = new \OAuth2\Response(); $server = $this->oauth; // validate the authorize request if (!$server->validateAuthorizeRequest($request, $response)) { $response->send(); d(var_dump($is_authorized)); //die; } // display an authorization form if (!$this->request->isPost()) { exit(' <form method="post"> <label>Do You Authorize TestClient?</label><br /> <input type="submit" name="authorized" value="yes"> <input type="submit" name="authorized" value="no"> </form>'); } // print the authorization code if the user has authorized your client $is_authorized = $_POST['authorized'] == 'yes'; $server->handleAuthorizeRequest($request, $response, $is_authorized); if ($is_authorized) { // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=') + 5, 40); exit("SUCCESS! Authorization Code: {$code}"); } $response->send(); }
/** * @SWG\Post( * path="/oauth/token", * tags={"oauth"}, * summary="Request for a valid access token", * description="Given client_id and client_secret a valid access token is issued.", * operationId="getToken", * consumes={"application/x-www-form-urlencoded"}, * @SWG\Parameter( * in="formData", * name="grant_type", * description="Type of grant wanted.", * required=true, * type="string", * enum={"client_credentials"}, * ), * @SWG\Parameter( * in="formData", * name="client_id", * description="A valid client_id.", * required=true, * type="string", * ), * @SWG\Parameter( * in="formData", * name="client_secret", * description="A valid client_secret.", * required=true, * type="string", * ), * @SWG\Parameter( * in="formData", * name="scope", * description="List of scopes separated by comma.", * required=false, * type="string", * ), * @SWG\Parameter( * in="formData", * name="state", * description="String parameter to check if there is no man in the middle.", * required=false, * type="string", * ), * @SWG\Response( * response=200, * description="Successfully created", * @SWG\Schema(), * examples={ * "application/json": { * "access_token": "a63097c58497b42bf2793e1f7851fe10ae7cff18", * "expires_in": 3600, * "token_type": "Bearer", * "scope": null * } * }, * ), * @SWG\Response( * response=400, * description="Bad request. Some parameter is missing.", * ), * ) */ public function getToken() { // TODO: return same access token if not expired $request = Request::createFromGlobals(); // Handle a request for an OAuth2.0 Access Token and send the response to the client return Response::responseFromOAuth($this->oauth->handleTokenRequest($request)); }
/** * This method gets called every time a REST method is called which lacks * the @noAuth keyword. So this is the right place to implement other * authentication mechanisms like OAuth2, what we're doing here. * * Don't call that method directly, it has not any benefits in doing * so. It will be automatically called by the super class, if it's there. * * @access protected * @param bool $ask It's just here for compatibility * @return bool True if verified request, False otherwise */ protected function doServerWideAuthorization($ask = false) { if ($this->bypassAuthentication) { return true; } list($obj, $method, $params, $thisParams, $keys) = $this->findUrl(); $accepted_scope = isset($keys['scope']) ? $keys['scope'] : null; // Handle a request to a resource and authenticate the access token $request = \OAuth2\Request::createFromGlobals(); $response = new \OAuth2\Response(); if (!$this->getOAuth2Server()->verifyResourceRequest($request, $response, $accepted_scope)) { // Presented token wasn't valid $response->send(); return false; } else { // Token is valid /** @var array $token_data */ $token_data = $this->getOAuth2Server()->getAccessTokenData($request); // Save all info in the _SERVER environment $_SERVER['OAUTH2_USER_ID'] = $token_data['user_id']; $_SERVER['OAUTH2_CLIENT_ID'] = $token_data['client_id']; $_SERVER['OAUTH2_EXPIRES'] = $token_data['expires']; $_SERVER['OAUTH2_EXPIRES_AT'] = strftime("%d.%m.%Y %H:%M", $token_data['expires']); $_SERVER['OAUTH2_SCOPE'] = $token_data['scope']; $_SERVER['OAUTH2_ACCESS_TOKEN'] = $token_data['access_token']; if ($this->optionalHeaders) { // This is completely optional, but GitHub does so, // too: http://developer.github.com/v3/oauth/ $this->header_manager->addHeader('X-OAuth-Scopes', $token_data['scope']); $this->header_manager->addHeader('X-Accepted-OAuth-Scopes: ', $accepted_scope); } return true; } }
/** * Runs the action. * * * @throws \CException if oauth is improperly configured. */ public function run() { if (!Yii::app()->hasComponent($this->oauth2Component)) { throw new CException("Could not find OAuth2Yii/Server component '{$this->oauth2Component}'"); } $oauth2 = Yii::app()->getComponent($this->oauth2Component); /* @var \OAuth2Yii\Component\ServerComponent $oauth2 */ $server = $oauth2->getServer(); if (!$oauth2->getCanGrant()) { throw new CException("No grant types enabled"); } if ($oauth2->enableAuthorization) { $authorizationStorage = $oauth2->getStorage(ServerComponent::STORAGE_AUTHORIZATION_CODE); $server->addGrantType(new GrantType\AuthorizationCode($authorizationStorage)); } if ($oauth2->enableClientCredentials) { $clientStorage = $oauth2->getStorage(ServerComponent::STORAGE_CLIENT_CREDENTIALS); $server->addGrantType(new GrantType\ClientCredentials($clientStorage)); } if ($oauth2->enableUserCredentials) { $userStorage = $oauth2->getStorage(ServerComponent::STORAGE_USER_CREDENTIALS); $server->addGrantType(new GrantType\UserCredentials($userStorage)); $refreshStorage = $oauth2->getStorage(ServerComponent::STORAGE_REFRESH_TOKEN); $server->addGrantType(new GrantType\RefreshToken($refreshStorage)); } // Disable any potential output from Yii logroutes foreach (Yii::app()->log->routes as $r) { if ($r instanceof \CWebLogRoute || $r instanceof CProfileLogRoute) { $r->enabled = false; } } YII_DEBUG && Yii::trace('Handling access token/authorization code request', 'oauth2.action.token'); $request = Request::createFromGlobals(); $server->handleTokenRequest($request)->send(); }
function Authorize() { $request = OAuth2\Request::createFromGlobals(); $response = new OAuth2\Response(); if ($_GET['access_token']) { $_POST['access_token'] = $_GET['access_token']; } // validate the authorize request if (!$this->server->validateAuthorizeRequest($request, $response)) { $response->send(); die; } // display an authorization form if (empty($_POST)) { exit(' <form method="post"> <label>Do You Authorize TestClient?</label><br /> <input type="submit" name="authorized" value="yes"> <input type="submit" name="authorized" value="no"> </form>'); } // print the authorization code if the user has authorized your client $is_authorized = $_POST['authorized'] === 'yes'; $server->handleAuthorizeRequest($request, $response, $is_authorized); if ($is_authorized) { // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=') + 5, 40); $openid = md5($uid . $code); exit("SUCCESS! Authorization Code: {$code},the user openid is {$openid}"); } $response->send(); }
protected function authorize() { if (!$this->server->verifyResourceRequest(OAuth2Request::createFromGlobals())) { // Not authorized return 401 error return false; } return true; }
function __construct($conf, $oauth2server) { $this->conf = $conf; $this->oauth2server = $oauth2server; $this->request = \OAuth2\Request::createFromGlobals(); $this->response = new \OAuth2\Response(); //$this->accessTokenData = $oauth2server->getAccessTokenData($this->request); }
/** * Gets user details * * @param string $username Username to be check with. * * @return array The associated "user_id" and optional "scope" values. * This function MUST return FALSE if the requested user does not exist or is * invalid. "scope" is a space-separated list of restricted scopes. * * @code * return array( * "user_id" => USER_ID, // REQUIRED user_id to be stored with the authorization code or access token * "scope" => SCOPE // OPTIONAL space-separated list of restricted scopes * ); */ public function getUserDetails($username) { $user = \JFactory::getUser(); $request = \OAuth2\Request::createFromGlobals(); // We load scopes from client $clientId = $request->request('client_id'); $scopes = $this->getClientScope($clientId); return array("user_id" => $user->get('id'), "username" => $user->get('username'), "name" => $user->get('name'), "scope" => $scopes); }
public function onDispatch(MvcEvent $e) { if (!Console::isConsole()) { $server = $e->getApplication()->getServiceManager()->get('ZF\\OAuth2\\Service\\OAuth2Server'); if (!$server->verifyResourceRequest(OAuth2Request::createFromGlobals())) { throw new \Exception('Not Authorized'); } } }
public function api2() { $scope_required = NULL; if (!$this->_server->verifyResourceRequest(OAuth2\Request::createFromGlobals(), $this->_response, $scope_required)) { $this->_response->send(); return; } $this->output->set_content_type('application/json')->set_output(json_encode(array('oauth2' => 'OK?'))); }
/** * @SWG\Post( * path="/oauth/v2/token", * tags={"authentication"}, * summary="Request a new access token.", * description="Request a new access token for the specific user.", * produces={"application/json"}, * @SWG\Parameter( * name="username", * in="query", * description="The username of the specific user.", * required=true, * type="string", * @SWG\Items(type="string") * ), * @SWG\Parameter( * name="password", * in="query", * description="The password of the specific user.", * required=true, * type="string", * @SWG\Items(type="string") * ), * @SWG\Parameter( * name="client_id", * in="query", * description="The id of the client application.", * required=true, * type="string", * @SWG\Items(type="string") * ), * @SWG\Parameter( * name="client_secret", * in="query", * description="The secret of the client application.", * required=true, * type="string", * @SWG\Items(type="string") * ), * @SWG\Response( * response=200, * description="Succesful operation." * ), * ) */ public function getToken($request, $response, $args) { $factory = new \PleioRest\AuthenticationServerFactory(); $server = $factory->getServer(); $authRequest = \OAuth2\Request::createFromGlobals(); $authResponse = $server->handleTokenRequest($authRequest); $response = $response->withStatus($authResponse->getStatusCode()); $response->write(json_encode($authResponse->getParameters(), JSON_PRETTY_PRINT)); return $response; }
public function validateOAuth2($scope = null) { if (!$this->getOAuth2Server()->verifyResourceRequest(OAuth2Request::createFromGlobals(), $response = null, $scope)) { $error = $this->getOAuth2Server()->getResponse(); $parameters = $error->getParameters(); $detail = isset($parameters['error_description']) ? $parameters['error_description'] : $error->getStatusText(); return new ApiProblem($error->getStatusCode(), $detail); } return true; }
/** * @return Novosga\Model\Usuario */ public function user() { $token = $this->getAccessTokenData(Request::createFromGlobals()); if (isset($token['user_id'])) { $rs = $this->em->getRepository('Novosga\\Model\\Usuario')->findBy(['login' => $token['user_id']]); if (count($rs)) { return $rs[0]; } } return; }
public function testValidToken() { $server = $this->getTestServer(); $request = Request::createFromGlobals(); $request->headers['AUTHORIZATION'] = 'Bearer accesstoken-openid-connect'; $response = new Response(); $server->handleUserInfoRequest($request, $response); $parameters = $response->getParameters(); $this->assertEquals($parameters['sub'], 'testuser'); $this->assertEquals($parameters['email'], '*****@*****.**'); $this->assertEquals($parameters['email_verified'], true); }
private function credentials($type) { $api = new OAuth2Service(); $server = $api->init($type); $req = Request::createFromGlobals(); $result = $server->handleTokenRequest($req); $params = $result->getParameters(); if ($result->getStatusCode() != 200) { $this->ajaxReturn(array('code' => $result->getStatusCode(), 'info' => $params), "json"); } else { $this->ajaxReturn(array('code' => 0, 'info' => $params), "json"); } }
public function __construct() { $dir = __DIR__ . '/db/'; $file = 'oauth.sqlite'; if (!file_exists($dir . $file)) { include_once $dir . 'rebuild_db.php'; } static::$storage = new Pdo(array('dsn' => 'sqlite:' . $dir . $file)); // create array of supported grant types $grantTypes = array('authorization_code' => new AuthorizationCode(static::$storage), 'user_credentials' => new UserCredentials(static::$storage)); static::$request = Request::createFromGlobals(); static::$server = new OAuth2Server(static::$storage, array('enforce_state' => true, 'allow_implicit' => true), $grantTypes); }
public function authorize() { $api = new OAuth2Service(); $server = $api->init(OAuth2Service::ALL); if (!$server->verifyResourceRequest(Request::createFromGlobals())) { $resp = $server->getResponse(); $params = $resp->getParameters(); return array('status' => $resp->getStatusCode(), 'info' => $params['error_description']); //,"json"); } return array('status' => 0, 'info' => '你通过了Api的验证'); //,"json"); }
public function call(Micro $application) { $oauth = $application['oauth']; $url = strtok($_SERVER["REQUEST_URI"], '?'); if (!in_array($url, self::$excepted_routes)) { // Handle a request to a resource and authenticate the access token if (!$oauth->verifyResourceRequest(Request::createFromGlobals())) { Response::responseFromOAuth($oauth->getResponse())->send(); throw new UnauthorizedRequest(); } } return true; }
public function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->library('session'); OAuth2\Autoloader::register(); $this->load->database(); $config = array('dsn' => $this->db->dsn, 'username' => $this->db->username, 'password' => $this->db->password); $this->_storage = new OAuth2\Storage\Pdo($config); $grant_types = array('user_credentials' => new UserCredentials($this->_storage), 'refresh_token' => new RefreshToken($this->_storage, array('always_issue_new_refresh_token' => TRUE))); $this->_server = new Server($this->_storage, array('enforce_state' => FALSE, 'allow_implicit' => TRUE, 'issuer' => $this->input->server('HTTP_HOST')), $grant_types); $this->_request = Request::createFromGlobals(); $this->_response = new Response(); }
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; }
private function authenticateApiRequest() { $resource = $this->app['oauth_resource']; $request = Request::createFromGlobals(); $response = new Response(); if ($resource->verifyResourceRequest($request, $response)) { $tokenData = $resource->getResourceController()->getToken(); // replace current user with the user from the access token $userModel = Auth::USER_MODEL; $user = $this->app['user'] = new $userModel($tokenData['user_id'], true); // use the authenticated user as the requester for model permissions Model::configure(['requester' => $user]); } else { $response->send(); exit; } }
public function getuserinfo() { if (!$this->server->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) { $this->server->getResponse()->send(); die; } $scope = $this->server->getResourceController()->getAccessTokenData(\OAuth2\Request::createFromGlobals(), $response)['scope']; if ($this->checkscope($_SERVER['PATH_INFO'], $scope)) { $encrypted = rawurldecode($_GET['text']); $data = $this->decrypt($encrypted); $this->ajaxReturn($this->getmoreinfo($data)); } else { $data['errorcode'] = 40001; $data['errmsg'] = "Invalid scope"; $this->ajaxReturn($data); } }
/** * 显示用户登录页面,并获取授权code */ public function authorize() { $this->oauth_server(); $server = $this->server_all; $request = \OAuth2\Request::createFromGlobals(); $response = new \OAuth2\Response(); //验证授权请求 if (!$server->validateAuthorizeRequest($request, $response)) { $response->send(); die; } // 显示登录页面 if (empty($_POST)) { if (is_login()) { echo " <meta charset=\"UTF-8\"><script>alert('不能重复登录!');window.history.go(-1);</script>"; exit; } else { $this->assign('iptype', checkUserIp()); //显示登录页面 $this->display(); } } //如果用户是授权用户就输出授权验证码 if ($_POST) { if (empty($_POST['logintype'])) { //集团登录 $result = A('Ucenter/Login', 'Widget')->company_dologin(); } else { //普通用户登录 $result = A('Ucenter/Login', 'Widget')->doLogin(); } if ($result['status']) { $is_authorized = $_POST['authorized'] === 'yes'; $userid = session('user_auth.uid'); $server->handleAuthorizeRequest($request, $response, $is_authorized, $userid); if ($is_authorized) { //跳转到回调地址,并携带code码 $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=') + 5, 40); header("Location: " . $response->getHttpHeader('Location')); } } else { $this->error($result['info']); } } $response->send(); }
public function tokenAction() { $request = $this->getRequest(); if (!$request instanceof HttpRequest) { return; } if ($request->isOptions()) { return $this->getResponse(); } $oauth2request = OAuth2Request::createFromGlobals(); $response = $this->getServer()->handleTokenRequest($oauth2request); if ($response->isClientError()) { $parameters = $response->getParameters(); $errorUri = isset($parameters['error_uri']) ? $parameters['error_uri'] : null; return new ProblemResponse(new Problem($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; }
protected function authorize() { $authorized = false; /* @var $server OAuth2Server */ $server = $this->getServiceLocator()->get('OAuth2Server'); if ($server->verifyResourceRequest(OAuth2Request::createFromGlobals())) { // authorized $authorized = true; } else { $request = $this->getServiceLocator()->get('Request'); $token = $request->getPost('token', false); if ($token) { /* @var $googleAuth GoogleAuth */ $googleAuth = $this->getServiceLocator()->get('ControllerPluginManager')->get('isGoogleAuthorized'); $authorized = $googleAuth->isGoogleAuthorized($token); } } return $authorized ? true : false; }
/** * Performs an authentication attempt * * @return \Zend\Authentication\Result * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface If authentication cannot be performed */ public function authenticate() { $oauth2Request = OAuth2Request::createFromGlobals(); $result = new Result(Result::FAILURE_CREDENTIAL_INVALID, new Guest()); if (!$this->getOauth2Server()->verifyResourceRequest($oauth2Request)) { $response = $this->getOauth2Server()->getResponse(); if ($response->isClientError()) { $result = new Result(Result::FAILURE, new Guest(), array(isset($parameters['error_description']) ? $parameters['error_description'] : null)); } } // Valid Access Token return Authenticated Identity $token = $this->getOauth2Server()->getAccessTokenData($oauth2Request); $identifier = isset($token['user_id']) ? $token['user_id'] : $token['client_id']; if (!is_null($identifier)) { $identity = new OAuth2Authenticated($identifier); $identity->setAccessToken($token); $result = new Result(Result::SUCCESS, $identity); } return $result; }
/** * Method executed when the dispatch event is triggered * * @param MvcEvent $e * @return void */ public static function onDispatch(MvcEvent $e) { if ($e->getRequest() instanceof \Zend\Console\Request) { return; } if ($e->getRouteMatch()->getMatchedRouteName() == 'login' || $e->getRouteMatch()->getMatchedRouteName() == 'users') { return; } $sm = $e->getApplication()->getServiceManager(); $usersTable = $sm->get('Users\\Model\\UsersTable'); $storage = new Pdo($usersTable->adapter->getDriver()->getConnection()->getConnectionParameters()); $server = new Server($storage); if (!$server->verifyResourceRequest(Request::createFromGlobals())) { $model = new JsonModel(array('errorCode' => $server->getResponse()->getStatusCode(), 'errorMsg' => $server->getResponse()->getStatusText())); $response = $e->getResponse(); $response->setContent($model->serialize()); $response->getHeaders()->addHeaderLine('Content-Type', 'application/json'); $response->setStatusCode($server->getResponse()->getStatusCode()); return $response; } }