public function authorizeCallback() { // If there is an error parameter, show that error $error = $this->request->get('error'); if (!empty($error)) { HtmlPage::renderError5xx(500, "<pre>OAuth Error: " . $this->request->get('error') . "\n" . '<a href="/authorize_callback">Retry</a></pre>'); return; } // Get OAuth2 settings $authorizeUrl = Config::get('oauth.authorization_url'); $clientId = Config::get('oauth.client'); $clientSecret = Config::get('oauth.secret'); $redirectUrl = Config::get('oauth.redirect_uri'); $userAgent = Config::get('oauth.user_agent'); // Prepare OAuth2 client to request an authorization code $client = new Client($clientId, $clientSecret, Client::AUTH_TYPE_AUTHORIZATION_BASIC); $client->setCurlOption(CURLOPT_USERAGENT, $userAgent); // Request an authorization code if there isn't one in the GET // parameter code, if there is one, request an access token $code = $this->request->get('code'); if (empty($code)) { $this->session->delete('accessToken'); $authUrl = $client->getAuthenticationUrl($authorizeUrl, $redirectUrl, array('scope' => 'identity', 'state' => 'As64xA3ueT6sjxiazAA7278yhs6103jx', 'duration' => 'permanent')); header('Location: ' . $authUrl); } else { $this->session->requestOAuth2AccessToken($code); header('Location: /'); return; } }
/** * Get Access Token * * @param string $code Access code sent by OAuth provider authorization callback * @param array $params Optional array of additional query parameters to send (key/value) * @return string */ public function getAccessToken($code, $params = array()) { $params['code'] = $code; $params['redirect_uri'] = $this->redirectUrl; $response = $this->client->getAccessToken($this->getTokenUrl(), 'authorization_code', $params); return $response; }
/** * @param array $params * @return string * @throws Exception */ public function authenticate(array $params) { if (!isset($params['code']) || empty($params['code'])) { throw new Exception('Authentication failed, invalid or empty code.'); } $oAuthConf = Config::$a['oauth']['providers'][$this->authProvider]; $client = new Client($oAuthConf['clientId'], $oAuthConf['clientSecret'], Client::AUTH_TYPE_AUTHORIZATION_BASIC); $client->setAccessTokenType(Client::ACCESS_TOKEN_BEARER); $response = $client->getAccessToken('https://ssl.reddit.com/api/v1/access_token', 'authorization_code', array('redirect_uri' => sprintf(Config::$a['oauth']['callback'], $this->authProvider), 'code' => $params['code'])); if (empty($response) || isset($response['error'])) { throw new Exception('Invalid access_token response'); } if (!isset($response['result']) || empty($response['result']) || !isset($response['result']['access_token'])) { throw new Exception('Failed request for access token'); } $client->setAccessToken($response['result']['access_token']); // Reddit requires a User-Agent $info = $client->fetch("https://oauth.reddit.com/api/v1/me.json", array(), 'GET', array('User-Agent' => 'destiny.gg/' . Config::version())); if (empty($info['result']) || !is_array($info['result']) || isset($info['error'])) { throw new Exception('Invalid user details response'); } $authCreds = $this->getAuthCredentials($params['code'], $info['result']); $authCredHandler = new AuthenticationRedirectionFilter(); return $authCredHandler->execute($authCreds); }
/** * @param array $params * @return string * @throws Exception */ public function authenticate(array $params) { if (!isset($params['code']) || empty($params['code'])) { throw new Exception('Authentication failed, invalid or empty code.'); } $oAuthConf = Config::$a['oauth']['providers'][$this->authProvider]; $client = new Client($oAuthConf['clientId'], $oAuthConf['clientSecret']); $client->setAccessTokenType(Client::ACCESS_TOKEN_OAUTH); $response = $client->getAccessToken('https://api.twitch.tv/kraken/oauth2/token', 'authorization_code', array('redirect_uri' => sprintf(Config::$a['oauth']['callback'], $this->authProvider), 'code' => $params['code'])); if (empty($response) || isset($response['error'])) { throw new Exception('Invalid access_token response'); } if (!isset($response['result']) || empty($response['result']) || !isset($response['result']['access_token'])) { throw new Exception('Failed request for access token'); } $client->setAccessToken($response['result']['access_token']); $response = $client->fetch('https://api.twitch.tv/kraken/user'); if (empty($response['result']) || isset($response['error'])) { throw new Exception('Invalid user details response'); } if (is_string($response['result'])) { throw new Exception(sprintf('Invalid auth result %s', $response['result'])); } $authCreds = $this->getAuthCredentials($params['code'], $response['result']); $authCredHandler = new AuthenticationRedirectionFilter(); return $authCredHandler->execute($authCreds); }
public function call($resource_url, $parameters = array(), $http_method = 'GET', array $http_headers = array()) { $url = $this->apiUrl . $resource_url . '.json'; if ($http_method === 'POST') { // Positionly expects JSON as post input format if (is_string($parameters)) { $parameters = json_decode($parameters, true); if (!is_array($parameters)) { throw new PositionlyApiException('Invalid JSON string in POST parameter'); } } if (is_array($parameters)) { $parameters = json_encode($parameters); } else { throw new PositionlyApiException('Invalid POST parameter. JSON string or array expected.'); } } $result = $this->client->fetch($url, $parameters, $http_method, $http_headers); $response = PositionlyApiResponse::createResponse($result['code'], $result['result'], $http_method); $responseResult = $response->getResult(); if ($response->getResponseCode() !== 200) { // an error occured. if (isset($responseResult['message'])) { throw new PositionlyApiException($responseResult['message'], $response->getResponseCode()); } // bad request, there are errors in form if ($response->getResponseCode() === 400 && isset($responseResult['errors'])) { return $response; } throw new PositionlyApiException("Unknown error (no message)", $response->getResponseCode()); } return $response; }
public function getData() { $clientId = $this->getClientId(); $clientSecret = $this->getClientSecret(); $merchantId = $this->getMerchantId(); $amount = $this->getAmount(); $description = $this->getDescription(); $redirectUrl = $this->getRedirectUrl(); $oauth2path = $this->getPath(); define("CLIENT_ID", $clientId); define("CLIENT_SECRET", $clientSecret); define("REDIRECT_URI", $redirectUrl); define("AUTHORIZATION_ENDPOINT", "https://paguei.online/app/api/authorize"); define("TOKEN_ENDPOINT", "https://paguei.online/app/api/token"); $client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET); if (!isset($_GET['code'])) { $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI); header('Location: ' . $auth_url); die('Redirect'); } else { $params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI); $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params); $info = $response['result']; $client->setAccessToken($info['access_token']); $id = $merchantId; $description = urlencode($description); $urlfetch = 'https://paguei.online/app/api/transfer'; $urlfetch2 = $urlfetch . '/' . $id . '/' . $amount . '/' . $description . '.json'; $response = $client->fetch($urlfetch2); return $response; } }
/** * Here you can render the homepage of the app */ public function index() { // Get OAuth2 parameters from config and session $clientId = Config::get('oauth.client'); $clientSecret = Config::get('oauth.secret'); $userAgent = Config::get('oauth.user_agent'); $accessTokenResult = $this->session->read('accessToken'); // Setup OAuth2 client to request resources from Reddit $client = new Client($clientId, $clientSecret, Client::AUTH_TYPE_AUTHORIZATION_BASIC); $client->setCurlOption(CURLOPT_USERAGENT, $userAgent); $client->setAccessToken($accessTokenResult["access_token"]); $client->setAccessTokenType(Client::ACCESS_TOKEN_BEARER); // Request user response $response = $client->fetch("https://oauth.reddit.com/api/v1/me.json"); $this->view->render("Home", array('me' => $response['result'], 'pageTitle' => 'Reddit profile example')); }
/** * @Route("/oauth", name="oauth") */ public function oauthAction(Request $request) { $client_test_token = $this->getParameter('oauth.test_token'); if ($client_test_token != NULL) { $this->get('logger')->info("Authenticating with test token"); $session = $request->getSession(); $session->set('oauth_token', $client_test_token); return $this->redirectToRoute('homepage'); } $client_id = $this->getParameter('oauth.client_id'); $client_secret = $this->getParameter('oauth.client_secret'); $base_url = $this->getParameter('oauth.base_url'); $send_url = $base_url . '/oauth/authorize'; $client = new Client($client_id, $client_secret); $redirectUrl = $request->getSchemeAndHttpHost() . $this->get('router')->generate('oauth_callback'); $authUrl = $client->getAuthenticationUrl($send_url, $redirectUrl); $this->get('logger')->info("Redirecting to {$authUrl}"); return new RedirectResponse($authUrl); }
/** * refresh access token * * @param \OAuth2\Token $token * @return \OAuth2\Token new token object */ public function refreshAccessToken(Token $token) { if (!$token->getRefreshToken()) { throw new Exception('could not refresh access token, no refresh token available'); } $parameters = array('grant_type' => 'refresh_token', 'type' => 'web_server', 'client_id' => $this->_client->getClientKey(), 'client_secret' => $this->_client->getClientSecret(), 'refresh_token' => $token->getRefreshToken()); $http = new HttpClient($this->_configuration->getAccessTokenEndpoint(), 'POST', http_build_query($parameters)); $http->execute(); return $this->_parseAccessTokenResponse($http, $token->getRefreshToken()); }
private function login() { try { // Make the call $auth_response = $this->oauth_client->getAccessToken('password', ['username' => '*****@*****.**', 'password' => 'Asdw1234##']); // Parse it $access_token = null !== $auth_response->getToken() ? $auth_response->getToken() : false; if (!$access_token) { throw new ApiException('Invalid access_token - Retry login.'); } // Set it and persist it, if needed $this->setAccessToken($access_token); // get user info from resource owner $resourceOwner = $this->oauth_client->getResourceOwner($auth_response); $user = $resourceOwner->toArray(); $this->setUser($user); return true; } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { // Failed to get the access token exit($e->getMessage()); } }
/** * Requests an OAuth2 access token and saves it in the Session * as an array representing the response and with key "accessToken". * * @param $code * @throws \OAuth2\Exception */ public function requestOAuth2AccessToken($code) { // Get OAuth2 settings $accessTokenUrl = Config::get('oauth.access_token_url'); $clientId = Config::get('oauth.client'); $clientSecret = Config::get('oauth.secret'); $redirectUrl = Config::get('oauth.redirect_uri'); $userAgent = Config::get('oauth.user_agent'); // Prepare OAuth2 client $client = new Client($clientId, $clientSecret, Client::AUTH_TYPE_AUTHORIZATION_BASIC); $client->setCurlOption(CURLOPT_USERAGENT, $userAgent); // Get access token $accessTokenResult = $this->read('accessToken'); if (null == $accessTokenResult) { $params = array('code' => $code, "redirect_uri" => $redirectUrl); $response = $client->getAccessToken($accessTokenUrl, "authorization_code", $params); $accessTokenResult = $response["result"]; $this->store('accessToken', $accessTokenResult); } // How to request any resource from Reddit // $client->setAccessToken($accessTokenResult["access_token"]); // $client->setAccessTokenType(Client::ACCESS_TOKEN_BEARER); // $this->model->response = $client->fetch("https://oauth.reddit.com/api/v1/me.json"); }
/** * Gets/sends data from the nation builder site - use for GET and DELETE * * @param $request * @param $api_call * @param $method * @param $params * @return null */ public function communicate($request, $api_call, $method = "GET", $params = array()) { $session = $request->getSession(); if (!$session->has('oauth_token')) { $this->logger->info("No oauth token found"); return NULL; } $token = $session->get('oauth_token'); $send_url = $this->base_url . $api_call; // if paginating, pass along tokens to request $input_query = $request->query->all(); if (array_key_exists('__nonce', $input_query) && array_key_exists('__token', $input_query)) { $params['__nonce'] = $input_query['__nonce']; $params['__token'] = $input_query['__token']; } $client = new Client($this->client_id, $this->client_secret); $client->setAccessToken($token); $response = $client->fetch($send_url, $params, $method); if ($response['code'] !== 200) { $this->logger->info("Could not retrieve data. Response: " . json_encode($response)); return NULL; } return $response['result']; }
/** * @param array $params * @return string * @throws Exception */ public function authenticate(array $params) { if (!isset($params['code']) || empty($params['code'])) { throw new Exception('Authentication failed, invalid or empty code.'); } $authConf = Config::$a['oauth']['providers'][$this->authProvider]; $callback = sprintf(Config::$a['oauth']['callback'], $this->authProvider); $client = new Client($authConf['clientId'], $authConf['clientSecret']); $response = $client->getAccessToken('https://accounts.google.com/o/oauth2/token', 'authorization_code', array('redirect_uri' => $callback, 'code' => $params['code'])); if (empty($response) || isset($response['error'])) { throw new Exception('Invalid access_token response'); } if (!isset($response['result']) || empty($response['result']) || !isset($response['result']['access_token'])) { throw new Exception('Failed request for access token'); } $client->setAccessToken($response['result']['access_token']); $response = $client->fetch('https://www.googleapis.com/oauth2/v2/userinfo'); if (empty($response['result']) || isset($response['error'])) { throw new Exception('Invalid user details response'); } $authCreds = $this->getAuthCredentials($params['code'], $response['result']); $authCredHandler = new AuthenticationRedirectionFilter(); return $authCredHandler->execute($authCreds); }
/** * Gets information about the given access token. * * @link https://tools.ietf.org/html/draft-richer-oauth-introspection-06 * * @param $accessTokenToIntrospect * @return \Poniverse\AccessTokenInfo * @throws InvalidAccessTokenException * @throws \Symfony\Component\HttpKernel\Exception\HttpException */ public function getAccessTokenInfo($accessTokenToIntrospect) { $token = $this->client->getAccessToken(Config::get('poniverse.urls.token'), Client::GRANT_TYPE_CLIENT_CREDENTIALS, [])['result']['access_token']; $request = \Httpful\Request::post($this->urls['api'] . 'meta/introspect?token=' . $accessTokenToIntrospect); /** @var Httpful\Response $result */ $result = $request->addHeader('Accept', 'application/json')->addHeader('Authorization', 'Bearer ' . $token)->send(); $data = json_decode($result, true); if (404 === $result->code) { throw new InvalidAccessTokenException('This access token is expired or invalid!'); } if (200 !== $result->code) { throw new \Symfony\Component\HttpKernel\Exception\HttpException(500, 'An unknown error occurred while contacting the Poniverse API.'); } $tokenInfo = new \Poniverse\AccessTokenInfo($accessTokenToIntrospect); $tokenInfo->setIsActive($data['active'])->setScopes($data['scope'])->setClientId($data['client_id']); return $tokenInfo; }
/** * revoke access token * * @return bool */ public function revokeAccessToken() { if (!$this->_dataStore->retrieveAccessToken()->getAccessToken()) { throw new Exception('could not revoke access token, no access token found, did you forgot call autorize()!!'); } if (!$this->_configuration->getRevokeEndpoint()) { throw new Exception('no revoke end point found.'); } $parameters = array('type' => 'web_server', 'client_id' => $this->_client->getClientKey(), 'access_token' => $this->_dataStore->retrieveAccessToken()->getAccessToken()); $http = new HttpClient($this->_configuration->getRevokeEndpoint(), 'POST', http_build_query($parameters)); $http->execute(); $headers = $http->getHeaders(); if ($http->getHeader('http_code') == '200') { // remove session details access_token, refresh_token, ... $this->_dataStore->removeAccessToken(); return true; } else { return false; } }
/** * Exchanges the code from the URI parameters for an access token, id token and user info * @return Boolean Wheter it exchanged the code or not correctly */ private function exchangeCode() { if (!isset($_REQUEST['code'])) { return false; } $code = $_REQUEST['code']; $this->debugInfo("Code: " . $code); // Generate the url to the API that will give us the access token and id token $auth_url = $this->generateUrl('token'); // Make the call $auth0_response = $this->oauth_client->getAccessToken($auth_url, "authorization_code", array("code" => $code, "redirect_uri" => $this->redirect_uri)); // Parse it $auth0_response = $auth0_response['result']; $this->debugInfo(json_encode($auth0_response)); $access_token = isset($auth0_response['access_token']) ? $auth0_response['access_token'] : false; $id_token = isset($auth0_response['id_token']) ? $auth0_response['id_token'] : false; if (!$access_token) { throw new ApiException('Invalid access_token - Retry login.'); } // Set the access token in the oauth client for future calls to the Auth0 API $this->oauth_client->setAccessToken($access_token); $this->oauth_client->setAccessTokenType(Client::ACCESS_TOKEN_BEARER); // Set it and persist it, if needed $this->setAccessToken($access_token); $this->setIdToken($id_token); $token = Auth0JWT::decode($id_token, $this->client_id, $this->client_secret); $user = ApiUsers::get($this->domain, $id_token, $token->user_id); $this->setUser($user); return true; }
/** * Exchanges the code from the URI parameters for an access token, id token and user info * @return Boolean Whether it exchanged the code or not correctly */ private function exchangeCode() { if (!isset($_REQUEST['code'])) { return false; } $code = $_REQUEST['code']; $this->debugInfo("Code: " . $code); // Generate the url to the API that will give us the access token and id token $auth_url = $this->generateUrl('token'); // Make the call $response = $this->oauth_client->getAccessToken($auth_url, "authorization_code", array("code" => $code, "redirect_uri" => $this->redirect_uri), array('Auth0-Client' => ApiClient::getInfoHeadersData()->build())); $auth0_response = $response['result']; if ($response['code'] !== 200) { throw new ApiException($auth0_response['error'] . ': ' . $auth0_response['error_description']); } $this->debugInfo(json_encode($auth0_response)); $access_token = isset($auth0_response['access_token']) ? $auth0_response['access_token'] : false; $id_token = isset($auth0_response['id_token']) ? $auth0_response['id_token'] : false; if (!$access_token) { throw new ApiException('Invalid access_token - Retry login.'); } if (!$id_token) { // id_token is not mandatory anymore. There is no need to force openid connect $this->debugInfo('Missing id_token after code exchange. Remember to ask for openid scope.'); } // Set the access token in the oauth client for future calls to the Auth0 API $this->oauth_client->setAccessToken($access_token); $this->oauth_client->setAccessTokenType(Client::ACCESS_TOKEN_BEARER); // Set it and persist it, if needed $this->setAccessToken($access_token); $this->setIdToken($id_token); $userinfo_url = $this->generateUrl('user_info'); $user = $this->oauth_client->fetch($userinfo_url); $this->setUser($user["result"]); return true; }
/** * Requests user info to Auth0 server. * * @return array */ public final function getUserInfo() { $userinfo_url = $this->generateUrl('user_info'); return $this->oauth_client->fetch($userinfo_url); }