记一次jwt挖laravel底层过程
前些天不是自己在laravel里面安装jwt嘛,流程是前台登录获取token,然后将token放到header里面过来用中间件验证,但是,我尝试了修改下传过来的token给我报错这个

这个报错很明显是语法报错,追踪了下
// 检测用户的登录状态,如果正常则通过
if($user = $this->auth->parseToken()->authenticate()){
AuthUser::setInfo($user);
return $next($request);
}
跟到authenticate()方法
public function authenticate()
{
$id = $this->getPayload()->get('sub');
if (! $this->auth->byId($id)) {
return false;
}
return $this->user();
}
跟到getPayload()方法
public function getPayload()
{
$this->requireToken();
return $this->manager->decode($this->token);
}
跟到decode()方法
public function decode(Token $token, $checkBlacklist = true)
{
$payloadArray = $this->provider->decode($token->get());
$payload = $this->payloadFactory
->setRefreshFlow($this->refreshFlow)
->customClaims($payloadArray)
->make();
if ($checkBlacklist && $this->blacklistEnabled && $this->blacklist->has($payload)) {
throw new TokenBlacklistedException('The token has been blacklisted');
}
return $payload;
}
跟到decode()方法
public function decode($token);
跟不下去了😏
最后还是全局搜索了报错短语,找到
public function decode($token)
{
try {
$jwt = $this->parser->parse($token);
} catch (Exception $e) {
throw new TokenInvalidException('Could not decode token: '.$e->getMessage(), $e->getCode(), $e);
}
if (! $jwt->verify($this->signer, $this->getVerificationKey())) {
throw new TokenInvalidException('Token Signature could not be verified.');
}
return (new Collection($jwt->getClaims()))->map(function ($claim) {
return is_object($claim) ? $claim->getValue() : $claim;
})->toArray();
}
跟着->parse($token)找到
public function parse($jwt)
{
$data = $this->splitJwt($jwt);
$header = $this->parseHeader($data[0]);
$claims = $this->parseClaims($data[1]);
$signature = $this->parseSignature($header, $data[2]);
foreach ($claims as $name => $value) {
if (isset($header[$name])) {
$header[$name] = $value;
}
}
if ($signature === null) {
unset($data[2]);
}
return new Token($header, $claims, $signature, $data);
}
跟着-$this->parseHeader($data[0])找到,找到重点来了!
protected function parseHeader($data)
{
$header = (array) $this->decoder->jsonDecode($this->decoder->base64UrlDecode($data));
if (isset($header['enc'])) {
throw new InvalidArgumentException('Encryption is not supported yet');
}
return $header;
}
跟着$this->decoder->base64UrlDecode($data)发现返回到竟然是乱码字符串,下图

然后我把2去了发现返回json字符串,下图

所以再这个进入到
跟着->jsonDecode(
public function jsonDecode($json)
{
// 下面这个json_decode就会报错了
$data = json_decode($json);
if (json_last_error() != JSON_ERROR_NONE) {
throw new RuntimeException('Error while decoding to JSON: ' . json_last_error_msg());
}
return $data;
}
总结: jwt测试不能随意到改下token就测了,这样会报错,也不能换成其他项目生成到toekn来测试,这会报系统异常Token Signature could not be verified这个意思是“无法验证令牌签名
”,所以当一个正常当token过来就算是过期了,我这都会返回401的,也会给刷新token,所以按照流程规范走就行。🙃

浙公网安备 33010602011771号