Browse Source

修改jwt服务

master
xyiege 1 year ago
parent
commit
0d7a82ce82
  1. 32
      app/api/controller/Index.php
  2. 20
      app/api/service/JWTService.php

32
app/api/controller/Index.php

@ -5,6 +5,13 @@ namespace app\api\controller;
use app\BaseController;
use app\Request;
// for jwt
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Token;
class Index extends BaseController
{
//
@ -39,4 +46,29 @@ class Index extends BaseController
}
return $salt;
}
public function test(){
// return time();
// throwError('密码错误');
$claims=[
"id" => 1,
"nick_name" => 'zhangsan'
];
$signer = new Sha256();
$key = InMemory::plainText(config('jwt.secret'));
// 设置发行时间和过期时间
$now = time();
$token = $builder
->issuedAt($now) // iat: 发行时间
->expiresAt($now + config('jwt.token_ttl')) // exp: 过期时间
->withClaim('iss', 'xtt') // iss: 发行人
->withClaim('sub', 'xtoken') // sub: 主题
->withClaim('aud', 'ttc'); // aud: 受众
foreach ($claims as $key => $value) {
$token = $token->withClaim($key, $value);
}
return (string) $token->sign($signer, $key);
}
}

20
app/api/service/JWTService.php

@ -1,6 +1,7 @@
<?php
namespace app\api\service;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
@ -20,13 +21,26 @@ class JWTService
$signer = new Sha256();
$key = InMemory::plainText($this->secret);
$token = (new Builder())->issuedNow()->canOnlyBeUsedAfter(0)->expiresAt(time() + config('jwt.token_ttl'));
$builder = new Builder();
// 设置发行时间和过期时间
$now = time();
$token = $builder
->issuedAt($now) // iat: 发行时间
->expiresAt($now + config('jwt.token_ttl')) // exp: 过期时间
->withClaim('iss', 'your_issuer') // iss: 发行人
->withClaim('sub', 'your_subject') // sub: 主题
->withClaim('aud', 'your_audience'); // aud: 受众
// 添加自定义 Claims
foreach ($claims as $key => $value) {
$token = $token->withClaim($key, $value);
}
return (string) $token->sign($signer, $key);
// 构建并签名 Token
$signedToken = $token->sign($signer, $key);
return (string) $signedToken;
}
public function verifyToken(string $token): array
@ -39,7 +53,7 @@ class JWTService
return $token->getClaims();
}
} catch (\Exception $e) {
// Handle exception
// 处理异常
}
return [];

Loading…
Cancel
Save