SpringBoot2.x使⽤JWT⽣成和解析Token-简单案例使⽤:
SpringBoot 2.3.0
JDK 1.8
Idea2019
主要jwt的依赖:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
⼯具类:JWTService.java
⽤于⽣成和解析token
projectmon.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.ptions.AlgorithmMismatchException;
import com.ptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
projectmon.jwt.Payload;
project.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.*;
@Component
public class JWTService {
private String secret = "secret";
private String issuer = "USERSERVICE";//发布者
private String subject = "userLoginToken";//主题
private String audience = "APP";//签名的观众也可以理解谁接受签名的
private Map<String,String> claims;//⾃定义签名
/**
* 创建 hour⼩时后过期的Token
* @param claims
* @param hour
* @return
*/
public String createToken(Map<String,String> claims,int hour) {
Payload createPayload = atePayload(1);
createPayload.setClaims(claims);
Algorithm hmac256 = Algorithm.Secret());
Algorithm hmac256 = Algorithm.Secret());
return createToken(createPayload,hmac256);
}
/**
* 根据负载和算法创建Token
* @param payload
* @param algorithm
* @return
*/
public String createToken(Payload payload,Algorithm algorithm) {
Builder headBuilder = createHeaderBuilder(algorithm);
Builder publicClaimbuilder = addPublicClaimBuilder(headBuilder,payload);
Builder privateClaimbuilder = addPrivateClaimbuilder(publicClaimbuilder,payload);
String token = privateClaimbuilder.sign(algorithm);
return token;
}
/**
* 创建⾃定⼩时后过期的负载
* @param hour
* @return
*/springboot推荐算法
public Payload createPayload(int hour) {
Payload payload = new Payload();
payload.Issuer());
payload.Subject());
payload.Audience());
this.setIssuedAtAndExpiresAt(new Date(), hour, payload);
return payload;
}
/**
* 创建⾃定⼩时后过期的负载
* @param hour
* @return
*/
public Payload createPayload(String issuer, String subject, String audience, Date date,int hour) { Payload payload = new Payload();
payload.setIssuer(issuer);
payload.setSubject(subject);
payload.setAudience(audience);
this.setIssuedAtAndExpiresAt(date, hour, payload);
return payload;
}
/**
* 添加私有声明
* @param builder
* @param payload
* @return
*/
private Builder addPrivateClaimbuilder(Builder builder, Payload payload) {
Map<String, String> claims = Claims();
if(!CollectionUtils.isEmpty(claims)) {
claims.forEach((k,v)->{
builder.withClaim(k, (String) v);
});
}
return builder;
}
/**
* 添加公共声明
* @param builder
* @param payload
* @return
*/
private Builder addPublicClaimBuilder(Builder builder,Payload payload) {
if(!StringUtils.Issuer())) {
builder.Issuer());
}
if(!StringUtils.Subject())) {
builder.Subject());
}
IssuedAt() != null) {
builder .IssuedAt()); //⽣成签名的时间
}
ExpiresAt() != null) {
builder .ExpiresAt());//签名过期的时间
}
if(CollectionUtils.Audience())) {
builder.withAudience(s);
});
}
return builder;
}
/**
* 创建JWT 头部信息
* @param algorithm
* @return
*/
private Builder createHeaderBuilder(Algorithm algorithm) {
Builder builder = ate().withHeader(buildJWTHeader(algorithm)); return builder;
}
/**
* 校验Token
* @param token
* @return
*/
public Payload verifyToken(String token) {
DecodedJWT jwt = null;
Payload payload = null;
try {
jwt = getDecodedJWT(token);
payload = getPublicClaim(jwt);
payload = getPrivateClaim(jwt, payload);
}catch (AlgorithmMismatchException e) {
throw e;
}catch (TokenExpiredException e) {
throw e;
} catch (Exception e) {
throw e;
}
return payload;
}
/**
* 获取JWT 私有声明
* @param jwt
* @param payload
* @return
*/
private Payload getPrivateClaim(DecodedJWT jwt, Payload payload) { Map<String, String> claims = new HashMap<String, String>();
String asString = v.asString();
claims.put(k, asString);
});
payload.setClaims(claims);
return payload;
}
/**
* 获取JWT 公共声明
* @param jwt
* @return
*/
private Payload getPublicClaim(DecodedJWT jwt) {
Payload payload = new Payload();
payload.Issuer());
payload.Subject());
payload.Audience());
payload.IssuedAt());
payload.ExpiresAt());
return payload;
}
/**
* 获取 DecodedJWT
* @param token
* @return
*/
private DecodedJWT getDecodedJWT(String token) {
JWTVerifier verifier = quire(Algorithm.Secret())).build(); DecodedJWT jwt = verifier.verify(token);
return jwt;
}
/**
* 构建JWT头部Map信息
* @param algorithm
* @return
*/
private Map<String, Object> buildJWTHeader(Algorithm algorithm) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("alg", Name());
map.put("typ", "JWT");
return map;
}
/**
* 根据发布时间设置过期时间
* @param issuedAt
* @param hour
* @param payload
*/
public void setIssuedAtAndExpiresAt(Date issuedAt,Integer hour,Payload payload) { payload.setIssuedAt(issuedAt);
payload.setExpiresAt(getAfterDateByHour(issuedAt,hour));
}
/**
* 返回⼀定时间后的⽇期
* @param date 开始计时的时间
* @param hour 增加的⼩时
* @return
*/
public Date getAfterDateByHour(Date date, int hour){
if(date == null){
date = new Date();
}
Date afterDate = getAfterDate(date,0,0,0,hour,0,0);
return afterDate;
}
public Date getAfterDateByMinute(Date date, int minute){
if(date == null){
date = new Date();
}
Date afterDate = getAfterDate(date,0,0,0,0,minute,0);
return afterDate;
}
/**
* 返回⼀定时间后的⽇期
* @param date 开始计时的时间
* @param year 增加的年
* @param month 增加的⽉
* @param day 增加的⽇
* @param hour 增加的⼩时
* @param minute 增加的分钟
* @param second 增加的秒
* @return
*/
public Date getAfterDate(Date date, int year, int month, int day, int hour, int minute, int second){ if(date == null){
date = new Date();
}
Calendar cal = new GregorianCalendar ();
cal.setTime(date);
if(year != 0){
cal.add(Calendar.YEAR, year);
}
if(month != 0){
cal.add(Calendar.MONTH, month);
}
if(day != 0){
cal.add(Calendar.DATE, day);
}
if(hour != 0){
cal.add(Calendar.HOUR_OF_DAY, hour);
}
if(minute != 0){
cal.add(Calendar.MINUTE, minute);
}
if(second != 0){
cal.add(Calendar.SECOND, second);
}
Time();
}
/**
* 获得token中的信息⽆需secret解密也能获得
*
* @return token中包含的实体类
*/
public User getUser(String token) {
DecodedJWT jwt = JWT.decode(token);
User user = new User();
user.Claim("username").asString());
user.Claim("password").asString());
return user;
}
public void setClaims(Map<String, String> claims) {
this.claims = claims;
}
public Map<String, String> getClaims() {
return claims;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论