<!-- token -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
package com.example.mongodemo.util;
import com.example.mongodemo.code.JWTCode;
import io.jsonwebtoken.*;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class JWTUtil
{
private final static Logger logger = LoggerFactory.getLogger(JWTUtil.class);
private static final String JWT_SECRET = "fnarip*fudasfasfas5fa9sdf_jcewdiudsad56161bfof_1564d16";
public static String createJWT(String id, long ttlMillis) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
SecretKey key = generalKey();
JwtBuilder builder = Jwts.builder().setIssuedAt(new Date())
.claim("openId", id)
.signWith(signatureAlgorithm, key).setExpiration(new Date(nowMillis + ttlMillis));
return builder.compact();
}
private static SecretKey generalKey() {
String stringKey = JWT_SECRET;
byte[] encodedKey = Base64.decodeBase64(stringKey);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
public static Claims parseJWT(String jwt) throws RuntimeException {
SecretKey key = generalKey();
Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
return claims;
}
public static JWTCode judgeToken(String token){
try{
parseJWT(token);
}
catch (ExpiredJwtException e) {
logger.info("token过期!",e);
return JWTCode.OVERDUE;
} catch (Exception e) {
logger.info("token无效!",e);
return JWTCode.ERROR;
}
return JWTCode.SUCCESS;
}
public static String getOpenId(HttpServletRequest request){
String token = request.getHeader("token");
String openId = "";
try {
openId = parseJWT(token).get("openId").toString();
}
catch (Exception e){
System.out.println("tokn解析openId失败");
logger.error("tokn解析openId失败!",e);
return null;
}
return openId;
}
public static void main(String[] args) {
try {
String token = createJWT("asdfafas",TimeUnit.HOURS.toMillis(10));
Cookie cookie = StringUtil.setCookie("mwentoken",token, (int)TimeUnit.HOURS.toMillis(10)) ;
String value =StringUtil.getCookie("mwentoken",new Cookie[]{cookie});
System.out.println(value);
System.out.println(token);
System.out.println( parseJWT(value).get("openId").toString());
} catch (ExpiredJwtException e) {
System.out.println("token过期");
} catch (Exception e) {
System.out.println("token无效!!!");
e.printStackTrace();
}
}
}
package com.example.mongodemo.util;
import com.example.mongodemo.dto.ResultDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class StringUtil {
private static String TOKEN = "config";
public static String md5(String... args) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
String res = String.join("", args);
return new String(messageDigest.digest(res.getBytes()));
}
public static boolean checkSignature(String signature, String timestamp,
String nonce) {
String[] arr = new String[] { TOKEN, timestamp, nonce };
Arrays.sort(arr);
StringBuilder content = new StringBuilder();
for (String s : arr) {
content.append(s);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return tmpStr != null && tmpStr.equals(signature.toUpperCase());
}
private static String byteToStr(byte[] byteArray) {
StringBuilder strDigest = new StringBuilder();
for (int i = 0; i < byteArray.length; i++) {
strDigest.append(byteToHexStr(byteArray[i]));
}
return strDigest.toString();
}
private static String byteToHexStr(byte mByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
return new String(tempArr);
}
public static Cookie setCookie(String name, String value, int time) throws UnsupportedEncodingException {
String v = URLEncoder.encode(value, "utf-8");
Cookie cookie = new Cookie(name,v);
cookie.setMaxAge((int) time);
cookie.setPath("/");
return cookie;
}
public static String getCookie(String key,Cookie[] cookie) throws UnsupportedEncodingException {
for (int i=0;i<cookie.length;++i) {
if(cookie[i].getName().equals(key)) {
return URLDecoder.decode(cookie[i].getValue(),"utf-8");
}
}
return "NULL";
}
public static void renderJson(HttpServletResponse response, ResultDTO dto) {
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.print(dto.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
assert out != null;
out.close();
}
}
}
package com.example.mongodemo.code;
public enum JWTCode {
SUCCESS,ERROR,OVERDUE;
}