JWT(json web token)
程序员文章站
2024-02-04 08:22:46
...
spring-boot-jwt
Spring-Boot-OAuth2-JWT-MySQ
jfinal_jwt
maven 依赖
<!--JWT-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
实例
package com.wanggs.cons;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wanggs.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import org.joda.time.DateTime;
public class JWT {
private static String JWT_KEY = "lOi98Jhy6dt";//PropertyUtil.getProperty("jwt.key","lOi98Jhy6dt");
private static Key key = null;
// token过期时间天数
private static int EXP_DAYS = 30;//Integer.valueOf(PropertyUtil.getProperty("jwt.expDays", "30"));
static {
SecretKeyFactory keyFactory;
try {
keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
KeySpec keySpec = new PBEKeySpec(JWT_KEY.toCharArray());
key = keyFactory.generateSecret(keySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
}
public static String create(User user) {
String json = JSON.toJSONString(user);
return Jwts.builder().setSubject(user.getId().toString()).setClaims(JSON.parseObject(json))
.setExpiration(new DateTime().plusDays(EXP_DAYS).toDate()).signWith(io.jsonwebtoken.SignatureAlgorithm.HS512, key).compact();
}
public static User parse(String compactJws) throws NoAuthorization {
if (compactJws == null) {
throw new NoAuthorization();
}
try {
Jws<Claims> claims = Jwts.parser().setSigningKey(key).parseClaimsJws(compactJws);
// 走到这里说明token验证通过
// 接下来获取信息
Claims body = claims.getBody();
JSONObject jsonObject = new JSONObject(body);
return JSON.toJavaObject(jsonObject, User.class);
} catch (Exception e) {
throw new NoAuthorization();
}
}
public static boolean checkToken(HttpServletRequest request) {
String token = getToken(request);
return checkToken(token);
}
public static boolean checkToken(String compactJws) {
try {
//LOG.debug("检查token:{}", compactJws);
Jwts.parser().setSigningKey(key).parseClaimsJws(compactJws);
return true;
} catch (Exception e) {
return false;
}
}
public static User parse(HttpServletRequest request) throws NoAuthorization {
String token = getToken(request);
return parse(token);
}
public static String getToken(HttpServletRequest request) {
String jwt = request.getHeader("Authorization");
if (jwt == null) {
return null;
}
jwt = jwt.replace("Bearer", "").trim();
return jwt;
}
public static void main(String[] args) {
User user = new User();
user.setId(1L);
user.setOpenId("aaaaa");
user.setNickName("bbbbb");
String jwt = create(user);
System.out.println("jwt:" + jwt);
try {
Thread.sleep(1000);
System.out.println("checkToken:" + checkToken(jwt));
User user2 = parse(jwt);
System.out.println(JSON.toJSONString(user2));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 输出:
* jwt:eyJhbGciOiJIUzUxMiJ9.eyJuaWNrTmFtZSI6ImJiYmJiIiwib3BlbklkIjoiYWFhYWEiLCJpZCI6MSwiZXhwIjoxNTA3Mjc0OTUzfQ.CvdniqQ29gVokSmh8kj8qrlbgea5Ij49aI0y6Zx0YnjP0djodI7c1SwAYyAyrcMzk5BIau3Z8rMdb3m8z-7Nbg
* checkToken:true
{"id":1,"nickName":"bbbbb","openId":"aaaaa"}
*
*/
}
异常
public class NoAuthorization extends Exception {
private static final long serialVersionUID = -4640347603089936793L;
}
实体类
package com.wanggs.domain;
import java.util.Date;
/**
* Created by wanggs on 2017/9/6.
*/
public class User {
private Long id;
private String name;
private String username;
private String pswd;
private Date gmtCreate;
// 微信openId,数据库字段:openId
private String openId;
// 微信nickName,数据库字段:nickName
private String nickName;
// 微信性别,1男,2女,数据库字段:gender
private Integer gender;
// 微信头像,数据库字段:headimgurl
private String headimgurl;
// 微信用户组,数据库字段:groupId
private Integer groupId;
// 登录时间,数据库字段:loginTime
private Date loginTime;
// 登录城市,数据库字段:loginCity
private String loginCity;
// 是否玩过神机妙算/0未玩过/1玩过,数据库字段:isPlay
private Integer isPlay;
public void setId(Long id){
this.id = id;
}
public Long getId(){
return this.id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return this.username;
}
public void setPswd(String pswd){
this.pswd = pswd;
}
public String getPswd(){
return this.pswd;
}
public void setGmtCreate(Date gmtCreate){
this.gmtCreate = gmtCreate;
}
public Date getGmtCreate(){
return this.gmtCreate;
}
/** 设置 微信openId,对应字段 user.openId */
public void setOpenId(String openId){
this.openId = openId;
}
/** 获取 微信openId,对应字段 user.openId */
public String getOpenId(){
return this.openId;
}
/** 设置 微信nickName,对应字段 user.nickName */
public void setNickName(String nickName){
this.nickName = nickName;
}
/** 获取 微信nickName,对应字段 user.nickName */
public String getNickName(){
return this.nickName;
}
/** 设置 微信性别,1男,2女,对应字段 user.gender */
public void setGender(Integer gender){
this.gender = gender;
}
/** 获取 微信性别,1男,2女,对应字段 user.gender */
public Integer getGender(){
return this.gender;
}
/** 设置 微信头像,对应字段 user.headimgurl */
public void setHeadimgurl(String headimgurl){
this.headimgurl = headimgurl;
}
/** 获取 微信头像,对应字段 user.headimgurl */
public String getHeadimgurl(){
return this.headimgurl;
}
/** 设置 微信用户组,对应字段 user.groupId */
public void setGroupId(Integer groupId){
this.groupId = groupId;
}
/** 获取 微信用户组,对应字段 user.groupId */
public Integer getGroupId(){
return this.groupId;
}
/** 设置 登录时间,对应字段 user.loginTime */
public void setLoginTime(Date loginTime){
this.loginTime = loginTime;
}
/** 获取 登录时间,对应字段 user.loginTime */
public Date getLoginTime(){
return this.loginTime;
}
/** 设置 登录城市,对应字段 user.loginCity */
public void setLoginCity(String loginCity){
this.loginCity = loginCity;
}
/** 获取 登录城市,对应字段 user.loginCity */
public String getLoginCity(){
return this.loginCity;
}
/** 设置 是否玩过神机妙算/0未玩过/1玩过,对应字段 user.isPlay */
public void setIsPlay(Integer isPlay){
this.isPlay = isPlay;
}
/** 获取 是否玩过神机妙算/0未玩过/1玩过,对应字段 user.isPlay */
public Integer getIsPlay(){
return this.isPlay;
}
}
}
上一篇: 用大顶堆取出一个数组中最小的k个数
下一篇: 编程的艺术--王垠