本文整理汇总了PHP中JWT类的典型用法代码示例。如果您正苦于以下问题:PHP JWT类的具体用法?PHP JWT怎么用?PHP JWT使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JWT类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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: 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;
}
开发者ID:DaniloEpic,项目名称:slast,代码行数:14,代码来源:JWT.php
示例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');
}
开发者ID:nightstomp,项目名称:php-jwt,代码行数:7,代码来源:JWTTest.php
示例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);
}
开发者ID:durbs182,项目名称:phpauth,代码行数:33,代码来源:validatetoken.php
示例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;
}
}
开发者ID:arielcessario,项目名称:angular-tests,代码行数:31,代码来源:utils.php
示例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' => '')));
}
}
}
开发者ID:eunovate,项目名称:AMS,代码行数:32,代码来源:Login_ctrl.php
示例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");
}
开发者ID:jorgecabane93,项目名称:eMarkingWeb,代码行数:56,代码来源:FirebaseToken.php
示例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);
}
开发者ID:samjarrett,项目名称:jwt-bundle,代码行数:16,代码来源:Manager.php
示例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;
}
}
开发者ID:rbredow,项目名称:allyzabbacart,代码行数:28,代码来源:ZendeskRemoteAuth.php
示例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);
}
开发者ID:rahul9878,项目名称:google-api-php-client,代码行数:31,代码来源:VerifyTest.php
示例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);
}
开发者ID:voryx,项目名称:ThruwayDrupal,代码行数:7,代码来源:Utils.php
示例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;
}
}
开发者ID:arielcessario,项目名称:bayres-new,代码行数:30,代码来源:config.php
示例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;
}
开发者ID:rahul9878,项目名称:google-api-php-client,代码行数:43,代码来源:Verify.php
示例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'));
}
开发者ID:hemisu,项目名称:zustmanager,代码行数:28,代码来源:user_data.php
示例16: encode
/**
* $scopes: should be an array with the follow structure:
*
* 'scope' => [
* 'actions' => ['action1', 'action2']
* ],
* 'scope2' => [
* 'actions' => ['action1', 'action2']
* ]
*/
public static function encode($client_id, $client_secret, $scopes = null, $custom_payload = null, $lifetime = 36000) {
$time = time();
$payload = array(
"iat" => $time,
);
if ($scopes) {
$payload["scopes"] = $scopes;
}
if ($scopes) {
$custom_payload = array_merge($custom_payload, $payload);
}
$jti = md5(json_encode($payload));
$payload['jti'] = $jti;
$payload["exp"] = $time + $lifetime;
$payload["aud"] = $client_id;
$secret = base64_decode(strtr($client_secret, '-_', '+/'));
$jwt = \JWT::encode($payload, $secret);
return $jwt;
}
开发者ID:pombredanne,项目名称:ArcherSys,代码行数:40,代码来源:Auth0JWT.php
示例17: check
/**
* @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;
}
开发者ID:schalkt,项目名称:schauth,代码行数:34,代码来源:Token.php
示例18: 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
示例19: login
public function login()
{
$res = new stdClass();
$res->success = FALSE;
$data = new stdClass();
parse_str(file_get_contents("php://input"), $data);
$data = (object) $data;
$this->load->model('sp_model');
$where = 'userName="' . $data->username . '"';
$arr = $this->sp_model->where('jwt_user', $where, 'id', 'asc');
if (count($arr) == 1) {
if (Password::validate_password($data->password, $arr[0]->password)) {
$res->success = true;
$token = array();
$token['id'] = $arr[0]->id;
$res->access_token = JWT::encode($token, $this->config->item('jwt_key'));
$res->id = $arr[0]->id;
} else {
$res->error = 'Invalid user name or password.';
http_response_code(401);
}
} else {
$res->error = 'Invalid user name or password.';
http_response_code(401);
}
$this->load->view('json', array('output' => $res));
}
开发者ID:JUkhan,项目名称:jwt_php,代码行数:27,代码来源:Account.php
示例20: 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);
}
$this->_validateData($funcName, $data, isset($claims['admin']) && $claims["admin"] == true);
$claims["d"] = $data;
$claims["v"] = $this->version;
$claims["iat"] = time();
$token = JWT::encode($claims, $this->secret, "HS256");
if (strlen($token) > 1024) {
throw new Exception($funcName . ": generated token is too large. Token cannot be larger than 1024 bytes.");
}
return $token;
}
开发者ID:kellbot,项目名称:nestgraph,代码行数:61,代码来源:FirebaseToken.php
注:本文中的JWT类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论