实现原理
导入maven依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
创建实体对象
package com.wl.study.utils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SessionInfo {
private Long userId;
private String userName;
private String token;
}
创建token生成与解析
package com.wl.study.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import java.text.MessageFormat;
import java.util.Optional;
public class JwtUtil {
/***
* 生成token
* @param sessionInfo
* @return
*/
public static Optional<String> generateToken(SessionInfo sessionInfo){
String token = Jwts.builder()
//主题
.setSubject(JwtConfig.JWT_SUBJECT)
//自定义属性
.claim(JwtConfig.JWT_USERID, sessionInfo.getUserId())
.claim(JwtConfig.JWT_USERNAME, sessionInfo.getUserName())
// 压缩
.compressWith(CompressionCodecs.DEFLATE)
// 签名
.signWith(SignatureAlgorithm.HS512, JwtConfig.JWT_SIGNING_KEY)
.compact();
return Optional.of(MessageFormat.format("{0}{1}",JwtConfig.JWT_TOKEN_PREFIX,token));
}
/***
* 解析token
* @param token
* @return
*/
public static Optional<SessionInfo> parserToken(String token){
if(StringUtils.isEmpty(token)){
return Optional.empty();
}
Claims claims = Jwts.parser()
.setSigningKey(JwtConfig.JWT_SIGNING_KEY)
.parseClaimsJws(token.replace(JwtConfig.JWT_TOKEN_PREFIX, ""))
.getBody();
SessionInfo sessionInfo = SessionInfo.builder().token(token).build();
if(claims.containsKey(JwtConfig.JWT_USERID)){
sessionInfo.setUserId( Long.valueOf(claims.get(JwtConfig.JWT_USERID).toString()));
}
if(claims.containsKey(JwtConfig.JWT_USERNAME)){
sessionInfo.setUserName( claims.get(JwtConfig.JWT_USERNAME).toString());
}
return Optional.of(sessionInfo);
}
private static class JwtConfig{
private final static String JWT_SUBJECT ="integral";
private final static String JWT_USERID ="userId";
private final static String JWT_USERNAME ="userName";
/***
* 密钥
*/
private final static String JWT_SIGNING_KEY = "integral@Jwt!&key^#";
/**
* jwt的前缀
*/
public static final String JWT_TOKEN_PREFIX = "Bearer ";
}
public static void main(String[] args) {
SessionInfo sessionInfo = new SessionInfo();
sessionInfo.setUserId(1L);
sessionInfo.setUserName("张飞");
Optional<String> optional = JwtUtil.generateToken(sessionInfo);
System.out.println(MessageFormat.format("{0}:{1}","生成token",optional.orElse(null)));
System.out.println(MessageFormat.format("{0}:{1}","解析token",JwtUtil.parserToken(optional.get())));
}
}
创建token工具类
package com.wl.study.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import java.text.MessageFormat;
import java.util.Optional;
public class JwtUtil {
/***
* 生成token
* @param sessionInfo
* @return
*/
public static Optional<String> generateToken(SessionInfo sessionInfo){
String token = Jwts.builder()
//主题
.setSubject(JwtConfig.JWT_SUBJECT)
//自定义属性
.claim(JwtConfig.JWT_USERID, sessionInfo.getUserId())
.claim(JwtConfig.JWT_USERNAME, sessionInfo.getUserName())
// 压缩
.compressWith(CompressionCodecs.DEFLATE)
// 签名
.signWith(SignatureAlgorithm.HS512, JwtConfig.JWT_SIGNING_KEY)
.compact();
return Optional.of(MessageFormat.format("{0}{1}",JwtConfig.JWT_TOKEN_PREFIX,token));
}
/***
* 解析token
* @param token
* @return
*/
public static Optional<SessionInfo> parserToken(String token){
if(StringUtils.isEmpty(token)){
return Optional.empty();
}
Claims claims = Jwts.parser()
.setSigningKey(JwtConfig.JWT_SIGNING_KEY)
.parseClaimsJws(token.replace(JwtConfig.JWT_TOKEN_PREFIX, ""))
.getBody();
SessionInfo sessionInfo = SessionInfo.builder().token(token).build();
if(claims.containsKey(JwtConfig.JWT_USERID)){
sessionInfo.setUserId( Long.valueOf(claims.get(JwtConfig.JWT_USERID).toString()));
}
if(claims.containsKey(JwtConfig.JWT_USERNAME)){
sessionInfo.setUserName( claims.get(JwtConfig.JWT_USERNAME).toString());
}
return Optional.of(sessionInfo);
}
private static class JwtConfig{
private final static String JWT_SUBJECT ="integral";
private final static String JWT_USERID ="userId";
private final static String JWT_USERNAME ="userName";
/***
* 密钥
*/
private final static String JWT_SIGNING_KEY = "integral@Jwt!&key^#";
/**
* jwt的前缀
*/
public static final String JWT_TOKEN_PREFIX = "Bearer ";
}
public static void main(String[] args) {
SessionInfo sessionInfo = new SessionInfo();
sessionInfo.setUserId(1L);
sessionInfo.setUserName("张飞");
Optional<String> optional = JwtUtil.generateToken(sessionInfo);
System.out.println(MessageFormat.format("{0}:{1}","生成token",optional.orElse(null)));
System.out.println(MessageFormat.format("{0}:{1}","解析token",JwtUtil.parserToken(optional.get())));
}
}