目录一、什么是Jwt1、简介2、JWT的组成3、JWT验证流程和特点二、相关问题三、PHP实现1、引入依赖2、功能实现3、封装工具类如下一、什么是JWT 1、简介 JWT(JSON
JWT(JSON WEB Token)是为了在网络应用环境间传递声明而执行的一种基于jsON的开放标准。
简单的说,JWT就是一种Token的编码算法,服务器端负责根据一个密码和算法生成Token,然后发给客户端,客户端只负责后面每次请求都在Http header里面带上这个Token,服务器负责验证这个Token是不是合法的,有没有过期等,并可以解析出subject和claim里面的数据。
第一部分为头部(header),第二部分我们称其为载荷(payload),第三部分是签证(signature)。【中间用 . 分隔】
一个标准的JWT生成的token格式如下:
eyJ0eXAioiJKV1QiLCJhbGCiOiJIUzI1NiIsImp0aSI6IjRmMWcyM2ExMmFhMTEifQ.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLmNvbSIsImF1ZCI6Imh0dHA6XC9cL2V4YW1wbGUub3JnIiwianRpIjoiNGYxZzIzYTEyYWExMSIsImlhdCI6MTY0MDE3MTA1MywibmJmIjoxNjQwMTcxMDU0LCJleHAiOjE2NDAxNzQ2NTMsInVpZCI6MjAsInVzZXJuYW1lIjoiTWFrZSJ9.bysUwNIyhqqEyL0JecSHdplSTfE6G6zuCsrAn6eyrQM
使用https://jwt.io/这个网站对JWT Token进行解析的结果如下
验证流程:
① 在头部信息中声明加密算法和常量, 然后把header使用json转化为字符串
② 在载荷中声明用户信息,同时还有一些其他的内容;再次使用json 把载荷部分进行转化,转化为字符串
③ 使用在header中声明的加密算法和每个项目随机生成的secret来进行加密, 把第一步分字符串和第二部分的字符串进行加密, 生成新的字符串。词字符串是独一无二的。
④ 解密的时候,只要客户端带着JWT来发起请求,服务端就直接使用secret进行解密。
特点:
① 三部分组成,每一部分都进行字符串的转化
② 解密的时候没有使用数据库,仅仅使用的是secret进行解密
③ JWT的secret千万不能泄密!
④ 不依赖数据库,而是直接根据token取出保存的用户信息,以及对token可用性校验,校验方式更加简单便捷化,单点登录更为简单。
不应该这样做,无状态的jwt变成了有状态了,背离了JWT通过算法验证的初心。
退出登录, 只要客户端端把Token丢弃就可以了,服务器端不需要废弃Token。
服务器端提供刷新Token的接口, 客户端负责按一定的逻辑刷新服务器Token。
composer require lcobucci/jwt 3.*
<?php
namespace App\Utils;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\HMac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Token\Plain;
use Lcobucci\JWT\Validation\Constraint\IdentifiedBy;
use Lcobucci\JWT\Validation\Constraint\IssuedBy;
use Lcobucci\JWT\Validation\Constraint\PermittedFor;
use Lcobucci\JWT\ValidationData;
class JwtUtil
{
// jwt GitHub: https://github.com/lcobucci/jwt https://jwt.io/
protected $issuer = "http://example.com";
protected $audience = "http://example.org";
protected $id = "4f1g23a12aa11";
// key 是绝对不允许泄露的
protected static $key = "8swQsm1Xb0TA0Jw5ASPwClKVZPoTyS7GvhtaW0MxzKEihs1BNpcS2q3FYMJ11111";
public function getToken()
{
$time = time();
$config = self::getConfig();
assert($config instanceof Configuration);
// 签发token, 设置签发人、接收人、唯一标识、签发时间、立即生效、过期时间、用户id、用户username、签名
$token = $config->builder()
->issuedBy($this->issuer) // Configures the issuer (iss claim)
->permittedFor($this->audience) // Configures the audience (aud claim)
->identifiedBy($this->id, true) // Configures the id (jti claim), replicating as a header item
->issuedAt($time) // Configures the time that the token was issue (iat claim)
->canOnlyBeUsedAfter($time + 1) // Configures the time that the token can be used (nbf claim) 签发x秒钟后生效
->expiresAt($time + 3600) // Configures the expiration time of the token (exp claim)
->withClaim('uid', 20) // Configures a new claim, called "uid"
->withClaim('username', "Make") // Configures a new claim, called "uid"
->getToken($config->signer(), $config->signingKey()); // Retrieves the generated token
return $token->toString();
}
public function verifyToken_bak($token)
{
try {
$config = self::getConfig();
assert($config instanceof Configuration);
$token = $config->parser()->parse($token);
assert($token instanceof Plain);
//Lcobucci\JWT\Validation\Constraint\IdentifiedBy: 验证jwt id是否匹配
//Lcobucci\JWT\Validation\Constraint\IssuedBy: 验证签发人参数是否匹配
//Lcobucci\JWT\Validation\Constraint\PermittedFor: 验证受众人参数是否匹配
//Lcobucci\JWT\Validation\Constraint\RelatedTo: 验证自定义cliam参数是否匹配
//Lcobucci\JWT\Validation\Constraint\SignedWith: 验证令牌是否已使用预期的签名者和密钥签名
//Lcobucci\JWT\Validation\Constraint\StrictValidAt: ::验证存在及其有效性的权利要求中的iat,nbf和exp(支持余地配置
//Lcobucci\JWT\Validation\Constraint\LooseValidAt: 验证的权利要求iat,nbf和exp,当存在时(支持余地配置)
//验证jwt id是否匹配
$validate_jwt_id = new IdentifiedBy($this->id);
//验证签发人url是否正确
$validate_issued = new IssuedBy($this->issuer);
//验证客户端url是否匹配
$validate_aud = new PermittedFor($this->audience);
$config->setValidationConstraints($validate_jwt_id, $validate_issued, $validate_aud);
$constraints = $config->validationConstraints();
if (!$config->validator()->validate($token, ...$constraints)) {
die("token invalid!");
}
} catch (\Exception $e) {
die("error:" . $e->getMessage());
}
$jwtInfo = $token->claims(); // 这是jwt token中存储的所有信息
return $jwtInfo->get("uid"); // 获取uid
}
public static function getConfig()
{
$configuration = Configuration::forSymmetricSigner(
// You may use any HMAC variations (256, 384, and 512)
new Sha256(),
// replace the value below with a key of your own!
InMemory::base64Encoded(self::$key)
// You may also override the JOSE encoder/decoder if needed by providing extra arguments here
);
return $configuration;
}
public function verifyToken($token)
{
$token = (new Parser())->parse((string)$token);
//验证token
$data = new ValidationData();
$data->setIssuer($this->issuer);//验证的签发人
$data->setAudience($this->audience);//验证的接收人
$data->setId($this->id);//验证token标识
if (!$token->validate($data)) {
//token验证失败
die("token invalid!");
}
$jwtInfo = $token->claims(); // 这是jwt token中存储的所有信息
return $jwtInfo->get("uid"); // 获取uid
}
}
以上就是基于PHP实现JWT登录鉴权的示例代码的详细内容,更多关于PHP JWT登录鉴权的资料请关注编程网其它相关文章!
--结束END--
本文标题: 基于PHP实现JWT登录鉴权的示例代码
本文链接: https://www.lsjlt.com/news/146127.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0