本文整理汇总了PHP中JWT类的典型用法代码示例。如果您正苦于以下问题:PHP JWT类的具体用法?PHP JWT怎么用?PHP JWT使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JWT类的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: from_token
public static function from_token($token, $secret)
{
$vector = explode(".", $token);
if (count($vector) == 3) {
$js = json_decode(base64_decode($vector[0]), true);
$p = $vector[0] . "." . $vector[1];
if ($vector[2] == hash_hmac($js["alg"], $p, $secret)) {
$jwt = new JWT();
$jwt->setHeader($js["alg"]);
$jwt->setPayload(base64_decode($vector[1]));
}
}
return $jwt;
}
示例3: 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');
}
示例4: validatetoken
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);
}
示例5: execute
public function execute()
{
$user = $this->getUser();
if ($user->isBlocked()) {
$this->dieUsageMsg('blockedtext');
}
if (!$user->isLoggedIn()) {
$this->dieUsage('Must be logged in', 'token-impossible');
}
// Do not fatal out
if (!class_exists('JWT')) {
$this->dieUsage('JWT missing', 'token-impossible');
}
$config = $this->getConfig()->get('ContentTranslationCXServerAuth');
$algorithm = $config['algorithm'];
$key = $config['key'];
if ($key === '') {
$this->dieUsage('Key not configured', 'token-impossible');
}
$exp = time() + $config['age'];
$token = array('sub' => $user->getName(), 'iat' => time(), 'exp' => $exp);
$jwt = JWT::encode($token, $key, $algorithm);
$this->getResult()->addValue(null, 'jwt', $jwt);
$this->getResult()->addValue(null, 'exp', $exp);
}
开发者ID:Rjaylyn,项目名称:mediawiki-extensions-ContentTranslation,代码行数:25,代码来源:ApiContentTranslationToken.php
示例6: 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;
}
}
示例7: login
public function login()
{
// check ajax request
if ($this->input->is_ajax_request()) {
// check post parameter
if (!$this->input->post("username") || !$this->input->post("password")) {
echo json_encode(array("code" => 2, "response" => "Data insufficient"));
}
$uname = $this->input->post("username");
$password = $this->input->post("password");
// check login
$user = $this->Login_mdl->login($uname, $password);
// $sid=$this->Login_mdl->addsession($user->user_id,$user->user_name,$user->db_pass);
if ($user !== false) {
$chksesstbl = $this->Login_mdl->check_active_user($user->user_id);
if ($chksesstbl) {
$this->Login_mdl->reset_active_session($user->user_id);
}
$sessionid = session_id();
$sid = $this->Login_mdl->add_new_session($user->user_id, $sessionid);
$user->iat = time();
$user->exp = time() + 28800000;
//8 hr extend; default 5000
$user->sid = $sid;
//encdoe token
$jwt = JWT::encode($user, SECRECT_KEY);
echo json_encode(array("data" => $user, 'token' => $jwt, "status" => array("code" => 0, 'success' => true, 'msg' => $sessionid)));
} else {
echo json_encode(array("data" => '', 'token' => '', "status" => array("code" => 0, 'success' => false, 'msg' => '')));
}
}
}
示例8: createToken
/**
* @access public
* @param array|object $data An object or array of data you wish
* to associate with the token. It will
* be available as the variable "auth" in
* the Firebase rules engine.
* @param object $options Optional. An associative array with
* the developer supplied options for this
* token. The following keys are recognized:
*
* 'admin': Set to true if you want this
* token to bypass all security rules.
* Defaults to false.
*
* 'debug': Set to true if you want to
* enable debug output from your security
* rules.
*
* 'expires': Set to a number (seconds
* since epoch) or a DateTime object that
* specifies the time at which the token
* should expire.
*
* 'notBefore': Set to a number (seconds
* since epoch) or a DateTime object that
* specifies the time before which the
* should be rejected by the server.
*
*
* @return string A Firebase auth token.
*/
public function createToken($data, $options = null)
{
$funcName = 'Services_FirebaseTokenGenerator->createToken';
// If $data is JSONifiable, let it pass.
$json = json_encode($data);
if (function_exists("json_last_error") && ($errno = json_last_error())) {
$this->handleJSONError($errno);
} else {
if ($json === "null" && $data !== null) {
throw new UnexpectedValueException("Data is not valid JSON");
} else {
if (empty($data) && empty($options)) {
throw new Exception($funcName + ": data is empty and no options are set. This token will have no effect on Firebase.");
}
}
}
$claims = array();
if (is_array($options)) {
$claims = $this->_processOptions($options);
}
$claims["d"] = $data;
$claims["v"] = $this->version;
$claims["iat"] = time();
return JWT::encode($claims, $this->secret, "HS256");
}
示例9: encode
/**
* Converts and signs a PHP object or array into a JWT string.
*
* @param object|array $payload PHP object or array
* @param string|null $alg The signing algorithm. Supported
* algorithms are 'HS256', 'HS384' and 'HS512'
*
* @return string A signed JWT
*/
public function encode($payload, $alg = null)
{
if (empty($alg)) {
$alg = $this->alg;
}
return \JWT::encode($payload, $this->key, $alg);
}
示例10: login
public static function login(Cart66Account $account)
{
$name = $account->firstName . ' ' . $account->lastName;
$email = $account->email;
$externalId = $account->id;
$organization = Cart66Setting::getValue('zendesk_organization');
$key = Cart66Setting::getValue('zendesk_token');
$prefix = Cart66Setting::getValue('zendesk_prefix');
if (Cart66Setting::getValue('zendesk_jwt')) {
$now = time();
$token = array("jti" => md5($now . rand()), "iat" => $now, "name" => $name, "email" => $email);
include_once CART66_PATH . "/pro/models/JWT.php";
$jwt = JWT::encode($token, $key);
// Redirect
header("Location: https://" . $prefix . ".zendesk.com/access/jwt?jwt=" . $jwt);
exit;
} else {
/* Build the message */
$ts = isset($_GET['timestamp']) ? $_GET['timestamp'] : time();
$message = $name . '|' . $email . '|' . $externalId . '|' . $organization . '|||' . $key . '|' . $ts;
$hash = MD5($message);
$remoteAuthUrl = 'http://' . $prefix . '.zendesk.com/access/remoteauth/';
$arguments = array('name' => $name, 'email' => $email, 'external_id' => $externalId, 'organization' => $organization, 'timestamp' => $ts, 'hash' => $hash);
$url = add_query_arg($arguments, $remoteAuthUrl);
header("Location: " . $url);
exit;
}
}
示例11: testValidateIdToken
/**
* Most of the logic for ID token validation is in AuthTest -
* this is just a general check to ensure we verify a valid
* id token if one exists.
*/
public function testValidateIdToken()
{
$this->checkToken();
$client = $this->getClient();
$token = $client->getAccessToken();
if ($client->isAccessTokenExpired()) {
$token = $client->fetchAccessTokenWithRefreshToken();
}
$segments = explode('.', $token['id_token']);
$this->assertEquals(3, count($segments));
// Extract the client ID in this case as it wont be set on the test client.
$data = json_decode(JWT::urlSafeB64Decode($segments[1]));
$verify = new Google_AccessToken_Verify();
$payload = $verify->verifyIdToken($token['id_token'], $data->aud);
$this->assertTrue(isset($payload['sub']));
$this->assertTrue(strlen($payload['sub']) > 0);
// TODO: Need to be smart about testing/disabling the
// caching for this test to make sense. Not sure how to do that
// at the moment.
$client = $this->getClient();
$data = json_decode(JWT::urlSafeB64Decode($segments[1]));
$verify = new Google_AccessToken_Verify();
$payload = $verify->verifyIdToken($token['id_token'], $data->aud);
$this->assertTrue(isset($payload['sub']));
$this->assertTrue(strlen($payload['sub']) > 0);
}
示例12: getToken
public static function getToken($user)
{
//@todo, check to see if we have a token stored for this user
$key = Settings::get('hash_salt');
$token = array("uid" => $user->id(), "mail" => $user->getEmail());
return \JWT::encode($token, $key);
}
示例13: 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);
global $secret;
global $decoded_token;
try {
$decoded_token = JWT::decode($token, base64_decode(strtr($secret, '-_', '+/')), false);
} catch (UnexpectedValueException $ex) {
header('HTTP/1.0 401 Unauthorized');
echo "Invalid token";
exit;
}
global $serverName;
// // validate that this token was made for us
if ($decoded_token->aud != $serverName) {
header('HTTP/1.0 401 Unauthorized');
echo "Invalid token";
exit;
}
}
示例14: 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;
}
示例15: loginset
function loginset($id)
{
$userinfo = $this->User_data->userinfo($id);
//读取用户数据
//多说账号
$token = array("short_name" => 'zustmanager', "user_key" => $userinfo['student_id'], "name" => $userinfo['username']);
$duoshuoToken = JWT::encode($token, '97c1b8a2ce9f394b034232572c086196');
$cookie = array('name' => 'duoshuo_token', 'value' => $duoshuoToken, 'expire' => '86500', 'domain' => '', 'path' => '/', 'secure' => FALSE);
$this->input->set_cookie($cookie);
$userinfo_session = array('username' => $userinfo['username'], 'student_id' => $userinfo['student_id'], 'head_img' => $userinfo['head_img'], 'major' => $userinfo['major'], 'classnum' => $userinfo['classnum'], 'email' => $userinfo['email'], 'qq' => $userinfo['qq']);
$this->session->set_userdata($userinfo_session);
//将用户数据写入session
$logindate = array('status' => "1", 'lastLoginTime' => date("Y-m-d H:i:s"));
$this->db->from('user')->where('student_id', $id)->update('user', $logindate);
//更新用户登陆时间
$log = array('student_id' => $userinfo['student_id'], 'username' => $userinfo['username'], 'events' => '登陆', 'time' => date("Y-m-d H:i:s"));
$this->db->insert('log', $log);
//记录事件 登陆
/* print_r($userinfo);//用户数据调出 调试用
echo "<hr>";
echo $this->session->userdata('username');
echo "<hr>";
echo "查询到此人";
echo date("Y-m-d H:i:s");*/
$cookie = array('name' => 'zust_login', 'value' => $userinfo['student_id'] . '&' . $userinfo['password'], 'expire' => '86500', 'domain' => '', 'path' => '/', 'secure' => FALSE);
$this->input->set_cookie($cookie);
redirect(base_url('user/profile'));
}