Java验证jwt token
https://jwt.io/
RS256加密JWT生成、验证
https://blog.csdn.net/u011411069/article/details/79966226
How to load public certificate from pem file..?
https://www.howtobuildsoftware.com/index.php/how-do/ciLJ/java-ssl-cryptography-bouncycastle-public-key-how-to-load-public-certificate-from-pem-file
1.HS256对称加密
package jwt; import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.Vector;
import java.util.Map; import sun.misc.BASE64Decoder; import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT; public class JWTValidator {
private static String JWT_Type = "JWT"; protected boolean validated;
protected Object[] claims; public JWTValidator() {
setValidated(false);
setClaims(null);
}
public String Generate(String secret, String issuer, String audience, String subject){
try {
Algorithm algorithm = Algorithm.HMAC256(secret); // HS256
String token = JWT.create()
.withIssuer(issuer)
.withAudience(audience)
.withSubject(subject)
.sign(algorithm);
System.out.println(token);
return token;
} catch (Exception exception){
//UTF-8 encoding not supported
return "";
}
} public void Validate(String token, String secret, String issuer, String audience, String subject) {
DecodedJWT jwt = 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 (JWTVerificationException e) {
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; Date now = new Date(); if ((jwt.getNotBefore() != null && jwt.getNotBefore().after(now)) ||
(jwt.getExpiresAt() != null && jwt.getExpiresAt().before(now)))
return; setValidated(true); Map<String, Claim> claimsMap = jwt.getClaims();
Vector<Claim> claimsVector = new Vector<Claim>(); if (claimsMap != null) {
for (Map.Entry<String, Claim> entry : claimsMap.entrySet()) {
String key = entry.getKey();
if (key != null && !key.matches("aud|sub|iss|exp|iat")) {
//claimsVector.add(new Claim(key, entry.getValue().asString()));
}
}
} setClaims(claimsVector.isEmpty() ? null : claimsVector.toArray());
} public boolean isValidated() { return validated; }
public void setValidated(boolean val) { validated = val; } public Object[] getClaims() { return claims; }
public void setClaims(Object[] val) { claims = (val == null ? new Object[0] : val); }
}
2.RS256不对称加密,需要用public cert来验证
package jwt; import junit.framework.TestCase;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
import org.jose4j.lang.JoseException;
import sun.security.util.DerInputStream;
import sun.security.util.DerValue; import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.UUID; public class JWTValidatorForRSA extends TestCase{ public void testCreateToken() throws IOException {
System.out.println(createToken());
} public void testVerifyToken() throws Exception {
String token = createToken();
System.out.println(token); String pkeyPath = "D:\\temp\\idsrv4.crt";
JwtClaims jwtClaims = verifyToken(token,pkeyPath);
System.out.println(jwtClaims.getClaimValue("name"));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(jwtClaims.getIssuedAt().getValueInMillis()));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(jwtClaims.getExpirationTime().getValueInMillis()));
} /**
* 生成jwt,SHA256加密
* @return
* @throws IOException
*/
public String createToken() throws IOException {
String privateKeyPath = "D:\\temp\\idsrv4.key";
PrivateKey privateKey = getPrivateKey(getStringFromFile(privateKeyPath));
final JwtClaims claims = new JwtClaims();
claims.setClaim("name", "jack");
claims.setSubject("a@a.com");
claims.setAudience("test");//用于验证签名是否合法,验证方必须包含这些内容才验证通过
claims.setExpirationTimeMinutesInTheFuture(-1); // 60*24*30);
claims.setIssuedAtToNow(); // Generate the payload
final JsonWebSignature jws = new JsonWebSignature();
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
jws.setPayload(claims.toJson());
jws.setKeyIdHeaderValue(UUID.randomUUID().toString()); // Sign using the private key
jws.setKey(privateKey);
try {
return jws.getCompactSerialization();
} catch (JoseException e) {
return null;
}
} /**
* 验证jwt
* @param token
* @return
* @throws Exception
*/
public JwtClaims verifyToken(String token,String publicKeyPath) throws Exception { try {
PublicKey publicKey = getPublicKey(publicKeyPath); JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setRequireExpirationTime()
.setVerificationKey(publicKey)
.setExpectedAudience("test")//用于验证签名是否合法,可以设置多个,且可设置必须存在项,如果jwt中不包含这些内容则不通过
.build(); return jwtConsumer.processToClaims(token);
} catch (Exception e) {
throw new RuntimeException(e);
}
} private String getStringFromFile(String filePath) throws IOException {
// 生成方法:安装openssl,执行 openssl genrsa -out private.pem 2048
return IOUtils.toString(new FileInputStream(filePath));
} /**
* 获取PublicKey对象
* @param publicKeyBase64
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws CertificateException
* @throws FileNotFoundException
*/
private PublicKey getPublicKey(String publicKeyPath) throws NoSuchAlgorithmException, InvalidKeySpecException, CertificateException, FileNotFoundException {
/* Not work : data isn't an object ID (tag = 2)
String pem = publicKeyBase64
.replaceAll("\\-*BEGIN.*CERTIFICATE\\-*", "")
.replaceAll("\\-*END.*CERTIFICATE\\-*", "");
java.security.Security.addProvider(
new org.bouncycastle.jce.provider.BouncyCastleProvider()
);
System.out.println(pem); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(pem));
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);
*/ CertificateFactory fact = CertificateFactory.getInstance("X.509");
FileInputStream is = new FileInputStream (publicKeyPath);
X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
PublicKey publicKey = cer.getPublicKey(); System.out.println(publicKey); return publicKey;
} /**
* 获取PrivateKey对象
* @param privateKeyBase64
* @return
*/
private PrivateKey getPrivateKey(String privateKeyBase64) {
String privKeyPEM = privateKeyBase64
.replaceAll("\\-*BEGIN.*KEY\\-*", "")
.replaceAll("\\-*END.*KEY\\-*", ""); // Base64 decode the data
byte[] encoded = Base64.decodeBase64(privKeyPEM); try {
DerInputStream derReader = new DerInputStream(encoded);
DerValue[] seq = derReader.getSequence(0); if (seq.length < 9) {
throw new GeneralSecurityException("Could not read private key");
} // skip version seq[0];
BigInteger modulus = seq[1].getBigInteger();
BigInteger publicExp = seq[2].getBigInteger();
BigInteger privateExp = seq[3].getBigInteger();
BigInteger primeP = seq[4].getBigInteger();
BigInteger primeQ = seq[5].getBigInteger();
BigInteger expP = seq[6].getBigInteger();
BigInteger expQ = seq[7].getBigInteger();
BigInteger crtCoeff = seq[8].getBigInteger(); RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp,
primeP, primeQ, expP, expQ, crtCoeff); KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(keySpec);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Java验证jwt token的更多相关文章
- java中生成和验证jwt
在这篇文章中主要记录一下在Java中如何使用 java 代码生成jwt token,主要是使用jjwt来生成和验证jwt,关于什么是JWT,以及JWT可以干什么不做详解. jwt的格式: base64 ...
- Spring Cloud OAuth2.0 微服务中配置 Jwt Token 签名/验证
关于 Jwt Token 的签名与安全性前面已经做了几篇介绍,在 IdentityServer4 中定义了 Jwt Token 与 Reference Token 两种验证方式(https://www ...
- 基于Token的身份验证--JWT
初次了解JWT,很基础,高手勿喷. 基于Token的身份验证用来替代传统的cookie+session身份验证方法中的session. JWT是啥? JWT就是一个字符串,经过加密处理与校验处理的字符 ...
- 【Azure Developer】如何验证 Azure AD的JWT Token (JSON Web 令牌)?
问题描述 使用微软Azure AD,对授权进行管理.通过所注册应用的OAuth API(https://login.chinacloudapi.cn/{TENANT ID}/oauth2/v2.0/t ...
- 基于token的身份验证JWT
传统身份验证的方法 HTTP 是一种没有状态的协议,也就是它并不知道是谁是访问应用.这里我们把用户看成是客户端,客户端使用用户名还有密码通过了身份验证,不过下回这个客户端再发送请求时候,还得再验证一下 ...
- golang学习笔记10 beego api 用jwt验证auth2 token 获取解码信息
golang学习笔记10 beego api 用jwt验证auth2 token 获取解码信息 Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放 ...
- JAVA中的Token
JAVA中的Token 基于Token的身份验证 来源:转载 最近在做项目开始,涉及到服务器与安卓之间的接口开发,在此开发过程中发现了安卓与一般浏览器不同,安卓在每次发送请求的时候并不会带上上一次请求 ...
- Java生鲜电商平台-Java后端生成Token架构与设计详解
Java生鲜电商平台-Java后端生成Token架构与设计详解 目的:Java开源生鲜电商平台-Java后端生成Token目的是为了用于校验客户端,防止重复提交. 技术选型:用开源的JWT架构. 1. ...
- JWT(二):使用 Java 实现 JWT
JWT(一):认识 JSON WebToken JWT(二):使用 Java 实现 JWT 介绍 原理在上篇<JWT(一):认识 JSON Web Token>已经说过了,实现起来并不难, ...
随机推荐
- Python开发【第十二篇】python作用域和global nonlocal
python的作用域 作用域也叫名字空间,是访问变量时查找变量名的范围空间 python中的四个作用域 LEGB 作用域 英文解释 英文缩写 局部作用域 Local(function) L 外部嵌套函 ...
- Java自学-数字与字符串 字符串转换
Java中把数字转换为字符串,字符串转换为数字 步骤 1 : 数字转字符串 方法1: 使用String类的静态方法valueOf 方法2: 先把基本类型装箱为对象,然后调用对象的toString pa ...
- Java自学-数字与字符串 装箱和拆箱
Java中基本类型的装箱和拆箱 步骤 1 : 封装类 所有的基本类型,都有对应的类类型 比如int对应的类是Integer 这种类就叫做封装类 package digit; public class ...
- 浅谈Object.prototype.toString.call()方法
在JavaScript里使用typeof判断数据类型,只能区分基本类型,即:number.string.undefined.boolean.object.对于null.array.function.o ...
- FreeRTOS 任务通知
可以替代队列.二值信号量.计数型信号量和事件标志组 发送任务通知 获取任务通知 FreeRTOS 任务通知模拟二值信号量 FreeRTOS 任务通知模拟计数型信号量 FreeRTOS 任务通知模拟消息 ...
- RabbitMQ基本概念(二)-RabbitMQ消息队列架构与基本概念
没错我还是没有讲怎么安装和写一个HelloWord,不过快了,这一章我们先了解下RabbitMQ的基本概念. RabbitMQ架构 说是架构其实更像是应用场景下的架构(自己画的有点丑,勿嫌弃) 从图中 ...
- SpringBoot2.x配置Cors跨域
1 跨域的理解 跨域是指:浏览器A从服务器B获取的静态资源,包括Html.Css.Js,然后在Js中通过Ajax访问C服务器的静态资源或请求.即:浏览器A从B服务器拿的资源,资源中想访问服务器C的资源 ...
- JVM 运行时数据区:程序计数器、Java 虚拟机栈和本地方法栈,方法区、堆以及直接内存
Java 虚拟机可以看作一台抽象的计算机,如同真实的计算机,它也有自己的指令集和运行时内存区域. Java 虚拟机在执行 Java 程序的过程中会把它所管理的内存(运行时内存区域)划分为若干个不同的数 ...
- 【转】如何把变量或者数组定义到SDRAM及任意位置
我们开发软件的时候,经常会遇到到一个问题,就是内存不够,这个时候就纠结了,怎么办,有两种方法,第一种是扩展内存,外加SRAM或者SDRAM:第二种应该就是优化代码,也就是通常所说的把数组大小减一减,代 ...
- jmeter 实现登录参数化
业务场景 在测试过程中,一般需要模拟不同的用户登录,这样压测的数据比较平均,也能更好的模拟真实的压力情况. 如果使用同一个用户账号进行测试,那么比如在查询代办的时候,此人的待办太多,也不符合实际的情况 ...