From 68c75b0650c2d2f409fe7b3686f96d8e641772db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E7=9A=93=E9=9B=AF?= <18868469283@qq.com> Date: Sun, 13 Jan 2019 21:00:55 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B7=A5=E5=85=B7=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/sock/mall/util/JsonUtil.java | 61 ++++++++ .../java/com/sock/mall/util/JwtTokenUtil.java | 134 ++++++++++++++++++ .../java/com/sock/mall/util/RequestUtil.java | 67 +++++++++ 3 files changed, 262 insertions(+) create mode 100644 代码库/mall-admin/src/main/java/com/sock/mall/util/JsonUtil.java create mode 100644 代码库/mall-admin/src/main/java/com/sock/mall/util/JwtTokenUtil.java create mode 100644 代码库/mall-admin/src/main/java/com/sock/mall/util/RequestUtil.java diff --git a/代码库/mall-admin/src/main/java/com/sock/mall/util/JsonUtil.java b/代码库/mall-admin/src/main/java/com/sock/mall/util/JsonUtil.java new file mode 100644 index 0000000..20fa06d --- /dev/null +++ b/代码库/mall-admin/src/main/java/com/sock/mall/util/JsonUtil.java @@ -0,0 +1,61 @@ +package com.macro.mall.util; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.List; + +/** + * Jackson jsonлͷл + */ +public class JsonUtil { + + // jackson + private static final ObjectMapper MAPPER = new ObjectMapper(); + + /** + * תjsonַ + */ + public static String objectToJson(Object data) { + try { + String string = MAPPER.writeValueAsString(data); + return string; + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + return null; + } + + /** + * jsonתΪ + * + * @param jsonData json + * @param beanType еobject + */ + public static T jsonToPojo(String jsonData, Class beanType) { + try { + T t = MAPPER.readValue(jsonData, beanType); + return t; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * jsonתpojolist + */ + public static List jsonToList(String jsonData, Class beanType) { + JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType); + try { + List list = MAPPER.readValue(jsonData, javaType); + return list; + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + +} \ No newline at end of file diff --git a/代码库/mall-admin/src/main/java/com/sock/mall/util/JwtTokenUtil.java b/代码库/mall-admin/src/main/java/com/sock/mall/util/JwtTokenUtil.java new file mode 100644 index 0000000..029b6cf --- /dev/null +++ b/代码库/mall-admin/src/main/java/com/sock/mall/util/JwtTokenUtil.java @@ -0,0 +1,134 @@ +package com.macro.mall.util; + +import io.jsonwebtoken.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * JwtTokenɵĹ + * JWT tokenĸʽheader.payload.signature + * headerĸʽ㷨tokenͣ + * {"alg": "HS512","typ": "JWT"} + * payloadĸʽûʱ䡢ʱ䣩 + * {"sub":"wang","created":1489079981393,"exp":1489684781} + * signature㷨 + * HMACSHA256(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret) + */ +@Component +public class JwtTokenUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class); + private static final String CLAIM_KEY_USERNAME = "sub"; + private static final String CLAIM_KEY_CREATED = "created"; + @Value("${jwt.secret}") + private String secret; + @Value("${jwt.expiration}") + private Long expiration; + + /** + * ݸJWTtoken + */ + private String generateToken(Map claims) { + return Jwts.builder() + .setClaims(claims) + .setExpiration(generateExpirationDate()) + .signWith(SignatureAlgorithm.HS512, secret) + .compact(); + } + + /** + * tokenлȡJWTеĸ + */ + private Claims getClaimsFromToken(String token) { + Claims claims = null; + try { + claims = Jwts.parser() + .setSigningKey(secret) + .parseClaimsJws(token) + .getBody(); + } catch (Exception e) { + LOGGER.info("JWTʽ֤ʧ:{}",token); + } + return claims; + } + + /** + * tokenĹʱ + */ + private Date generateExpirationDate() { + return new Date(System.currentTimeMillis() + expiration * 1000); + } + + /** + * tokenлȡ¼û + */ + public String getUserNameFromToken(String token) { + String username; + try { + Claims claims = getClaimsFromToken(token); + username = claims.getSubject(); + } catch (Exception e) { + username = null; + } + return username; + } + + /** + * ֤tokenǷЧ + * + * @param token ͻ˴token + * @param userDetails ݿвѯûϢ + */ + public boolean validateToken(String token, UserDetails userDetails) { + String username = getUserNameFromToken(token); + return username.equals(userDetails.getUsername()) && !isTokenExpired(token); + } + + /** + * жtokenǷѾʧЧ + */ + private boolean isTokenExpired(String token) { + Date expiredDate = getExpiredDateFromToken(token); + return expiredDate.before(new Date()); + } + + /** + * tokenлȡʱ + */ + private Date getExpiredDateFromToken(String token) { + Claims claims = getClaimsFromToken(token); + return claims.getExpiration(); + } + + /** + * ûϢtoken + */ + public String generateToken(UserDetails userDetails) { + Map claims = new HashMap<>(); + claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername()); + claims.put(CLAIM_KEY_CREATED, new Date()); + return generateToken(claims); + } + + /** + * жtokenǷԱˢ + */ + public boolean canRefresh(String token) { + return !isTokenExpired(token); + } + + /** + * ˢtoken + */ + public String refreshToken(String token) { + Claims claims = getClaimsFromToken(token); + claims.put(CLAIM_KEY_CREATED, new Date()); + return generateToken(claims); + } +} diff --git a/代码库/mall-admin/src/main/java/com/sock/mall/util/RequestUtil.java b/代码库/mall-admin/src/main/java/com/sock/mall/util/RequestUtil.java new file mode 100644 index 0000000..0d1e12d --- /dev/null +++ b/代码库/mall-admin/src/main/java/com/sock/mall/util/RequestUtil.java @@ -0,0 +1,67 @@ +package com.macro.mall.util; + +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.IOException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +/** + * request + */ +public class RequestUtil { + + /** + * Ƴrequestָ + */ + public String removeParam(HttpServletRequest request, String paramName) { + String queryString = ""; + Enumeration keys = request.getParameterNames(); + while (keys.hasMoreElements()) { + String key = (String) keys.nextElement(); + if (key.equals(paramName)) { + continue; + } + if ("".equals(queryString)) { + queryString = key + "=" + request.getParameter(key); + } else { + queryString += "&" + key + "=" + request.getParameter(key); + } + } + return queryString; + } + + /** + * ȡbasePath + */ + public static String getBasePath(HttpServletRequest request) { + StringBuffer basePath = new StringBuffer(); + String scheme = request.getScheme(); + String domain = request.getServerName(); + int port = request.getServerPort(); + basePath.append(scheme); + basePath.append("://"); + basePath.append(domain); + if("http".equalsIgnoreCase(scheme) && 80 != port) { + basePath.append(":").append(String.valueOf(port)); + } else if("https".equalsIgnoreCase(scheme) && port != 443) { + basePath.append(":").append(String.valueOf(port)); + } + return basePath.toString(); + } + + /** + * вתMap,for֧첽ص,ƽʱֱʹrequest.getParameterMap(),Map + */ + public static Map getParameterMap(HttpServletRequest request) { + Map result = new HashMap<>(); + Enumeration parameterNames = request.getParameterNames(); + while (parameterNames.hasMoreElements()) { + String parameterName = (String) parameterNames.nextElement(); + result.put(parameterName, request.getParameter(parameterName)); + } + return result; + } + +} \ No newline at end of file