JSON Web Token(JWT)是目前最流行的跨域身份验证解决方案,下面我自己封装了一个PHP的Jwt类,直接复制即可使用,无需composer安装包;

常规的身份验证流程为:

该方案的最大的短板在于如果要实现多站用户登录状态共享则需要一个统一的session数据库库来保存会话数据实现共享,这样负载均衡下的每个服务器才可以正确的验证用户身份。如果实现了session共享依然有单点风险,session共享库一旦挂掉,影响多个站点。

Jwt是解决这种问题的代表,JWT方式将用户状态分散到了客户端中,基于token的鉴权机制类似于http协议也是无状态的,它不需要在服务端去保留用户的认证信息或者会话信息。这就意味着基于token认证机制的应用不需要去考虑用户在哪一台服务器登录了,这就为应用的扩展提供了便利.

Jwt验证流程为:用户使用用户名密码来请求服务器

服务器进行验证用户的信息

服务器通过验证发送给用户一个token

客户端存储token,并在每次请求时附送上这个token值

服务端验证token值,并返回数据这个token必须要在每次请求时传递给服务端,它应该保存在请求头里, 另外,服务端要支持 CORS(跨来源资源共享)策略,一般我们在服务端这么做就可以了 Access-Control-Allow-Origin: *。

JWT的结构加密后jwt信息如下所示,是由.分割的三部分组成,分别为Header、Payload、Signature

JWT 的组成Head -主要包含两个部分,alg指加密类型,可选值为HS256、RSA等等,typ=JWT为固定值,表示token的类型

具体的请看官方文档的介绍。

PHP的实现代码:<?php

/**

* User: tangyijun

* Date: 2019-07-31

* Time: 11:11

*/

namespace Toutiao\Services;

use \DomainException;

use \InvalidArgumentException;

use \UnexpectedValueException;

use \DateTime;

class JWT

{

/**

* When checking nbf, iat or expiration times,

* we want to provide some extra leeway time to

* account for clock skew.

*/

public static $leeway = 0;

/**

* Allow the current timestamp to be specified.

* Useful for fixing a value within unit testing.

*

* Will default to PHP time() value if null.

*/

public static $timestamp = null;

public static $supported_algs = array(

'HS256' => array('hash_hmac', 'SHA256'),

'HS512' => array('hash_hmac', 'SHA512'),

'HS384' => array('hash_hmac', 'SHA384'),

'RS256' => array('openssl', 'SHA256'),

'RS384' => array('openssl', 'SHA384'),

'RS512' => array('openssl', 'SHA512'),

);

/**

* Decodes a JWT string into a PHP object.

*

* @param string $jwt The JWT

* @param string|array $key The key, or map of keys.

* If the algorithm used is asymmetric, this is the public key

* @param array $allowed_algs List of supported verification algorithms

* Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'

*

* @return object The JWT's payload as a PHP object

*

* @throws UnexpectedValueException Provided JWT was invalid

* @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed

* @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'

* @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'

* @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim

*

* @uses jsonDecode

* @uses urlsafeB64Decode

*/

public static function decode($jwt, $key, array $allowed_algs = array())

{

$timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;

if (empty($key)) {

throw new InvalidArgumentException('Key may not be empty');

}

$tks = explode('.', $jwt);

if (count($tks) != 3) {

throw new UnexpectedValueException('Wrong number of segments');

}

list($headb64, $bodyb64, $cryptob64) = $tks;

if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) {

throw new UnexpectedValueException('Invalid header encoding');

}

if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) {

throw new UnexpectedValueException('Invalid claims encoding');

}

if (false === ($sig = static::urlsafeB64Decode($cryptob64))) {

throw new UnexpectedValueException('Invalid signature encoding');

}

if (empty($header->alg)) {

throw new UnexpectedValueException('Empty algorithm');

}

if (empty(static::$supported_algs[$header->alg])) {

throw new UnexpectedValueException('Algorithm not supported');

}

if (!in_array($header->alg, $allowed_algs)) {

throw new UnexpectedValueException('Algorithm not allowed');

}

if (is_array($key) || $key instanceof \ArrayAccess) {

if (isset($header->kid)) {

if (!isset($key[$header->kid])) {

throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');

}

$key = $key[$header->kid];

} else {

throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');

}

}

// Check the signature

if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {

throw new SignatureInvalidException('Signature verification failed');

}

// Check if the nbf if it is defined. This is the time that the

// token can actually be used. If it's not yet that time, abort.

if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {

throw new BeforeValidException(

'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)

);

}

// Check that this token has been created before 'now'. This prevents

// using tokens that have been created for later use (and haven't

// correctly used the nbf claim).

if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {

throw new BeforeValidException(

'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)

);

}

// Check if this token has expired.

if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {

throw new ExpiredException('Expired token');

}

return $payload;

}

/**

* Converts and signs a PHP object or array into a JWT string.

*

* @param object|array $payload PHP object or array

* @param string $key The secret key.

* If the algorithm used is asymmetric, this is the private key

* @param string $alg The signing algorithm.

* Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'

* @param mixed $keyId

* @param array $head An array with header elements to attach

*

* @return string A signed JWT

*

* @uses jsonEncode

* @uses urlsafeB64Encode

*/

public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null)

{

$header = array('typ' => 'JWT', 'alg' => $alg);

if ($keyId !== null) {

$header['kid'] = $keyId;

}

if ( isset($head) && is_array($head) ) {

$header = array_merge($head, $header);

}

$segments = array();

$segments[] = static::urlsafeB64Encode(static::jsonEncode($header));

$segments[] = static::urlsafeB64Encode(static::jsonEncode($payload));

$signing_input = implode('.', $segments);

$signature = static::sign($signing_input, $key, $alg);

$segments[] = static::urlsafeB64Encode($signature);

return implode('.', $segments);

}

/**

* Sign a string with a given key and algorithm.

*

* @param string $msg The message to sign

* @param string|resource $key The secret key

* @param string $alg The signing algorithm.

* Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'

*

* @return string An encrypted message

*

* @throws DomainException Unsupported algorithm was specified

*/

public static function sign($msg, $key, $alg = 'HS256')

{

if (empty(static::$supported_algs[$alg])) {

throw new DomainException('Algorithm not supported');

}

list($function, $algorithm) = static::$supported_algs[$alg];

switch($function) {

case 'hash_hmac':

return hash_hmac($algorithm, $msg, $key, true);

case 'openssl':

$signature = '';

$success = openssl_sign($msg, $signature, $key, $algorithm);

if (!$success) {

throw new DomainException("OpenSSL unable to sign data");

} else {

return $signature;

}

}

}

/**

* Verify a signature with the message, key and method. Not all methods

* are symmetric, so we must have a separate verify and sign method.

*

* @param string $msg The original message (header and body)

* @param string $signature The original signature

* @param string|resource $key For HS*, a string key works. for RS*, must be a resource of an openssl public key

* @param string $alg The algorithm

*

* @return bool

*

* @throws DomainException Invalid Algorithm or OpenSSL failure

*/

private static function verify($msg, $signature, $key, $alg)

{

if (empty(static::$supported_algs[$alg])) {

throw new DomainException('Algorithm not supported');

}

list($function, $algorithm) = static::$supported_algs[$alg];

switch($function) {

case 'openssl':

$success = openssl_verify($msg, $signature, $key, $algorithm);

if ($success === 1) {

return true;

} elseif ($success === 0) {

return false;

}

// returns 1 on success, 0 on failure, -1 on error.

throw new DomainException(

'OpenSSL error: ' . openssl_error_string()

);

case 'hash_hmac':

default:

$hash = hash_hmac($algorithm, $msg, $key, true);

if (function_exists('hash_equals')) {

return hash_equals($signature, $hash);

}

$len = min(static::safeStrlen($signature), static::safeStrlen($hash));

$status = 0;

for ($i = 0; $i < $len; $i++) {

$status |= (ord($signature[$i]) ^ ord($hash[$i]));

}

$status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash));

return ($status === 0);

}

}

/**

* Decode a JSON string into a PHP object.

*

* @param string $input JSON string

*

* @return object Object representation of JSON string

*

* @throws DomainException Provided string was invalid JSON

*/

public static function jsonDecode($input)

{

if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {

/** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you

* to specify that large ints (like Steam Transaction IDs) should be treated as

* strings, rather than the PHP default behaviour of converting them to floats.

*/

$obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);

} else {

/** Not all servers will support that, however, so for older versions we must

* manually detect large ints in the JSON string and quote them (thus converting

*them to strings) before decoding, hence the preg_replace() call.

*/

$max_int_length = strlen((string) PHP_INT_MAX) - 1;

$json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);

$obj = json_decode($json_without_bigints);

}

if (function_exists('json_last_error') && $errno = json_last_error()) {

static::handleJsonError($errno);

} elseif ($obj === null && $input !== 'null') {

throw new DomainException('Null result with non-null input');

}

return $obj;

}

/**

* Encode a PHP object into a JSON string.

*

* @param object|array $input A PHP object or array

*

* @return string JSON representation of the PHP object or array

*

* @throws DomainException Provided object could not be encoded to valid JSON

*/

public static function jsonEncode($input)

{

$json = json_encode($input);

if (function_exists('json_last_error') && $errno = json_last_error()) {

static::handleJsonError($errno);

} elseif ($json === 'null' && $input !== null) {

throw new DomainException('Null result with non-null input');

}

return $json;

}

/**

* Decode a string with URL-safe Base64.

*

* @param string $input A Base64 encoded string

*

* @return string A decoded string

*/

public static function urlsafeB64Decode($input)

{

$remainder = strlen($input) % 4;

if ($remainder) {

$padlen = 4 - $remainder;

$input .= str_repeat('=', $padlen);

}

return base64_decode(strtr($input, '-_', '+/'));

}

/**

* Encode a string with URL-safe Base64.

*

* @param string $input The string you want encoded

*

* @return string The base64 encode of what you passed in

*/

public static function urlsafeB64Encode($input)

{

return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));

}

/**

* Helper method to create a JSON error.

*

* @param int $errno An error number from json_last_error()

*

* @return void

*/

private static function handleJsonError($errno)

{

$messages = array(

JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',

JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',

JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',

JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',

JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3

);

throw new DomainException(

isset($messages[$errno])

? $messages[$errno]

: 'Unknown JSON error: ' . $errno

);

}

/**

* Get the number of bytes in cryptographic strings.

*

* @param string

*

* @return int

*/

private static function safeStrlen($str)

{

if (function_exists('mb_strlen')) {

return mb_strlen($str, '8bit');

}

return strlen($str);

}

}

PHP JWT 的生成加密串用法(上面的类请自己根据项目修改命名空间,use 不需要更改,引用系统类)$data = [

'appKey' => 'fasfsfs', //登录凭证,

'uid' => 222222,

];

$app_secret = 'fsasosaofsofsofss';

$sign = \Toutiao\Services\JWT::encode($data,$app_secret);

优点因为json的通用性,所以JWT是可以进行跨语言支持的,像JAVA,JavaScript,NodeJS,PHP等很多语言都可以使用。

因为有了payload部分,所以JWT可以在自身存储一些其他业务逻辑所必要的非敏感信息。

便于传输,jwt的构成非常简单,字节占用很小,所以它是非常便于传输的。

它不需要在服务端保存会话信息, 所以它易于应用的扩展

安全相关不应该在jwt的payload部分存放敏感信息,因为该部分是客户端可解密的部分。

保护好secret私钥,该私钥非常重要。

如果可以,请使用https协议

php后台跨域token,JSON Web Token(JWT)目前最流行的跨域身份验证解决方案(PHP)类...相关推荐

  1. (json web token)JWT攻击

    前记 最近国赛+校赛遇到两次json web token的题,发现自己做的并不算顺畅,于是有了这篇学习文章. 为什么要使用Json Web Token Json Web Token简称jwt 顾名思义 ...

  2. JSON Web Token(缩写 JWT) 目前最流行、最常见的跨域认证解决方案,前端后端都需要会使用的东西

    JSON Web Token(缩写 JWT)是目前最流行,也是最常见的跨域认证解决方案.无论是咱们后端小伙伴,还是前端小伙伴对都是需要了解. 本文介绍它的原理.使用场景.用法. 关于封面:这个冬天你过 ...

  3. JSON Web Token(缩写 JWT) 目前最流行的跨域认证解决方案

    JSON Web Token(缩写 JWT) 目前最流行的跨域认证解决方案 参考文章: (1)JSON Web Token(缩写 JWT) 目前最流行的跨域认证解决方案 (2)https://www. ...

  4. 理解JWT(JSON Web Token)认证及python实践

    最近想做个小程序,需要用到授权认证流程.以前项目都是用的 OAuth2 认证,但是Sanic 使用OAuth2 不太方便,就想试一下 JWT 的认证方式. 这一篇主要内容是 JWT 的认证原理,以及p ...

  5. JWT(JSON Web Token)的基本原理

    JWT(JSON Web Token)的基本原理 JSON Web Token(缩写 JWT)是目前最流行的跨域认证解决方案 一.跨域认证的问题 1.用户向服务器发送用户名和密码. 2.服务器验证通过 ...

  6. 认识JWT(JSON WEB TOKEN)

    1. JSON Web Token是什么 JSON Web Token (JWT)是一个开放标准(RFC 7519),它定义了一种紧凑的.自包含的方式,用于作为JSON对象在各方之间安全地传输信息.该 ...

  7. SpringBoot 2.x 使用 JWT(JSON Web Token)

    一.跨域认证遇到的问题 由于多终端的出现,很多的站点通过 web api restful 的形式对外提供服务,采用了前后端分离模式进行开发,因而在身份验证的方式上可能与传统的基于 cookie 的 S ...

  8. JWT(JSON Web Token)简介

    文章目录 一.JWT是什么 二.跨域认证问题 三.JWT原理 四.JWT数据结构 1.header(头部) 2.Payload(负载) 3.Signature 五.JWT是如何工作的 一.JWT是什么 ...

  9. 什么时候你应该用JSON Web Token

    下列场景中使用JSON Web Token是很有用的: Authorization (授权) : 这是使用JWT的最常见场景.一旦用户登录,后续每个请求都将包含JWT,允许用户访问该令牌允许的路由.服 ...

最新文章

  1. 注解--python库--matplotlib
  2. 【Python之路】第二篇--初识Python
  3. LSTM终获「正名」,IEEE 2021神经网络先驱奖授予LSTM提出者Sepp Hochreiter
  4. 【错误记录】编译安卓项目报错 ( AndroidMavenPlugin 错误 )
  5. 今天JKS挂了,记录一下手动发云机上流程
  6. boost::multiprecision模块cpp_bin_float相关的测试程序
  7. Leet Code OJ 344. Reverse String [Difficulty: Easy]
  8. html元素data属性设置变量,HTML5 自定义属性 data-* 和 jQuery.data 详解
  9. windows下使用MinGW+msys编译ffmpeg
  10. oracle实施伙伴,甲骨文推出Oracle合作伙伴网络专属计划
  11. 国科大.模式识别与机器学习.期末复习笔记手稿+复习大纲
  12. HTML 合并单元格(学生成绩管理表格)
  13. 计算机变网络限速,电脑网速太慢?先别着急找运营商,修改这个限制瞬间变流畅...
  14. 阿尔伯塔大学计算机专业世界排名,加拿大学生最满意的TOP20大学排名
  15. 维美儿 名画背后的故事 《戴珍珠耳环的少女》
  16. chrome浏览器安全检查_为您的Chrome浏览器检查皮肤
  17. [Python从零到壹] 十五.文本挖掘之数据预处理、Jieba工具和文本聚类万字详解
  18. MySQL数据库5.5.25a版本下载与安装
  19. 你应该看得懂的RecyclerView嵌套
  20. (精简理解)DPDK的无锁环形队列Ring

热门文章

  1. java模仿微博代码_杨老师课堂_Java核心技术下之控制台模拟微博用户注册案例
  2. [转] alpha、beta、rc各版本区别
  3. 帷幄匠心 c++ qt岗位,一二三四面 2个半小时
  4. show和shown区别
  5. 我的阿里云盘资源搜索引擎首次试运行
  6. 1.大数据存储选型——何时用hbase
  7. PXE+Kickstart无人值守安装系统
  8. 利用Excel批量修改图片名称
  9. 用python批量修改图片名称!超级简单
  10. 使用自然语言处理来检测电子邮件中的垃圾邮件