|
|
package com.sztzjy.blockchainsmartclaim.config.security;
|
|
|
|
|
|
|
|
|
import cn.hutool.core.convert.Convert;
|
|
|
import com.sztzjy.blockchainsmartclaim.config.Constant;
|
|
|
import com.sztzjy.blockchainsmartclaim.config.exception.UnAuthorizedException;
|
|
|
import io.jsonwebtoken.*;
|
|
|
import io.jsonwebtoken.security.Keys;
|
|
|
import io.jsonwebtoken.security.SignatureException;
|
|
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
|
|
import org.springframework.stereotype.Component;
|
|
|
import org.springframework.util.StringUtils;
|
|
|
|
|
|
import javax.crypto.spec.SecretKeySpec;
|
|
|
import javax.servlet.http.HttpServletRequest;
|
|
|
import java.security.Key;
|
|
|
import java.security.SecureRandom;
|
|
|
import java.util.Date;
|
|
|
import java.util.List;
|
|
|
|
|
|
@Component
|
|
|
public class TokenProvider {
|
|
|
|
|
|
private final static String SECRET = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAghgsx+OLLThi7c+/HgCaRla8n+/QLHt++uscoK22dMeaVa3WJvRb5C5qtHGzj9V74pI96JpxdWWCN3Zr1QtanQIDAQABAkB2fWRUD1jVMBVS+rPctLnPNPMKTRdzXGv0SC5D3tRfGZqdcfsmZg8hzBVndHxngmwZS73d+hPjofcdefDDnXq1AiEAz/r1AMF7fweN70mbKgBJuTja37puJMsH2Szwrvb5jlcCIQCgIaLZ5d9J7OomL0NwH8ghba/xgBEpKzErfGbFnTfeKwIgc8ptczFFV1DWZb2eJIEqinOr79l0jwl2YiQSD+cyw1sCIHqxCvv1Wx5jPgy/zeYNE+Q5DMP3Ii7u/x+Yk436JiI9AiEAio84hFm44YTUuV7YCYsbyvnCn/vtcAaqZlczbeHlP1I=";
|
|
|
private final static long EXP_TIME = 1000 * 60 * 60 * 12;
|
|
|
|
|
|
private final static String SECRET_ZHIYUN = "zy_qkl_c1fqkcgekg1icu7ddp8qiho0u";
|
|
|
|
|
|
private final static String CURRENT_TO_ZHIYUN = "jVzvfoZU_eFN0CJcFARg0K6DlzTLa7oMWB7lV_y2s7bkv2Bem0281wEwlJp5afhsmM-Ynwvh3mAUTpwblGEz1A";
|
|
|
|
|
|
/**
|
|
|
* 解析jwtToken
|
|
|
*
|
|
|
* @param jwtToken jwtToken
|
|
|
* @return jwt解析对象
|
|
|
*/
|
|
|
public static JwtUser getJWTUser(String jwtToken) {
|
|
|
jwtToken = jwtToken.replace("Bearer ", "");
|
|
|
try {
|
|
|
Claims claims = Jwts.parser()
|
|
|
.setSigningKey(
|
|
|
new SecretKeySpec(
|
|
|
SECRET.getBytes("UTF-8"),
|
|
|
SignatureAlgorithm.HS512.getJcaName()
|
|
|
)
|
|
|
)
|
|
|
.parseClaimsJws(jwtToken)
|
|
|
.getBody();
|
|
|
|
|
|
JwtUser jwtUser = new JwtUser();
|
|
|
jwtUser.setName(claims.get("name")==null?"":claims.get("name").toString());
|
|
|
jwtUser.setUserId(claims.get("userId")==null?"":claims.get("userId").toString());
|
|
|
if (claims.get("roleId")!=null){
|
|
|
jwtUser.setRoleId(Integer.valueOf(claims.get("roleId")==null?"0":claims.get("roleId").toString()));
|
|
|
}
|
|
|
|
|
|
if (claims.get("classId")!=null){
|
|
|
jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?"0":claims.get("classId").toString()));
|
|
|
}
|
|
|
|
|
|
if (claims.get("schoolId")!=null){
|
|
|
jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId")==null?"0":claims.get("schoolId").toString()));
|
|
|
}
|
|
|
|
|
|
jwtUser.setUsername(claims.get("username")==null?"":claims.get("username").toString());
|
|
|
jwtUser.setSchoolName(claims.get("schoolName") == null ? "" : claims.get("schoolName").toString());
|
|
|
jwtUser.setClassName(claims.get("className") == null ? "" : claims.get("className").toString());
|
|
|
jwtUser.setStudentId(claims.get("studentId") == null ? "" : claims.get("studentId").toString());
|
|
|
// jwtUser.setTeamCompanyId(claims.get("teamCompanyId") == null ? null : Convert.toLong(claims.get("teamCompanyId")));
|
|
|
// jwtUser.setUserCompanyId(claims.get("userCompanyId") == null ? null : Convert.toLong(claims.get("userCompanyId")));
|
|
|
// jwtUser.setTeamPracticalTaskId(claims.get("teamPracticalTaskId") == null ? null : Convert.toLong(claims.get("teamPracticalTaskId")));
|
|
|
jwtUser.setAuthorityCodes((List<String>) claims.get("authorityCodes"));
|
|
|
// 本系统 createToken 恒定写入 studentId claim;外部平台 token 无此字段,用于区分票源
|
|
|
jwtUser.setLocalIssued(claims.containsKey("studentId"));
|
|
|
return jwtUser;
|
|
|
} catch (ExpiredJwtException e1) {
|
|
|
throw new ExpiredJwtException(null, null, "token过期");
|
|
|
} catch (UnsupportedJwtException e2) {
|
|
|
throw new UnsupportedJwtException("不支持的token");
|
|
|
} catch (MalformedJwtException e3) {
|
|
|
throw new MalformedJwtException("token格式错误");
|
|
|
} catch (SignatureException e4) {
|
|
|
throw new SignatureException("签名失败");
|
|
|
} catch (Exception e) {
|
|
|
throw new UnAuthorizedException("无效token");
|
|
|
}
|
|
|
}
|
|
|
|
|
|
|
|
|
public static JwtUser getJWTUserOne(String jwtToken) {
|
|
|
jwtToken = jwtToken.replace("Bearer ", "");
|
|
|
try {
|
|
|
Claims claims = Jwts.parser()
|
|
|
.setSigningKey(
|
|
|
new SecretKeySpec(
|
|
|
SECRET.getBytes("UTF-8"),
|
|
|
SignatureAlgorithm.HS512.getJcaName()
|
|
|
)
|
|
|
)
|
|
|
.parseClaimsJws(jwtToken)
|
|
|
.getBody();
|
|
|
|
|
|
// JwtUser jwtUser = new JwtUser();
|
|
|
// jwtUser.setName(claims.get("name")==null?"":claims.get("name").toString());
|
|
|
// jwtUser.setUserId(claims.get("userId")==null?"":claims.get("userId").toString());
|
|
|
// jwtUser.setRoleId(Integer.valueOf(claims.get("roleId")==null?"0":claims.get("roleId").toString()));
|
|
|
// jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?"0":claims.get("classId").toString()));
|
|
|
// jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId")==null?"0":claims.get("schoolId").toString()));
|
|
|
// jwtUser.setUsername(claims.get("username")==null?"":claims.get("username").toString());
|
|
|
// jwtUser.setAuthorityCodes((List<String>) claims.get("authorityCodes"));
|
|
|
|
|
|
|
|
|
JwtUser jwtUser = new JwtUser();
|
|
|
jwtUser.setName(claims.get("name")==null?null:claims.get("name").toString());
|
|
|
jwtUser.setUserId(claims.get("userId")==null?null:claims.get("userId").toString());
|
|
|
if(claims.get("roleid")!=null){
|
|
|
jwtUser.setRoleId(Integer.valueOf(claims.get("roleid")==null?"4":claims.get("roleid").toString()));
|
|
|
}
|
|
|
|
|
|
if(claims.get("classId")!=null){
|
|
|
jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?null:claims.get("classId").toString()));
|
|
|
}
|
|
|
//jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?null:claims.get("classId").toString()));
|
|
|
if(claims.get("schoolId")!=null){
|
|
|
// jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?null:claims.get("classId").toString()));
|
|
|
jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId")==null?"0":claims.get("schoolId").toString()));
|
|
|
}
|
|
|
|
|
|
jwtUser.setUsername(claims.get("username")==null?null:claims.get("username").toString());
|
|
|
jwtUser.setClassName(claims.get("class")==null?null:claims.get("class").toString());
|
|
|
jwtUser.setStudentId(claims.get("studentNo")==null?null:claims.get("studentNo").toString());
|
|
|
jwtUser.setSchoolName(claims.get("school")==null?null:claims.get("school").toString());
|
|
|
jwtUser.setMajorName(claims.get("major")==null?null:claims.get("major").toString());
|
|
|
jwtUser.setPassword(claims.get("password")==null?"123qwe":claims.get("password").toString());
|
|
|
|
|
|
return jwtUser;
|
|
|
} catch (ExpiredJwtException e1) {
|
|
|
throw new ExpiredJwtException(null, null, "token过期");
|
|
|
} catch (UnsupportedJwtException e2) {
|
|
|
throw new UnsupportedJwtException("不支持的token");
|
|
|
} catch (MalformedJwtException e3) {
|
|
|
throw new MalformedJwtException("token格式错误");
|
|
|
} catch (SignatureException e4) {
|
|
|
throw new SignatureException("签名失败");
|
|
|
} catch (Exception e) {
|
|
|
throw new UnAuthorizedException("无效token");
|
|
|
}
|
|
|
}
|
|
|
|
|
|
|
|
|
public static String createToken(JwtUser jwtUser) {
|
|
|
Key key = Keys.hmacShaKeyFor(SECRET.getBytes());
|
|
|
Date expiration = new Date(System.currentTimeMillis() + EXP_TIME);
|
|
|
return Jwts.builder()
|
|
|
.claim("userId", jwtUser.getUserId())
|
|
|
.claim("roleId", jwtUser.getRoleId())
|
|
|
.claim("name", jwtUser.getName())
|
|
|
.claim("classId", jwtUser.getClassId())
|
|
|
.claim("schoolId", jwtUser.getSchoolId())
|
|
|
.claim("username", jwtUser.getUsername())
|
|
|
.claim("studentId", jwtUser.getStudentId())
|
|
|
.claim("authorityCodes", jwtUser.getAuthorityCodes())
|
|
|
.claim("schoolName", jwtUser.getSchoolName())
|
|
|
.claim("className", jwtUser.getClassName())
|
|
|
// .claim("teamCompanyId", jwtUser.getTeamCompanyId())
|
|
|
// .claim("userCompanyId", jwtUser.getUserCompanyId())
|
|
|
// .claim("teamPracticalTaskId", jwtUser.getTeamPracticalTaskId())
|
|
|
.setIssuedAt(new Date(System.currentTimeMillis()))
|
|
|
.setExpiration(expiration)
|
|
|
.signWith(key, SignatureAlgorithm.HS512)
|
|
|
.compact();
|
|
|
}
|
|
|
|
|
|
public static String createZHIYUNToken(JwtUser jwtUser) {
|
|
|
Key key = Keys.hmacShaKeyFor(CURRENT_TO_ZHIYUN.getBytes());
|
|
|
Date expiration = new Date(System.currentTimeMillis() + EXP_TIME);
|
|
|
return Jwts.builder()
|
|
|
.claim("userId", jwtUser.getUserId())
|
|
|
.claim("roleId", jwtUser.getRoleId())
|
|
|
.claim("name", jwtUser.getName())
|
|
|
.claim("classId", jwtUser.getClassId())
|
|
|
.claim("schoolId", jwtUser.getSchoolId())
|
|
|
.claim("username", jwtUser.getUsername())
|
|
|
.claim("majorId", jwtUser.getMajorId())
|
|
|
.setIssuedAt(new Date(System.currentTimeMillis()))
|
|
|
.setExpiration(expiration)
|
|
|
.signWith(key, SignatureAlgorithm.HS512)
|
|
|
.compact();
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 解析智云平台的token
|
|
|
*/
|
|
|
public static JwtUser getJWTUserByZhiYun(String token) {
|
|
|
// token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InR6czAwMSIsInVzZXJJZCI6" +
|
|
|
// "NDg3LCJuYW1lIjoi5Zev5ZO8IiwicGFzc3dvcmQiOiIxMjNxd2UiLCJyb2xlSWQiOjQsInNjaG9" +
|
|
|
// "vbElkIjoxLCJzY2hvb2xOYW1lIjoi5aSp5oup5aSn5a2mIi" +
|
|
|
// "wiY2xhc3NJZCI6MjAsImNsYXNzTmFtZSI6IuWkqeaLqea8lOekujHnj60iLCJsZXZlbElkIjo1fQ" +
|
|
|
// ".5fVdEtC7eDC2HuUX8jnodomdTUw_nPOzkOJUXCw5Fqc";
|
|
|
try {
|
|
|
Claims claims = Jwts.parser()
|
|
|
.setSigningKey(Keys.hmacShaKeyFor(SECRET_ZHIYUN.getBytes(java.nio.charset.StandardCharsets.UTF_8)))
|
|
|
.parseClaimsJws(token)
|
|
|
.getBody();
|
|
|
|
|
|
JwtUser jwtUser = new JwtUser();
|
|
|
jwtUser.setName(claims.get("name")==null?null:claims.get("name").toString());
|
|
|
jwtUser.setUserId(claims.get("userId")==null?null:claims.get("userId").toString());
|
|
|
if(claims.get("roleid")!=null){
|
|
|
jwtUser.setRoleId(Integer.valueOf(claims.get("roleid")==null?"4":claims.get("roleid").toString()));
|
|
|
}
|
|
|
|
|
|
if(claims.get("classId")!=null){
|
|
|
jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?null:claims.get("classId").toString()));
|
|
|
}
|
|
|
//jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?null:claims.get("classId").toString()));
|
|
|
if(claims.get("schoolId")!=null){
|
|
|
// jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?null:claims.get("classId").toString()));
|
|
|
jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId")==null?"0":claims.get("schoolId").toString()));
|
|
|
}
|
|
|
|
|
|
|
|
|
jwtUser.setUsername(claims.get("username")==null?null:claims.get("username").toString());
|
|
|
jwtUser.setClassName(claims.get("class")==null?null:claims.get("class").toString());
|
|
|
jwtUser.setStudentId(claims.get("studentNo")==null?null:claims.get("studentNo").toString());
|
|
|
jwtUser.setSchoolName(claims.get("school")==null?null:claims.get("school").toString());
|
|
|
jwtUser.setMajorName(claims.get("major")==null?null:claims.get("major").toString());
|
|
|
jwtUser.setPassword(claims.get("password")==null?null:claims.get("password").toString());
|
|
|
|
|
|
return jwtUser;
|
|
|
} catch (Exception e) {
|
|
|
throw new UnAuthorizedException("token解析失败");
|
|
|
}
|
|
|
}
|
|
|
|
|
|
|
|
|
//生成智云平台32字节密钥
|
|
|
public static void main(String[] args) {
|
|
|
// String prefix = "zy_wh_mnjy_";
|
|
|
// String generatedKey = generateKey(prefix);
|
|
|
// System.out.println("Generated Key: " + generatedKey);
|
|
|
// getJWTUserByZhiYun(null);
|
|
|
|
|
|
|
|
|
//生成一个新的长度为512字节的随机密钥供智云平台解析token
|
|
|
// int keyLength = 512; // 根据您的要求进行调整
|
|
|
// KeyGenerator keyGenerator;
|
|
|
// try {
|
|
|
// keyGenerator = KeyGenerator.getInstance("HmacSHA512");
|
|
|
// keyGenerator.init(keyLength);
|
|
|
// SecretKey secretKey = keyGenerator.generateKey();
|
|
|
// byte[] secretBytes = secretKey.getEncoded();
|
|
|
// String secret = Base64.getUrlEncoder().withoutPadding().encodeToString(secretBytes);
|
|
|
//
|
|
|
// System.out.println("Generated Secret: " + secret);
|
|
|
// } catch (NoSuchAlgorithmException e) {
|
|
|
// e.printStackTrace();
|
|
|
// }
|
|
|
|
|
|
JwtUser user = new JwtUser();
|
|
|
user.setUserId("486");
|
|
|
user.setRoleId(3);
|
|
|
user.setUsername("tzt006");
|
|
|
user.setSchoolId(1);
|
|
|
user.setSchoolName("天择大学");
|
|
|
user.setCollegeId(1);
|
|
|
user.setCollegeName("演示学院");
|
|
|
user.setMajorId(1);
|
|
|
user.setMajorName("产品演示专业");
|
|
|
String token = createZHIYUNToken(user);
|
|
|
System.out.println(token);
|
|
|
}
|
|
|
|
|
|
public static String generateKey(String prefix) {
|
|
|
String characters = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
|
SecureRandom random = new SecureRandom();
|
|
|
|
|
|
StringBuilder keyBuilder = new StringBuilder(prefix);
|
|
|
while (keyBuilder.length() < 32) {
|
|
|
int randomIndex = random.nextInt(characters.length());
|
|
|
char randomChar = characters.charAt(randomIndex);
|
|
|
keyBuilder.append(randomChar);
|
|
|
}
|
|
|
return keyBuilder.toString();
|
|
|
}
|
|
|
|
|
|
|
|
|
/**
|
|
|
* 获取当前用户信息
|
|
|
*
|
|
|
* @param request request
|
|
|
* @return JwtUser
|
|
|
*/
|
|
|
public static JwtUser getJWTUser(HttpServletRequest request) {
|
|
|
if (!(request.getUserPrincipal() instanceof UsernamePasswordAuthenticationToken)) {
|
|
|
throw new UnAuthorizedException("身份认证失败");
|
|
|
}
|
|
|
String jwtToken = request.getHeader(Constant.AUTHORIZATION);
|
|
|
if (StringUtils.hasText(jwtToken)) {
|
|
|
return getJWTUser(jwtToken);
|
|
|
}
|
|
|
throw new UnAuthorizedException("身份认证失败");
|
|
|
}
|
|
|
|
|
|
}
|