decode() public static method

Decodes a JWT string into a PHP object.
public static decode ( string $jwt, string | Array | null $key = null, boolean $verify = true ) : object
$jwt string The JWT
$key string | Array | null The secret key, or map of keys
$verify boolean Don't skip verification process
return object The JWT's payload as a PHP object
Beispiel #1
1
 /**
  * Inicialización de la petición
  * ****************************************
  * Aqui debe ir la autenticación de la API
  * ****************************************
  */
 protected final function initialize()
 {
     $router = Router::get();
     // Habilitando CORS para hacer funcional el RESTful
     header('Access-Control-Allow-Origin: *');
     header('Access-Control-Allow-Credentials: true');
     // Habilitar todos los headers que recibe (Authorization sobre todo para manejar JWT)
     $requestHeaders = $this->getHeaders();
     $request = array_keys($requestHeaders);
     header("Access-Control-Allow-Headers: " . implode(',', $request) . ',Authorization');
     // Verificar los accesos y validez de token
     // TODO: Implementar un limit a la consultas de getAll() por seguridad cuando la vista sea pública
     if (!($this->publicView && ($router['method'] == 'GET' || $router['method'] == 'OPTIONS'))) {
         // Precendia del Token
         if (!empty($requestHeaders['Authorization'])) {
             $token = $requestHeaders['Authorization'];
             $this->me = JWT::decode(str_replace('Bearer ', '', $token), TOKEN);
             $now = time();
             // Verificamos que este activo
             if ($now >= $this->me->exp) {
                 $this->setCode(403);
                 die('Error 403 - Acceso Denegado');
             }
         } else {
             $this->setCode(403);
             die('Error 403 - Acceso Denegado');
         }
     }
 }
 public static function validate_id_token($id_token)
 {
     $jwt = null;
     $lastException = null;
     // TODO: cache the keys
     $discovery = json_decode(file_get_contents(self::$base_uri . self::$keys_endpoint));
     if ($discovery->keys == null) {
         throw new DomainException('base_uri + keys_endpoint does not contain the keys attribute');
     }
     foreach ($discovery->keys as $key) {
         try {
             if ($key->x5c == null) {
                 throw new DomainException('key does not contain the x5c attribute');
             }
             $key_der = $key->x5c[0];
             // Per section 4.7 of the current JWK draft [1], the 'x5c' property will be the DER-encoded value
             // of the X.509 certificate. PHP's openssl functions all require a PEM-encoded value.
             $key_pem = chunk_split($key_der, 64, "\n");
             $key_pem = "-----BEGIN CERTIFICATE-----\n" . $key_pem . "-----END CERTIFICATE-----\n";
             // This throws exception if the id_token cannot be validated.
             $jwt = JWT::decode($id_token, $key_pem, self::$allowed_algorithms);
             break;
         } catch (Exception $e) {
             $lastException = $e;
         }
     }
     if ($jwt == null) {
         throw $lastException;
     }
     return $jwt;
 }
Beispiel #3
0
 function testKIDChooser()
 {
     $keys = array('1' => 'my_key', '2' => 'my_key2');
     $msg = JWT::encode('abc', $keys['1'], 'HS256', '1');
     $decoded = JWT::decode($msg, $keys, true);
     $this->assertEquals($decoded, 'abc');
 }
Beispiel #4
0
 function onPaymentNotification(&$statuses)
 {
     $this->pluginParams();
     $this->payment_params = $this->plugin_params;
     if ($this->payment_params->debug) {
         $this->writeToLog("JWT from googlewallet: \n\n\n" . print_r($_POST, true));
     }
     $gwdata = JWT::decode($_POST["jwt"], null, false);
     if (empty($gwdata)) {
         return false;
     }
     if ($this->payment_params->debug) {
         $this->writeToLog("Decoded data from googlewallet: \n\n\n" . print_r($gwdata, true));
     }
     $dbOrder = $this->getOrder($gwdata->request->sellerData);
     $this->loadPaymentParams($dbOrder);
     $gwdata = JWT::decode($_POST["jwt"], $this->payment_params->sellerSecret, true);
     if (empty($gwdata)) {
         return false;
     }
     $orderId = $gwdata->response->orderId;
     if ($orderId) {
         echo $orderId;
         ob_start();
         $order_status = $this->payment_params->verified_status;
         $this->modifyOrder($order_id, $order_status, true, true);
         return true;
     }
     $email = new stdClass();
     $email->subject = JText::sprintf('PAYMENT_NOTIFICATION_FOR_ORDER', 'Google Wallet', 'Unknown', $dbOrder->order_number);
     $email->body = str_replace('<br/>', "\r\n", JText::sprintf('PAYMENT_NOTIFICATION_STATUS', 'Google Wallet', 'Unknown')) . ' ' . JText::_('STATUS_NOT_CHANGED');
     $action = false;
     $this->modifyOrder($action, null, null, $email);
 }
Beispiel #5
0
 /**
  * @param      $token
  * @param null $expire
  *
  * @return null
  */
 public static function check($token, $expire = null)
 {
     $salt = \Config::get('schauth::config.token.salt');
     // token decode
     $userToken = \JWT::decode($token, $salt, array('HS256'));
     // check token data
     if (empty($userToken->time) || empty($userToken->id)) {
         return null;
     }
     if (!empty($userToken->expAt)) {
         // check token expire at
         if ($userToken->expAt < time()) {
             return null;
         }
     } else {
         if ($expire === null) {
             $expire = \Config::get('schauth::config.expire.token_web');
             if ($expire < 60) {
                 $expire = 60;
             }
         }
         // check token expire
         if ($userToken->time + $expire < time()) {
             return null;
         }
     }
     return $userToken;
 }
Beispiel #6
0
 function __construct($getWSDL = false, $debug = false, $params = null)
 {
     $tenantTokens = array();
     $config = @(include 'config.php');
     if ($config) {
         $this->wsdlLoc = $config['defaultwsdl'];
         $this->clientId = $config['clientid'];
         $this->clientSecret = $config['clientsecret'];
         $this->appsignature = $config['appsignature'];
     } else {
         if ($params && array_key_exists('defaultwsdl', $params)) {
             $this->wsdlLoc = $params['defaultwsdl'];
         } else {
             $this->wsdlLoc = "https://webservice.exacttarget.com/etframework.wsdl";
         }
         if ($params && array_key_exists('clientid', $params)) {
             $this->clientId = $params['clientid'];
         }
         if ($params && array_key_exists('clientsecret', $params)) {
             $this->clientSecret = $params['clientsecret'];
         }
         if ($params && array_key_exists('appsignature', $params)) {
             $this->appsignature = $params['appsignature'];
         }
     }
     $this->debugSOAP = $debug;
     if (!property_exists($this, 'clientId') || is_null($this->clientId) || !property_exists($this, 'clientSecret') || is_null($this->clientSecret)) {
         throw new Exception('clientid or clientsecret is null: Must be provided in config file or passed when instantiating ET_Client');
     }
     if ($getWSDL) {
         $this->CreateWSDL($this->wsdlLoc);
     }
     if ($params && array_key_exists('jwt', $params)) {
         if (!property_exists($this, 'appsignature') || is_null($this->appsignature)) {
             throw new Exception('Unable to utilize JWT for SSO without appsignature: Must be provided in config file or passed when instantiating ET_Client');
         }
         $decodedJWT = JWT::decode($params['jwt'], $this->appsignature);
         $dv = new DateInterval('PT' . $decodedJWT->request->user->expiresIn . 'S');
         $newexpTime = new DateTime();
         $this->setAuthToken($this->tenantKey, $decodedJWT->request->user->oauthToken, $newexpTime->add($dv));
         $this->setInternalAuthToken($this->tenantKey, $decodedJWT->request->user->internalOauthToken);
         $this->setRefreshToken($this->tenantKey, $decodedJWT->request->user->refreshToken);
         $this->packageName = $decodedJWT->request->application->package;
     }
     $this->refreshToken();
     try {
         $url = "https://www.exacttargetapis.com/platform/v1/endpoints/soap?access_token=" . $this->getAuthToken($this->tenantKey);
         $endpointResponse = restGet($url);
         $endpointObject = json_decode($endpointResponse->body);
         if ($endpointResponse && property_exists($endpointObject, "url")) {
             $this->endpoint = $endpointObject->url;
         } else {
             throw new Exception('Unable to determine stack using /platform/v1/endpoints/:' . $endpointResponse->body);
         }
     } catch (Exception $e) {
         throw new Exception('Unable to determine stack using /platform/v1/endpoints/: ' . $e->getMessage());
     }
     parent::__construct($this->LocalWsdlPath(), array('trace' => 1, 'exceptions' => 0));
     parent::__setLocation($this->endpoint);
 }
Beispiel #7
0
 /**
  * Decodes a JWT string into a PHP object.
  *
  * @param string      $jwt           The JWT
  * @param array|null  $allowed_algs  List of supported verification algorithms
  *
  * @return object      The JWT's payload as a PHP object
  */
 public function decode($jwt, $allowedAlgs = array())
 {
     if (empty($allowedAlgs)) {
         $allowedAlgs = array($this->alg);
     }
     return \JWT::decode($jwt, $this->key, $allowedAlgs);
 }
 public static function getUsuario()
 {
     $headers = apache_request_headers();
     $token = explode(" ", $headers["Authorization"]);
     $usuario = JWT::decode(trim($token[1], '"'), "complejodeportivo", 'HS256');
     return $usuario;
 }
function userId()
{
    $token = explode(' ', Request::header('Authorization'))[1];
    $payloadObject = JWT::decode($token, Config::get('secrets.TOKEN_SECRET'));
    $payload = json_decode(json_encode($payloadObject), true);
    return $payload['sub'];
}
Beispiel #10
0
function checkSecurity()
{
    $requestHeaders = apache_request_headers();
    $authorizationHeader = $requestHeaders['Authorization'];
    //    echo print_r(apache_request_headers());
    if ($authorizationHeader == null) {
        header('HTTP/1.0 401 Unauthorized');
        echo "No authorization header sent";
        exit;
    }
    // // validate the token
    $pre_token = str_replace('Bearer ', '', $authorizationHeader);
    $token = str_replace('"', '', $pre_token);
    $secret = 'uiglp';
    global $decoded_token;
    try {
        $decoded_token = JWT::decode($token, base64_decode(strtr($secret, '-_', '+/')), false);
        //        $decoded_token = JWT::decode($token, 'uiglp');
    } catch (UnexpectedValueException $ex) {
        header('HTTP/1.0 401 Unauthorized');
        echo "Invalid token";
        exit;
    }
    // // validate that this token was made for us
    if ($decoded_token->aud != 'uiglp') {
        header('HTTP/1.0 401 Unauthorized');
        echo "Invalid token";
        exit;
    }
}
Beispiel #11
0
function require_login(&$app, $redirect = true)
{
    $params = $app->request()->params();
    if (array_key_exists('token', $params)) {
        try {
            $data = JWT::decode($params['token'], Config::$jwtSecret);
            $_SESSION['user_id'] = $data->user_id;
            $_SESSION['me'] = $data->me;
        } catch (DomainException $e) {
            if ($redirect) {
                header('X-Error: DomainException');
                $app->redirect('/', 301);
            } else {
                return false;
            }
        } catch (UnexpectedValueException $e) {
            if ($redirect) {
                header('X-Error: UnexpectedValueException');
                $app->redirect('/', 301);
            } else {
                return false;
            }
        }
    }
    if (!array_key_exists('user_id', $_SESSION)) {
        if ($redirect) {
            $app->redirect('/');
        }
        return false;
    } else {
        return ORM::for_table('users')->find_one($_SESSION['user_id']);
    }
}
 /**
  * Verifies an id token and returns the authenticated apiLoginTicket.
  * Throws an exception if the id token is not valid.
  * The audience parameter can be used to control which id tokens are
  * accepted.  By default, the id token must have been issued to this OAuth2 client.
  *
  * @param $audience
  * @return array the token payload, if successful
  */
 public function verifyIdToken($idToken, $audience = null)
 {
     if (empty($idToken)) {
         throw new LogicException('id_token cannot be null');
     }
     // Check signature
     $certs = $this->getFederatedSignonCerts();
     foreach ($certs as $cert) {
         $modulus = new BigInteger(JWT::urlsafeB64Decode($cert['n']), 256);
         $exponent = new BigInteger(JWT::urlsafeB64Decode($cert['e']), 256);
         $rsa = new RSA();
         $rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
         try {
             $payload = JWT::decode($idToken, $rsa->getPublicKey(), array('RS256'));
             if (property_exists($payload, 'aud')) {
                 if ($audience && $payload->aud != $audience) {
                     return false;
                 }
             }
             // support HTTP and HTTPS issuers
             // @see https://developers.google.com/identity/sign-in/web/backend-auth
             $issuers = array(self::OAUTH2_ISSUER, self::OAUTH2_ISSUER_HTTPS);
             if (!isset($payload->iss) || !in_array($payload->iss, $issuers)) {
                 return false;
             }
             return (array) $payload;
         } catch (ExpiredException $e) {
             return false;
         } catch (DomainException $e) {
             // continue
         }
     }
     return false;
 }
Beispiel #13
0
/**
 * @description Valida que el rol del usuario sea el correcto
 * @param $requerido
 */
function validateRol($requerido)
{
    global $jwt_enabled;
    if ($jwt_enabled == false) {
        return;
    }
    $requestHeaders = apache_request_headers();
    $authorizationHeader = isset($requestHeaders['Authorization']) ? $requestHeaders['Authorization'] : null;
    //    echo print_r(apache_request_headers());
    if ($authorizationHeader == null) {
        header('HTTP/1.0 401 Unauthorized');
        echo "No authorization header sent";
        exit;
    }
    // // validate the token
    $pre_token = str_replace('Bearer ', '', $authorizationHeader);
    $token = str_replace('"', '', $pre_token);
    global $secret;
    global $decoded_token;
    $decoded_token = JWT::decode($token, $secret, true);
    $rol = $decoded_token->data->rol;
    if ($rol > $requerido) {
        header('HTTP/1.0 401 Unauthorized');
        echo "No authorization header sent";
        exit;
    }
}
Beispiel #14
0
function validatetoken($redirectpage)
{
    // get oauth token from cookie
    // if not present redirect to $redirectpage
    // if found check that token is valid by decoding it
    if (isset($_COOKIE["access_token"])) {
        $secretkeyfile = 'oauth.txt';
        $secret = "";
        // read oauth shared secret from local file
        if (is_file($secretkeyfile)) {
            $lines = file($secretkeyfile);
            foreach ($lines as $line) {
                $secret = base64_decode($line);
                break;
            }
        } else {
            error_log("validatetoken: file not found: " . $secretkeyfile);
            die("internal error - token validation");
        }
        include_once 'JWT.php';
        $access_token = $_COOKIE["access_token"];
        try {
            $jwt = JWT::decode($access_token, $secret, true);
            return $jwt;
        } catch (Exception $e) {
            $msg = $e->getMessage();
            echo 'Token validation error: ', $msg, "\n";
            error_log("validatetoken: invalid token : " . $msg);
        }
    }
    setcookie("access_token", "", time() - 3600);
    redirect($redirectpage);
}
 public function confirmation()
 {
     App::uses('JWT', 'Vendor');
     $server_security_key = Configure::read('Security.key');
     $token = urldecode($this->request->query['token']);
     $token_info = JWT::decode($token, '$server_security_key');
     if ($this->request->is('post')) {
         $actionButton = isset($this->request->data['confirm']) ? 'confirm' : 'cancel';
         switch ($actionButton) {
             case 'cancel':
                 $this->set('sucess_msg', 'You chose not to submit the survey at this time.  Resume the survey at your convenience by following the link sent to your e-mail by Planit.');
                 break;
             case 'confirm':
                 $timestamp = date('Y-m-d G:i:s');
                 $this->Answer->create();
                 $this->Answer->updateAll(array('Answer.submission_date' => "'" . $timestamp . "'"), array('Answer.user_id' => $token_info->userid, 'survey_id' => $token_info->surveyid));
                 $this->set('sucess_msg', 'Your survey data have been sent to Planit.  Thank you for providing your time in completing the survey.');
                 //$this->Session->setFlash('You have completed the survey.  Thank you.', 'default', array(), 'processing_msg_success');
                 break;
         }
     } else {
         $action = $this->request->query['action'];
         switch ($action) {
             case "save":
                 $this->set('action', 'save');
                 break;
             case "submit":
                 $this->set('action', 'submit');
                 break;
         }
     }
     $this->set('tokeninfo', $token_info);
 }
 public function func_responce($payment_data, $system_settings)
 {
     $return = array("errors" => array(), "info" => array(), "data" => array(), "type" => "exit");
     $this->CI->load->library('JWT');
     try {
         $payment_data = (array) JWT::decode($payment_data['jwt'], $system_settings["settings_data"]["seller_secret"]);
         $payment_data = array_merge($payment_data['request'], $payment_data['responce']);
     } catch (Exception $e) {
         $payment_data = array();
     }
     foreach ($this->variables as $payment_var => $site_var) {
         $return["data"][$site_var] = isset($payment_data[$payment_var]) ? $this->CI->input->xss_clean($payment_data[$payment_var]) : "";
     }
     $error = false;
     $this->CI->load->model("Payments_model");
     $site_payment_data = $this->CI->Payments_model->get_payment_by_id($return['data']['id_payment']);
     if (floatval($site_payment_data['amount']) != floatval($return['data']['amount']) || $site_payment_data['currency_gid'] != $return['data']['currency']) {
         $error = true;
     }
     if ($error) {
         $return["data"]["status"] = -1;
     } else {
         $return["data"]["status"] = 1;
         echo $return['data']['payment_id'];
     }
     return $return;
 }
 public static function validateIdToken($id_token, $settings, $antiforgery_id)
 {
     $jwt = NULL;
     $lastException = NULL;
     // TODO: cache the keys
     $discovery = json_decode(file_get_contents($settings->jwks_uri));
     if ($discovery->keys == NULL) {
         throw new DomainException('jwks_uri does not contain the keys attribute');
     }
     foreach ($discovery->keys as $key) {
         try {
             if ($key->x5c == NULL) {
                 throw new DomainException('key does not contain the x5c attribute');
             }
             $key_der = $key->x5c[0];
             // Per section 4.7 of the current JWK draft [1], the 'x5c' property will be the DER-encoded value
             // of the X.509 certificate. PHP's openssl functions all require a PEM-encoded value.
             $key_pem = chunk_split($key_der, 64, "\n");
             $key_pem = "-----BEGIN CERTIFICATE-----\n" . $key_pem . "-----END CERTIFICATE-----\n";
             // This throws exception if the id_token cannot be validated.
             $jwt = JWT::decode($id_token, $key_pem, self::$allowed_algorithms);
             break;
         } catch (Exception $e) {
             $lastException = $e;
         }
     }
     if ($jwt == NULL) {
         throw $lastException;
     }
     if ($jwt->nonce != $antiforgery_id) {
         throw new DomainException(sprintf('Nonce mismatch. Expecting %s', $antiforgery_id));
     }
     return $jwt;
 }
 public function jwt_decode($token)
 {
     try {
         return JWT::decode($token, F3::get('custom.SUPER-KEY'));
     } catch (Exception $e) {
         return false;
     }
 }
 function testDecodeWithAuthToken()
 {
     try {
         $token = new Services_Twilio_Capability('AC123', 'foo');
         $payload = JWT::decode($token->generateToken(), 'foo');
     } catch (UnexpectedValueException $e) {
         $this->assertTrue(false, "Could not decode with 'foo'");
     }
 }
 private static function verifySignatureFirebase($jwt)
 {
     $jwtCertsJSON = SessionCache::get(self::$JWT_CERTS_CACHE_KEY);
     if ($jwtCertsJSON === FALSE) {
         $jwtCertsJSON = HttpUtil::processRequest('https://www.googleapis.com/oauth2/v1/certs');
         SessionCache::set(self::$JWT_CERTS_CACHE_KEY, $jwtCertsJSON);
     }
     $jwtCerts = json_decode($jwtCertsJSON, TRUE);
     return JWT::decode($jwt, $jwtCerts);
 }
 public function decodeJWTToken($token)
 {
     try {
         $objDecodedToken = \JWT::decode($token, $this->secret, true);
     } catch (UnexpectedValueException $ex) {
         //        header('HTTP/1.0 401 Unauthorized');
         return false;
     }
     return $objDecodedToken;
 }
 /**
  * Validate Jwt token data
  *
  * @param string $token_field_name
  * @param PyStringNode $jsonString
  *
  * @Then /^(?:the )?response should contain jwt token in field "([^"]*)" with data:$/
  */
 public function responseShouldContainJwtTokenInFieldWithData($token_field_name, PyStringNode $jsonString)
 {
     $expected = json_decode($this->replacePlaceHolder($jsonString->getRaw()), true);
     $response = $this->response->json();
     Assertions::assertArrayHasKey($token_field_name, $response);
     $actual = \JWT::decode($response[$token_field_name], $this->config['secret_key']);
     foreach ($expected as $key => $needle) {
         Assertions::assertObjectHasAttribute($key, $actual);
         Assertions::assertEquals($expected[$key], $actual->{$key});
     }
 }
 public function decode($jwt, $key = null, $allowedAlgorithms = null)
 {
     try {
         //Maintain BC: Do not verify if no algorithms are passed in.
         if (!$allowedAlgorithms) {
             $key = null;
         }
         return (array) \JWT::decode($jwt, $key, $allowedAlgorithms);
     } catch (\Exception $e) {
         return false;
     }
 }
Beispiel #24
0
 public function updateUser()
 {
     $token = explode(' ', Request::header('Authorization'))[1];
     $payloadObject = JWT::decode($token, Config::get('secrets.TOKEN_SECRET'));
     $payload = json_decode(json_encode($payloadObject), true);
     $user = User::find($payload['sub']);
     $user->displayName = Input::get('displayName', $user->displayName);
     $user->email = Input::get('email', $user->email);
     $user->save();
     $token = $this->createToken($user);
     return Response::json(array('token' => $token));
 }
Beispiel #25
0
 /**
  * @soap
  * @return string
  */
 public function check()
 {
     // Retreive the authorization header
     if (!function_exists('apache_request_headers')) {
         function apache_request_headers()
         {
             $arh = array();
             $rx_http = '/\\AHTTP_/';
             foreach ($_SERVER as $key => $val) {
                 if (preg_match($rx_http, $key)) {
                     $arh_key = preg_replace($rx_http, '', $key);
                     $rx_matches = array();
                     // do some nasty string manipulations to restore the original letter case
                     // this should work in most cases
                     $rx_matches = explode('_', $arh_key);
                     if (count($rx_matches) > 0 and strlen($arh_key) > 2) {
                         foreach ($rx_matches as $ak_key => $ak_val) {
                             $rx_matches[$ak_key] = ucfirst($ak_val);
                         }
                         $arh_key = implode('-', $rx_matches);
                     }
                     $arh[ucfirst(strtolower($arh_key))] = $val;
                 }
             }
             return $arh;
         }
     }
     $requestHeaders = apache_request_headers();
     $authorizationHeader = @$requestHeaders['AUTHORIZATION'];
     if ($authorizationHeader == null) {
         header('HTTP/1.0 401 Unauthorized');
         echo "No authorization header sent";
         exit;
     }
     // Validate the token
     $token = str_replace('Bearer ', '', $authorizationHeader);
     $secret = 'QsJTRnA6ccboG-mNKKE4XsNc_RP2tvltBhfzzQ7_geow8Yz9Z5EZRk9XLkmMRgdQ';
     $decoded_token = null;
     try {
         $decoded_token = \JWT::decode($token, base64_decode(strtr($secret, '-_', '+/')));
     } catch (UnexpectedValueException $ex) {
         header('HTTP/1.0 401 Unauthorized');
         echo "Invalid token";
         exit;
     }
     // Validate that this token was made for us
     if ($decoded_token->aud != 'BAZxb4JU6TN99UZ1bcJVepvmlMiCIxvR0') {
         header('HTTP/1.0 401 Unauthorized');
         echo "Invalid token";
         exit;
     }
 }
 /**
  * Token for decoding
  *
  * @param string $token
  * @return array
  *
  * @throws AccessDeniedException
  */
 public function decode($token)
 {
     try {
         $data = \JWT::decode($token, $this->secretKey, $this->allowed_algs);
     } catch (\UnexpectedValueException $e) {
         throw new \UnexpectedValueException($e->getMessage());
     } catch (\DomainException $e) {
         throw new \UnexpectedValueException($e->getMessage());
     }
     if ($data->exp < time()) {
         throw new \UnexpectedValueException('token not allowed');
     }
     return $data;
 }
Beispiel #27
0
 public static function checkToken($app)
 {
     return function () use($app) {
         $res = $app->response();
         //$data = json_decode($app->request->getBody());
         //$token = $data->token;
         $token = $app->request->headers->get('token');
         $token = JWT::decode($token, $_SERVER['SECRET_KEY']);
         if (!$token->admin) {
             $res->status(401);
             $res->body('auth error');
         }
     };
 }
 public function login()
 {
     App::uses('JWT', 'Vendor');
     $server_security_key = Configure::read('Security.key');
     $token = urldecode($this->request->query['token']);
     $token_info = JWT::decode($token, '$server_security_key');
     $user_details = $this->User->find('first', array('conditions' => array('User.id' => $token_info->userid)));
     if (!empty($user_details)) {
         $this->redirect(array('controller' => 'Answers', 'action' => 'add', '?' => array('token' => $this->request->query['token'])));
     } else {
         $this->Session->setFlash('Access denied.  Token is either expired or invalid. Please contact Planit to get a valid token.', 'default', array(), 'auth_login');
     }
     $this->set('tokeninfo', $token_arr);
 }
Beispiel #29
0
 public function setRequest(Request $request)
 {
     $jwt = false;
     $authorizationHeader = $request->headers->get('X-JWT-Authorization');
     $matches = [];
     // we always take the Authorization header over the query param
     if (preg_match('/^Token (.*)$/', $authorizationHeader, $matches)) {
         $jwt = $matches[1];
     }
     if ($jwt) {
         $decoded = TokenLib::decode($jwt, $this->key, array('HS256'));
         $this->jwt = (array) $decoded;
     }
 }
function verifyToken()
{
    if (AUTH_TURNED_OFF) {
        return true;
    }
    $CI = get_instance();
    if ($CI->input->get_request_header('Authorization')) {
        $tokenHeader = $CI->input->get_request_header('Authorization', TRUE);
        try {
            $token = JWT::decode($tokenHeader, JWT_KEY);
        } catch (Exception $e) {
            return false;
        }
    } else {
        $token = null;
    }
    if ($token->time != "Permanent") {
        $loginTime = new DateTime($token->time);
        $nowTime = new DateTime(date("Y-m-d H:i:s", time()));
        $interval = $loginTime->diff($nowTime);
        $hoursDifference = $interval->h + $interval->days * 24;
        // $minutesDifference = $interval->i + ($hoursDifference * 60);
        if ($hoursDifference >= 48) {
            return false;
        }
    }
    if ($token !== null && $token !== false && $token->privilegeSet !== "Reset") {
        return $token->privilegeSet;
    } else {
        return false;
    }
}