【问题标题】:JWT Signature verification failed , java to phpJWT 签名验证失败,java 到 php
【发布时间】:2016-12-27 14:18:35
【问题描述】:
【问题讨论】:
标签:
java
php
json
web
jwt
【解决方案1】:
是格式转换问题。 jjwt 需要使用 base64 编码的密钥,而 php-jwt 使用纯字符串
Jjwt JwtBuilder
JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey);
Php-jwt JWT
/**
* Decodes a JWT string into a PHP object.
*
* @param string $jwt The JWT
* @param string|array $key The key, or map of keys.
* If the algorithm used is asymmetric, this is the public key
public static function decode($jwt, $key, $allowed_algs = array()
在调用JwtBuilder.signWith之前将您的密钥编码为base64
builder.signWith(SignatureAlgorithm.HS256,
DatatypeConverter.printBase64Binary(key));
【解决方案2】:
对于仍然面临这个问题的人。
如果您是从 java 创建 jwt,则将“typ”标头添加到其中,由 PHP-jwt 检查。 jjwt 也将密钥编码为 base64,因此来自 Java
String jwtSecret = "yoursecret";
Map<String, Object> header = new HashMap<>();
header.put("typ", Header.JWT_TYPE);
String jwt = Jwts.builder()
.setHeader(header)
.setSubject("someclaim")
.setIssuedAt(new Date())
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512,TextCodec.BASE64.encode(jwtSecret))
.compact();
在php中
define('SECRET', 'yoursecret');
$decoded = (array) JWT::decode($jwt,SECRET, array('HS512'));
如果秘密包含特殊字符,它似乎也无法正确解码。