您现在的位置是:首页 > 博客日记 > Php Php

lcobucci/jwt —— 一个轻松生成jwt token的插件

2021-01-04 18:44:19 【Php】 人已围观

1.安装

  1. "lcobucci/jwt": "^3.4"版本
  2. php >= 5.6
  3. OpenSSL Extension
  4. // 安装
  5. $ composer require lcobucci/jwt

2. 一些参数说明

  1. iss issuer】签发人(可以是,发布者的url地址)
  2. sub subject】该JWT所面向的用户,用于处理特定应用,不是常用的字段
  3. aud audience】受众人(可以是客户端的url地址,用作验证是否是指定的人或者url
  4. exp expiration jwt销毁的时间;unix时间戳
  5. nbf not before jwt的使用时间不能早于该时间;unix时间戳
  6. iat issued at jwt的发布时间;unix 时间戳
  7. jti JWT ID jwt的唯一ID编号

3.简单封装

  1. <?php
  2. /**
  3. * jwt封装的一个简单的类
  4. */
  5. use Lcobucci\JWT\Configuration;
  6. use Lcobucci\JWT\Signer\Hmac\Sha256;
  7. use Lcobucci\JWT\Signer\Key\InMemory;
  8. use DateTimeImmutable;
  9. use Lcobucci\JWT\Token\Plain;
  10. use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
  11. use Lcobucci\JWT\Validation\Constraint\SignedWith;
  12. class Service
  13. {
  14. /**
  15. * 配置秘钥加密
  16. * @return Configuration
  17. */
  18. public static function getConfig()
  19. {
  20. $configuration = Configuration::forSymmetricSigner(
  21. // You may use any HMAC variations (256, 384, and 512)
  22. new Sha256(),
  23. // replace the value below with a key of your own!
  24. InMemory::base64Encoded('YWFhc0pOU0RLSkJITktKU0RiamhrMTJiM2Joa2ox')
  25. // You may also override the JOSE encoder/decoder if needed by providing extra arguments here
  26. );
  27. return $configuration;
  28. }
  29. /**
  30. * 签发令牌
  31. */
  32. public static function createToken()
  33. {
  34. $config = self::getConfig();
  35. assert($config instanceof Configuration);
  36. $now = new DateTimeImmutable();
  37. $token = $config->builder()
  38. // 签发人
  39. ->issuedBy('http://example.com')
  40. // 受众
  41. ->permittedFor('http://example.org')
  42. // JWT ID 编号 唯一标识
  43. ->identifiedBy('123')
  44. // 签发时间
  45. ->issuedAt($now)
  46. // 在1分钟后才可使用
  47. // ->canOnlyBeUsedAfter($now->modify('+1 minute'))
  48. // 过期时间1小时
  49. ->expiresAt($now->modify('+1 hour'))
  50. // 自定义uid 额外参数
  51. ->withClaim('uid', 1)
  52. // 自定义header 参数
  53. ->withHeader('foo', 'bar')
  54. // 生成token
  55. ->getToken($config->signer(), $config->signingKey());
  56. //result:
  57. //eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImZvbyI6ImJhciJ9.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLmNvbSIsImF1ZCI6Imh0dHA6XC9cL2V4YW1wbGUub3JnIiwianRpIjoiNGYxZzIzYTEyYWEiLCJpYXQiOjE2MDk0Mjk3MjMsIm5iZiI6MTYwOTQyOTc4MywiZXhwIjoxNjA5NDMzMzIzLCJ1aWQiOjF9.o4uLWzZjk-GJgrxgirypHhXKkMMUEeL7z7rmvmW9Mnw
  58. //base64 decode:
  59. //{"typ":"JWT","alg":"HS256","foo":"bar"}{"iss":"http:\/\/example.com","aud":"http:\/\/example.org","jti":"4f1g23a12aa","iat":1609429723,"nbf":1609429783,"exp":1609433323,"uid":1}[6cb`"*Gr0ńxoL
  60. return $token->toString();
  61. }
  62. /**
  63. * 解析令牌
  64. */
  65. public static function parseToken(string $token)
  66. {
  67. $config = self::getConfig();
  68. assert($config instanceof Configuration);
  69. $token = $config->parser()->parse('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImZvbyI6ImJhciJ9.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLmNvbSIsImF1ZCI6Imh0dHA6XC9cL2V4YW1wbGUub3JnIiwianRpIjoiNGYxZzIzYTEyYWEiLCJpYXQiOjE2MDk0Mjk3MjMsIm5iZiI6MTYwOTQyOTc4MywiZXhwIjoxNjA5NDMzMzIzLCJ1aWQiOjF9.o4uLWzZjk-GJgrxgirypHhXKkMMUEeL7z7rmvmW9Mnw'
  70. );
  71. assert($token instanceof Plain);
  72. dump($token->headers()); // Retrieves the token headers
  73. dump($token->claims()); // Retrieves the token claims
  74. }
  75. /**
  76. * 验证令牌
  77. */
  78. public static function validationToken(string $token)
  79. {
  80. $config = self::getConfig();
  81. assert($config instanceof Configuration);
  82. $token = $config->parser()->parse($token);
  83. assert($token instanceof Plain);
  84. //Lcobucci\JWT\Validation\Constraint\IdentifiedBy: 验证jwt id是否匹配
  85. //Lcobucci\JWT\Validation\Constraint\IssuedBy: 验证签发人参数是否匹配
  86. //Lcobucci\JWT\Validation\Constraint\PermittedFor: 验证受众人参数是否匹配
  87. //Lcobucci\JWT\Validation\Constraint\RelatedTo: 验证自定义cliam参数是否匹配
  88. //Lcobucci\JWT\Validation\Constraint\SignedWith: 验证令牌是否已使用预期的签名者和密钥签名
  89. //Lcobucci\JWT\Validation\Constraint\StrictValidAt: ::验证存在及其有效性的权利要求中的iat,nbf和exp(支持余地配置
  90. //Lcobucci\JWT\Validation\Constraint\LooseValidAt: 验证的权利要求iat,nbf和exp,当存在时(支持余地配置)
  91. //验证jwt id是否匹配
  92. $validate_jwt_id = new \Lcobucci\JWT\Validation\Constraint\IdentifiedBy('123');
  93. $config->setValidationConstraints($validate_jwt_id);
  94. //验证签发人url是否正确
  95. $validate_issued = new \Lcobucci\JWT\Validation\Constraint\IssuedBy('http://example.com');
  96. $config->setValidationConstraints($validate_issued);
  97. //验证客户端url是否匹配
  98. $validate_aud = new \Lcobucci\JWT\Validation\Constraint\PermittedFor('http://example.org');
  99. $config->setValidationConstraints($validate_aud);
  100. $constraints = $config->validationConstraints();
  101. try {
  102. $config->validator()->assert($token, ...$constraints);
  103. } catch (RequiredConstraintsViolated $e) {
  104. // list of constraints violation exceptions:
  105. var_dump($e->violations());
  106. }
  107. }
  108. }

4.使用

  1. //生成token
  2. Service::createToken();
  3. //解析token
  4. Service::parseToken($token);
  5. //验证token
  6. Service::validationToken($token);


关注TinyMeng博客,更多精彩分享,敬请期待!
 

很赞哦! ()