本文整理汇总了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;
}
}
示例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');
}
}
}
示例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;
}
示例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;
}
示例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);
}
示例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');
}
示例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);
}
示例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);
}
示例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'];
}
示例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);
}
示例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']);
}
}
示例12: getUsuario
public static function getUsuario()
{
$headers = apache_request_headers();
$token = explode(" ", $headers["Authorization"]);
$usuario = JWT::decode(trim($token[1], '"'), "complejodeportivo", 'HS256');
return $usuario;
}
示例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;
}
}
示例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;
}
}
示例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;
}