当前位置: 首页>>代码示例>>PHP>>正文


PHP JWT::decode方法代码示例

本文整理汇总了PHP中JWT::decode方法的典型用法代码示例。如果您正苦于以下问题:PHP JWT::decode方法的具体用法?PHP JWT::decode怎么用?PHP JWT::decode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在JWT的用法示例。


在下文中一共展示了JWT::decode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: verifyToken

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;
    }
}
开发者ID:Ayeblinken,项目名称:potonka,代码行数:32,代码来源:authentication_helper.php

示例2: initialize

 /**
  * 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');
         }
     }
 }
开发者ID:Jamp,项目名称:sgas,代码行数:35,代码来源:rest_controller.php

示例3: validate_id_token

 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;
 }
开发者ID:xscript,项目名称:aad-first-party-sso-wordpress,代码行数:31,代码来源:AuthorizationHelper.php

示例4: func_responce

 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;
 }
开发者ID:Aspirant2011,项目名称:pelsukov.com,代码行数:27,代码来源:gwallet_model.php

示例5: confirmation

 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);
 }
开发者ID:joelafrica,项目名称:planitsurveyportal,代码行数:33,代码来源:AnswersController.php

示例6: testKIDChooser

 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');
 }
开发者ID:nightstomp,项目名称:php-jwt,代码行数:7,代码来源:JWTTest.php

示例7: decode

 /**
  * 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);
 }
开发者ID:samjarrett,项目名称:jwt-bundle,代码行数:15,代码来源:Manager.php

示例8: onPaymentNotification

 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);
 }
开发者ID:q0821,项目名称:esportshop,代码行数:34,代码来源:googlewallet.php

示例9: userId

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'];
}
开发者ID:paulstefanday,项目名称:HumbleCommunity,代码行数:7,代码来源:helpers.php

示例10: __construct

 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);
 }
开发者ID:davidfallon,项目名称:FuelSDK-PHP,代码行数:60,代码来源:ET_Client.php

示例11: require_login

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']);
    }
}
开发者ID:jeena,项目名称:Quill,代码行数:33,代码来源:controllers.php

示例12: getUsuario

 public static function getUsuario()
 {
     $headers = apache_request_headers();
     $token = explode(" ", $headers["Authorization"]);
     $usuario = JWT::decode(trim($token[1], '"'), "complejodeportivo", 'HS256');
     return $usuario;
 }
开发者ID:beimarhuarachi,项目名称:compleapp,代码行数:7,代码来源:Verificador.php

示例13: validateRol

/**
 * @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;
    }
}
开发者ID:arielcessario,项目名称:angular-tests,代码行数:31,代码来源:utils.php

示例14: checkSecurity

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;
    }
}
开发者ID:arielcessario,项目名称:hydrox-V2,代码行数:30,代码来源:cliente.php

示例15: verifyIdToken

 /**
  * 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;
 }
开发者ID:rahul9878,项目名称:google-api-php-client,代码行数:43,代码来源:Verify.php


注:本文中的JWT::decode方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。