JwtTokenUtils.java 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package com.ydtech.security.utils;
  2. import com.ydtech.security.GrantedAuthorityImpl;
  3. import com.ydtech.security.JwtAuthenticatioToken;
  4. import io.jsonwebtoken.Claims;
  5. import io.jsonwebtoken.Jwts;
  6. import io.jsonwebtoken.SignatureAlgorithm;
  7. import org.apache.catalina.User;
  8. import org.springframework.security.core.Authentication;
  9. import org.springframework.security.core.GrantedAuthority;
  10. import org.springframework.security.core.context.SecurityContextHolder;
  11. import javax.servlet.http.HttpServletRequest;
  12. import java.io.Serializable;
  13. import java.util.*;
  14. /**
  15. * JWT工具类
  16. *
  17. * @author Louis
  18. * @date Jun 29, 2019
  19. */
  20. public class JwtTokenUtils implements Serializable {
  21. private static final long serialVersionUID = 1L;
  22. /**
  23. * 用户名称
  24. */
  25. private static final String USERNAME = Claims.SUBJECT;
  26. /**
  27. * 创建时间
  28. */
  29. private static final String CREATED = "created";
  30. /**
  31. * 权限列表
  32. */
  33. private static final String AUTHORITIES = "authorities";
  34. /**
  35. * 密钥
  36. */
  37. private static final String SECRET = "abcdefgh";
  38. /**
  39. * 有效期12小时
  40. */
  41. private static final long EXPIRE_TIME = 12 * 60 * 60 * 1000;
  42. /**
  43. * deptId
  44. */
  45. private static final String DEPTID = "deptId";
  46. /**
  47. * userId
  48. */
  49. private static final String USERID = "id";
  50. /**
  51. * 生成令牌
  52. *
  53. * @param authentication 用户
  54. * @return 令牌
  55. */
  56. public static String generateToken(Authentication authentication) {
  57. Map<String, Object> claims = new HashMap<>(3);
  58. claims.put(USERNAME, SecurityUtils.getUsername(authentication));
  59. claims.put(CREATED, new Date());
  60. claims.put(DEPTID, SecurityUtils.getDeptId());
  61. claims.put(AUTHORITIES, authentication.getAuthorities());
  62. claims.put(USERID, SecurityUtils.getUserId());
  63. return generateToken(claims);
  64. }
  65. /**
  66. * 从数据声明生成令牌
  67. *
  68. * @param claims 数据声明
  69. * @return 令牌
  70. */
  71. private static String generateToken(Map<String, Object> claims) {
  72. Date expirationDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
  73. return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, SECRET).compact();
  74. }
  75. /**
  76. * 从令牌中获取用户名
  77. *
  78. * @param token 令牌
  79. * @return 用户名
  80. */
  81. public static String getUsernameFromToken(String token) {
  82. String username;
  83. try {
  84. Claims claims = getClaimsFromToken(token);
  85. username = claims.getSubject();
  86. } catch (Exception e) {
  87. username = null;
  88. }
  89. return username;
  90. }
  91. /**
  92. * 根据请求令牌获取登录认证信息
  93. *
  94. * @param request 令牌
  95. * @return 用户名
  96. */
  97. public static Authentication getAuthenticationeFromToken(HttpServletRequest request) {
  98. Authentication authentication = null;
  99. // 获取请求携带的令牌
  100. String token = JwtTokenUtils.getToken(request);
  101. if (token != null) {
  102. // 请求令牌不能为空
  103. if (SecurityUtils.getAuthentication() == null) {
  104. // 上下文中Authentication为空
  105. Claims claims = getClaimsFromToken(token);
  106. if (claims == null) {
  107. return null;
  108. }
  109. String username = claims.getSubject();
  110. if (username == null) {
  111. return null;
  112. }
  113. if (isTokenExpired(token)) {
  114. return null;
  115. }
  116. Object authors = claims.get(AUTHORITIES);
  117. List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
  118. if (authors != null && authors instanceof List) {
  119. for (Object object : (List) authors) {
  120. authorities.add(new GrantedAuthorityImpl((String) ((Map) object).get("authority")));
  121. }
  122. }
  123. authentication = new JwtAuthenticatioToken(username, null, authorities, token);
  124. } else {
  125. String username = SecurityUtils.getByUsername();
  126. if (username == null) {
  127. return null;
  128. }
  129. if (validateToken(token, username)) {
  130. // 如果上下文中Authentication非空,且请求令牌合法,直接返回当前登录认证信息
  131. authentication = SecurityContextHolder.getContext().getAuthentication();
  132. }
  133. }
  134. }
  135. return authentication;
  136. }
  137. /**
  138. * 从令牌中获取数据声明
  139. *
  140. * @param token 令牌
  141. * @return 数据声明
  142. */
  143. private static Claims getClaimsFromToken(String token) {
  144. Claims claims;
  145. try {
  146. claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
  147. } catch (Exception e) {
  148. claims = null;
  149. }
  150. return claims;
  151. }
  152. /**
  153. * 验证令牌
  154. *
  155. * @param token
  156. * @param username
  157. * @return
  158. */
  159. public static Boolean validateToken(String token, String username) {
  160. String userName = getUsernameFromToken(token);
  161. return (userName.equals(username) && !isTokenExpired(token));
  162. }
  163. /**
  164. * 刷新令牌
  165. *
  166. * @param token
  167. * @return
  168. */
  169. public static String refreshToken(String token) {
  170. String refreshedToken;
  171. try {
  172. Claims claims = getClaimsFromToken(token);
  173. claims.put(CREATED, new Date());
  174. refreshedToken = generateToken(claims);
  175. } catch (Exception e) {
  176. refreshedToken = null;
  177. }
  178. return refreshedToken;
  179. }
  180. /**
  181. * 判断令牌是否过期
  182. *
  183. * @param token 令牌
  184. * @return 是否过期
  185. */
  186. public static Boolean isTokenExpired(String token) {
  187. try {
  188. Claims claims = getClaimsFromToken(token);
  189. Date expiration = claims.getExpiration();
  190. return expiration.before(new Date());
  191. } catch (Exception e) {
  192. return false;
  193. }
  194. }
  195. /**
  196. * 获取请求token
  197. *
  198. * @param request
  199. * @return
  200. */
  201. public static String getToken(HttpServletRequest request) {
  202. String token = request.getHeader("Authorization");
  203. String tokenHead = "Bearer ";
  204. if (token == null) {
  205. token = request.getHeader("token");
  206. } else if (token.contains(tokenHead)) {
  207. token = token.substring(tokenHead.length());
  208. }
  209. if ("".equals(token)) {
  210. token = null;
  211. }
  212. return token;
  213. }
  214. /**
  215. * 从请求中获取用户名
  216. *
  217. * @param request
  218. * @return 用户名
  219. */
  220. public static String getUsernameFromRequest(HttpServletRequest request) {
  221. String username;
  222. try {
  223. String token = getToken(request);
  224. username = getUsernameFromToken(token);
  225. } catch (Exception e) {
  226. username = null;
  227. }
  228. return username;
  229. }
  230. /**
  231. * 从请求中获取部门id
  232. *
  233. * @param request
  234. * @return 部门id
  235. */
  236. public static String getDeptIdFromRequest(HttpServletRequest request) {
  237. String deptId;
  238. try {
  239. String token = getToken(request);
  240. deptId = getDeptIdFromToken(token);
  241. } catch (Exception e) {
  242. deptId = null;
  243. }
  244. return deptId;
  245. }
  246. /**
  247. * 从请求中获取用户id
  248. *
  249. * @param request
  250. * @return 用户id
  251. */
  252. public static String getUserIdFromRequest(HttpServletRequest request) {
  253. String userId;
  254. try {
  255. String token = getToken(request);
  256. userId = getUserIdFromToken(token);
  257. } catch (Exception e) {
  258. userId = null;
  259. }
  260. return userId;
  261. }
  262. /**
  263. * 从令牌中获取部门id
  264. *
  265. * @return
  266. */
  267. public static String getDeptIdFromToken(String token) {
  268. String deptId = null;
  269. try {
  270. Claims claims = getClaimsFromToken(token);
  271. deptId = (String) claims.get(DEPTID);
  272. } catch (Exception e) {
  273. deptId = null;
  274. }
  275. return deptId;
  276. }
  277. /**
  278. * 从令牌中获取用户id
  279. *
  280. * @return
  281. */
  282. public static String getUserIdFromToken(String token) {
  283. String userId = null;
  284. try {
  285. Claims claims = getClaimsFromToken(token);
  286. userId = (String) claims.get(USERID);
  287. } catch (Exception e) {
  288. userId = null;
  289. }
  290. return userId;
  291. }
  292. }