JWT 编码器服务定制
此扩展包自带一个内置的令牌编码器,基于 lcobucci/jwt 库。如果它不符合您的需求,您可以将其替换为您自己的编码器服务。这是一个基于 nixilla/php-jwt 库的编码器示例。
创建您自己的编码器
创建编码器类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
// src/App/Encoder/NixillaJWTEncoder.php
namespace App\Encoder;
use JWT\Authentication\JWT;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTEncodeFailureException;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException;
/**
* NixillaJWTEncoder
*
* @author Nicolas Cabot <n.cabot@lexik.fr>
*/
class NixillaJWTEncoder implements JWTEncoderInterface
{
private $key;
public function __construct(string $key = 'super_secret_key')
{
$this->key = $key;
}
/**
* {@inheritdoc}
*/
public function encode(array $data)
{
try {
return JWT::encode($data, $this->key);
}
catch (\Exception $e) {
throw new JWTEncodeFailureException(JWTEncodeFailureException::INVALID_CONFIG, 'An error occurred while trying to encode the JWT token.', $e);
}
}
/**
* {@inheritdoc}
*/
public function decode($token)
{
try {
return (array) JWT::decode($token, $this->key);
} catch (\Exception $e) {
throw new JWTDecodeFailureException(JWTDecodeFailureException::INVALID_TOKEN, 'Invalid JWT Token', $e);
}
}
}
这项工作,包括代码示例,是在 Creative Commons BY-SA 3.0 许可下获得许可的。