我有一个字符串形式的令牌,我下载了公共证书,并按如下方式创建了一个公钥。
但我不确定如何通过这么多信息继续进行验证。
我找到了C#和.NET的解决方案,但没有找到Java的解决方案。 请注意,我没有jks文件或私钥。
FileInputStream fin = new FileInputStream("d://public.crt");
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
答案 0 :(得分:1)
要使用Auth0库(com.auth0:java-jwt)在Java中验证JWT:
检索已使用密钥签名的算法,例如:
// Load your public key from a file
final PublicKey ecdsa256PublicKey = getPublicKey(...);
final Algorithm algorithm = Algorithm.ECDSA256((ECPublicKey) ecdsa256PublicKey, null);
使用相应的算法验证其签名:
final DecodedJWT decodedJWT = JWT.decode("J.W.T[...]");
// Will throw a SignatureVerificationException if the token's signature is invalid
algorithm.verify(decodedJWT);
答案 1 :(得分:0)
如果您询问有关JSON WebToken的信息,可以按照以下代码示例进行操作:
import javax.xml.bind.DatatypeConverter;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;
//Sample method to validate and read the JWT
private void parseJWT(String jwt) {
//This line will throw an exception if it is not a signed JWS (as expected)
Claims claims = Jwts.parser()
.setSigningKey(DatatypeConverter.parseBase64Binary(apiKey.getSecret()))
.parseClaimsJws(jwt).getBody();
System.out.println("ID: " + claims.getId());
System.out.println("Subject: " + claims.getSubject());
System.out.println("Issuer: " + claims.getIssuer());
System.out.println("Expiration: " + claims.getExpiration());
}
如需进一步阅读,您可以访问点击here
答案 2 :(得分:0)
我做了类似的事情来验证JWT
try {
DecodedJWT decodedJWT = JWT.decode(jwt); // your string
JwkProvider provider = new JwkProviderBuilder(new URL("JWKS URL")).build();
Jwk jwk = provider.get(decodedJWT.getKeyId());
Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);
Verification verifier = JWT.require(algorithm);
verifier.build().verify(decodedJWT);
} catch (JWTVerificationException | JwkException | MalformedURLException e) {
// throw your exception
}
JwkProviderBuilder
可能很昂贵,因此,如果您使用的是Spring,则可以将其提取为另一种方法,并用@PostConstruct
对其进行注释以进行优化。