基于Java验证jwt token代码实例
这篇文章主要介绍了基于Java验证jwttoken代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
Howtoloadpubliccertificatefrompemfile..?地址
1.HS256对称加密
packagejwt;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.security.KeyFactory;
importjava.security.PrivateKey;
importjava.security.PublicKey;
importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjava.security.spec.PKCS8EncodedKeySpec;
importjava.security.spec.X509EncodedKeySpec;
importjava.util.Base64;
importjava.util.Date;
importjava.util.Vector;
importjava.util.Map;
importsun.misc.BASE64Decoder;
importcom.auth0.jwt.JWT;
importcom.auth0.jwt.algorithms.Algorithm;
importcom.auth0.jwt.exceptions.JWTVerificationException;
importcom.auth0.jwt.interfaces.Claim;
importcom.auth0.jwt.interfaces.DecodedJWT;
publicclassJWTValidator{
privatestaticStringJWT_Type="JWT";
protectedbooleanvalidated;
protectedObject[]claims;
publicJWTValidator(){
setValidated(false);
setClaims(null);
}
publicStringGenerate(Stringsecret,Stringissuer,Stringaudience,Stringsubject){
try{
Algorithmalgorithm=Algorithm.HMAC256(secret);//HS256
Stringtoken=JWT.create()
.withIssuer(issuer)
.withAudience(audience)
.withSubject(subject)
.sign(algorithm);
System.out.println(token);
returntoken;
}catch(Exceptionexception){
//UTF-8encodingnotsupported
return"";
}
}
publicvoidValidate(Stringtoken,Stringsecret,Stringissuer,Stringaudience,Stringsubject){
DecodedJWTjwt=null;
setValidated(false);
if(token==null||secret==null||issuer==null||audience==null||subject==null)
return;
try{
jwt=JWT.require(Algorithm.HMAC256(secret.getBytes())).build().verify(token);
}catch(JWTVerificationExceptione){
return;
}
if(jwt==null||jwt.getType()==null||!jwt.getType().contentEquals(JWT_Type))
return;
if(!jwt.getIssuer().contentEquals(issuer)||
!jwt.getAudience().contains(audience)||
!jwt.getSubject().contentEquals(subject))
return;
Datenow=newDate();
if((jwt.getNotBefore()!=null&&jwt.getNotBefore().after(now))||
(jwt.getExpiresAt()!=null&&jwt.getExpiresAt().before(now)))
return;
setValidated(true);
MapclaimsMap=jwt.getClaims();
VectorclaimsVector=newVector();
if(claimsMap!=null){
for(Map.Entryentry:claimsMap.entrySet()){
Stringkey=entry.getKey();
if(key!=null&&!key.matches("aud|sub|iss|exp|iat")){
//claimsVector.add(newClaim(key,entry.getValue().asString()));
}
}
}
setClaims(claimsVector.isEmpty()?null:claimsVector.toArray());
}
publicbooleanisValidated(){returnvalidated;}
publicvoidsetValidated(booleanval){validated=val;}
publicObject[]getClaims(){returnclaims;}
publicvoidsetClaims(Object[]val){claims=(val==null?newObject[0]:val);}
}
2.RS256不对称加密,需要用publiccert来验证
packagejwt;
importjunit.framework.TestCase;
importorg.apache.commons.codec.binary.Base64;
importorg.apache.commons.io.IOUtils;
importorg.jose4j.jws.AlgorithmIdentifiers;
importorg.jose4j.jws.JsonWebSignature;
importorg.jose4j.jwt.JwtClaims;
importorg.jose4j.jwt.consumer.JwtConsumer;
importorg.jose4j.jwt.consumer.JwtConsumerBuilder;
importorg.jose4j.lang.JoseException;
importsun.security.util.DerInputStream;
importsun.security.util.DerValue;
importjava.io.ByteArrayInputStream;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.math.BigInteger;
importjava.security.*;
importjava.security.cert.CertificateException;
importjava.security.cert.CertificateFactory;
importjava.security.cert.X509Certificate;
importjava.security.spec.InvalidKeySpecException;
importjava.security.spec.RSAPrivateCrtKeySpec;
importjava.security.spec.X509EncodedKeySpec;
importjava.text.SimpleDateFormat;
importjava.util.UUID;
publicclassJWTValidatorForRSAextendsTestCase{
publicvoidtestCreateToken()throwsIOException{
System.out.println(createToken());
}
publicvoidtestVerifyToken()throwsException{
Stringtoken=createToken();
System.out.println(token);
StringpkeyPath="D:\\temp\\idsrv4.crt";
JwtClaimsjwtClaims=verifyToken(token,pkeyPath);
System.out.println(jwtClaims.getClaimValue("name"));
System.out.println(newSimpleDateFormat("yyyy-MM-ddHH:mm:ss").format(jwtClaims.getIssuedAt().getValueInMillis()));
System.out.println(newSimpleDateFormat("yyyy-MM-ddHH:mm:ss").format(jwtClaims.getExpirationTime().getValueInMillis()));
}
/**
*生成jwt,SHA256加密
*@return
*@throwsIOException
*/
publicStringcreateToken()throwsIOException{
StringprivateKeyPath="D:\\temp\\idsrv4.key";
PrivateKeyprivateKey=getPrivateKey(getStringFromFile(privateKeyPath));
finalJwtClaimsclaims=newJwtClaims();
claims.setClaim("name","jack");
claims.setSubject("a@a.com");
claims.setAudience("test");//用于验证签名是否合法,验证方必须包含这些内容才验证通过
claims.setExpirationTimeMinutesInTheFuture(-1);//60*24*30);
claims.setIssuedAtToNow();
//Generatethepayload
finalJsonWebSignaturejws=newJsonWebSignature();
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
jws.setPayload(claims.toJson());
jws.setKeyIdHeaderValue(UUID.randomUUID().toString());
//Signusingtheprivatekey
jws.setKey(privateKey);
try{
returnjws.getCompactSerialization();
}catch(JoseExceptione){
returnnull;
}
}
/**
*验证jwt
*@paramtoken
*@return
*@throwsException
*/
publicJwtClaimsverifyToken(Stringtoken,StringpublicKeyPath)throwsException{
try{
PublicKeypublicKey=getPublicKey(publicKeyPath);
JwtConsumerjwtConsumer=newJwtConsumerBuilder()
.setRequireExpirationTime()
.setVerificationKey(publicKey)
.setExpectedAudience("test")//用于验证签名是否合法,可以设置多个,且可设置必须存在项,如果jwt中不包含这些内容则不通过
.build();
returnjwtConsumer.processToClaims(token);
}catch(Exceptione){
thrownewRuntimeException(e);
}
}
privateStringgetStringFromFile(StringfilePath)throwsIOException{
//生成方法:安装openssl,执行opensslgenrsa-outprivate.pem2048
returnIOUtils.toString(newFileInputStream(filePath));
}
/**
*获取PublicKey对象
*@parampublicKeyBase64
*@return
*@throwsNoSuchAlgorithmException
*@throwsInvalidKeySpecException
*@throwsCertificateException
*@throwsFileNotFoundException
*/
privatePublicKeygetPublicKey(StringpublicKeyPath)throwsNoSuchAlgorithmException,InvalidKeySpecException,CertificateException,FileNotFoundException{
/*Notwork:dataisn'tanobjectID(tag=2)
Stringpem=publicKeyBase64
.replaceAll("\\-*BEGIN.*CERTIFICATE\\-*","")
.replaceAll("\\-*END.*CERTIFICATE\\-*","");
java.security.Security.addProvider(
neworg.bouncycastle.jce.provider.BouncyCastleProvider()
);
System.out.println(pem);
X509EncodedKeySpecpubKeySpec=newX509EncodedKeySpec(Base64.decodeBase64(pem));
KeyFactorykeyFactory=KeyFactory.getInstance("RSA");
PublicKeypublicKey=keyFactory.generatePublic(pubKeySpec);
*/
CertificateFactoryfact=CertificateFactory.getInstance("X.509");
FileInputStreamis=newFileInputStream(publicKeyPath);
X509Certificatecer=(X509Certificate)fact.generateCertificate(is);
PublicKeypublicKey=cer.getPublicKey();
System.out.println(publicKey);
returnpublicKey;
}
/**
*获取PrivateKey对象
*@paramprivateKeyBase64
*@return
*/
privatePrivateKeygetPrivateKey(StringprivateKeyBase64){
StringprivKeyPEM=privateKeyBase64
.replaceAll("\\-*BEGIN.*KEY\\-*","")
.replaceAll("\\-*END.*KEY\\-*","");
//Base64decodethedata
byte[]encoded=Base64.decodeBase64(privKeyPEM);
try{
DerInputStreamderReader=newDerInputStream(encoded);
DerValue[]seq=derReader.getSequence(0);
if(seq.length<9){
thrownewGeneralSecurityException("Couldnotreadprivatekey");
}
//skipversionseq[0];
BigIntegermodulus=seq[1].getBigInteger();
BigIntegerpublicExp=seq[2].getBigInteger();
BigIntegerprivateExp=seq[3].getBigInteger();
BigIntegerprimeP=seq[4].getBigInteger();
BigIntegerprimeQ=seq[5].getBigInteger();
BigIntegerexpP=seq[6].getBigInteger();
BigIntegerexpQ=seq[7].getBigInteger();
BigIntegercrtCoeff=seq[8].getBigInteger();
RSAPrivateCrtKeySpeckeySpec=newRSAPrivateCrtKeySpec(modulus,publicExp,privateExp,
primeP,primeQ,expP,expQ,crtCoeff);
KeyFactoryfactory=KeyFactory.getInstance("RSA");
returnfactory.generatePrivate(keySpec);
}catch(Exceptione){
e.printStackTrace();
}
returnnull;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。