|
|
package com.dsideal.gw.Util;
|
|
|
|
|
|
import com.dsideal.gw.GwApplication;
|
|
|
import io.jsonwebtoken.Claims;
|
|
|
import io.jsonwebtoken.Jwts;
|
|
|
import io.jsonwebtoken.SignatureAlgorithm;
|
|
|
import io.jsonwebtoken.security.Keys;
|
|
|
import com.jfinal.plugin.activerecord.Record;
|
|
|
|
|
|
import javax.crypto.SecretKey;
|
|
|
import javax.servlet.http.HttpServletRequest;
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
import java.util.Date;
|
|
|
import java.util.HashMap;
|
|
|
import java.util.Map;
|
|
|
|
|
|
public class JwtUtil {
|
|
|
public static final String AUTHORIZATION_STARTER = "Bearer ";
|
|
|
public static final String SECRET = GwApplication.PropKit.get("jwt.SECRET");
|
|
|
|
|
|
// 生成安全的密钥
|
|
|
private static final SecretKey key = Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8));
|
|
|
|
|
|
/**
|
|
|
* 功能:生成JWT函数
|
|
|
*
|
|
|
* @param identity_id 身份ID
|
|
|
* @param person_id 人员ID
|
|
|
* @param bureau_id 机构ID
|
|
|
* @return JWT签名
|
|
|
*/
|
|
|
public static String generateToken(int identity_id, String person_id, String bureau_id) {
|
|
|
// 获取当前日期和时间
|
|
|
Date now = new Date();
|
|
|
// 格式化日期
|
|
|
Map<String, Object> claims = new HashMap<>();
|
|
|
claims.put("create_time", now.toString());
|
|
|
claims.put("identity_id", identity_id);
|
|
|
claims.put("person_id", person_id);
|
|
|
claims.put("bureau_id", bureau_id);
|
|
|
|
|
|
return AUTHORIZATION_STARTER + Jwts.builder()
|
|
|
.setClaims(claims)
|
|
|
.signWith(key, SignatureAlgorithm.HS256)
|
|
|
.compact();
|
|
|
}
|
|
|
|
|
|
public static Claims getClaims(String token) {
|
|
|
if (token.contains(AUTHORIZATION_STARTER)) {
|
|
|
token = token.replace(AUTHORIZATION_STARTER, "");
|
|
|
}
|
|
|
Claims claims;
|
|
|
try {
|
|
|
claims = Jwts.parserBuilder()
|
|
|
.setSigningKey(key)
|
|
|
.build()
|
|
|
.parseClaimsJws(token)
|
|
|
.getBody();
|
|
|
} catch (Exception e) {
|
|
|
System.out.println(e.toString());
|
|
|
claims = null;
|
|
|
}
|
|
|
return claims;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 获取当前用户信息
|
|
|
*
|
|
|
* @param req 请求
|
|
|
* @return
|
|
|
*/
|
|
|
public static Record getPersonInfo(HttpServletRequest req) {
|
|
|
String jwtToken = req.getHeader("Authorization");
|
|
|
if (jwtToken == null) {
|
|
|
//尝试从Cookie中获取jwt-token
|
|
|
jwtToken = CookieUtil.getValue(req, "jwt-token");
|
|
|
}
|
|
|
Record record = new Record();
|
|
|
Claims claims = getClaims(jwtToken);
|
|
|
if (claims != null) {
|
|
|
record.set("identity_id", claims.get("identity_id"));
|
|
|
record.set("person_id", claims.get("person_id"));
|
|
|
record.set("bureau_id", claims.get("bureau_id"));
|
|
|
record.set("create_time", claims.get("create_time"));
|
|
|
}
|
|
|
return record;
|
|
|
}
|
|
|
} |