| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316 |
- package com.ydtech.security.utils;
- import com.ydtech.security.GrantedAuthorityImpl;
- import com.ydtech.security.JwtAuthenticatioToken;
- import io.jsonwebtoken.Claims;
- import io.jsonwebtoken.Jwts;
- import io.jsonwebtoken.SignatureAlgorithm;
- import org.apache.catalina.User;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.context.SecurityContextHolder;
- import javax.servlet.http.HttpServletRequest;
- import java.io.Serializable;
- import java.util.*;
- /**
- * JWT工具类
- *
- * @author Louis
- * @date Jun 29, 2019
- */
- public class JwtTokenUtils implements Serializable {
- private static final long serialVersionUID = 1L;
- /**
- * 用户名称
- */
- private static final String USERNAME = Claims.SUBJECT;
- /**
- * 创建时间
- */
- private static final String CREATED = "created";
- /**
- * 权限列表
- */
- private static final String AUTHORITIES = "authorities";
- /**
- * 密钥
- */
- private static final String SECRET = "abcdefgh";
- /**
- * 有效期12小时
- */
- private static final long EXPIRE_TIME = 12 * 60 * 60 * 1000;
- /**
- * deptId
- */
- private static final String DEPTID = "deptId";
- /**
- * userId
- */
- private static final String USERID = "id";
- /**
- * 生成令牌
- *
- * @param authentication 用户
- * @return 令牌
- */
- public static String generateToken(Authentication authentication) {
- Map<String, Object> claims = new HashMap<>(3);
- claims.put(USERNAME, SecurityUtils.getUsername(authentication));
- claims.put(CREATED, new Date());
- claims.put(DEPTID, SecurityUtils.getDeptId());
- claims.put(AUTHORITIES, authentication.getAuthorities());
- claims.put(USERID, SecurityUtils.getUserId());
- return generateToken(claims);
- }
- /**
- * 从数据声明生成令牌
- *
- * @param claims 数据声明
- * @return 令牌
- */
- private static String generateToken(Map<String, Object> claims) {
- Date expirationDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
- return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, SECRET).compact();
- }
- /**
- * 从令牌中获取用户名
- *
- * @param token 令牌
- * @return 用户名
- */
- public static String getUsernameFromToken(String token) {
- String username;
- try {
- Claims claims = getClaimsFromToken(token);
- username = claims.getSubject();
- } catch (Exception e) {
- username = null;
- }
- return username;
- }
- /**
- * 根据请求令牌获取登录认证信息
- *
- * @param request 令牌
- * @return 用户名
- */
- public static Authentication getAuthenticationeFromToken(HttpServletRequest request) {
- Authentication authentication = null;
- // 获取请求携带的令牌
- String token = JwtTokenUtils.getToken(request);
- if (token != null) {
- // 请求令牌不能为空
- if (SecurityUtils.getAuthentication() == null) {
- // 上下文中Authentication为空
- Claims claims = getClaimsFromToken(token);
- if (claims == null) {
- return null;
- }
- String username = claims.getSubject();
- if (username == null) {
- return null;
- }
- if (isTokenExpired(token)) {
- return null;
- }
- Object authors = claims.get(AUTHORITIES);
- List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
- if (authors != null && authors instanceof List) {
- for (Object object : (List) authors) {
- authorities.add(new GrantedAuthorityImpl((String) ((Map) object).get("authority")));
- }
- }
- authentication = new JwtAuthenticatioToken(username, null, authorities, token);
- } else {
- String username = SecurityUtils.getByUsername();
- if (username == null) {
- return null;
- }
- if (validateToken(token, username)) {
- // 如果上下文中Authentication非空,且请求令牌合法,直接返回当前登录认证信息
- authentication = SecurityContextHolder.getContext().getAuthentication();
- }
- }
- }
- return authentication;
- }
- /**
- * 从令牌中获取数据声明
- *
- * @param token 令牌
- * @return 数据声明
- */
- private static Claims getClaimsFromToken(String token) {
- Claims claims;
- try {
- claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
- } catch (Exception e) {
- claims = null;
- }
- return claims;
- }
- /**
- * 验证令牌
- *
- * @param token
- * @param username
- * @return
- */
- public static Boolean validateToken(String token, String username) {
- String userName = getUsernameFromToken(token);
- return (userName.equals(username) && !isTokenExpired(token));
- }
- /**
- * 刷新令牌
- *
- * @param token
- * @return
- */
- public static String refreshToken(String token) {
- String refreshedToken;
- try {
- Claims claims = getClaimsFromToken(token);
- claims.put(CREATED, new Date());
- refreshedToken = generateToken(claims);
- } catch (Exception e) {
- refreshedToken = null;
- }
- return refreshedToken;
- }
- /**
- * 判断令牌是否过期
- *
- * @param token 令牌
- * @return 是否过期
- */
- public static Boolean isTokenExpired(String token) {
- try {
- Claims claims = getClaimsFromToken(token);
- Date expiration = claims.getExpiration();
- return expiration.before(new Date());
- } catch (Exception e) {
- return false;
- }
- }
- /**
- * 获取请求token
- *
- * @param request
- * @return
- */
- public static String getToken(HttpServletRequest request) {
- String token = request.getHeader("Authorization");
- String tokenHead = "Bearer ";
- if (token == null) {
- token = request.getHeader("token");
- } else if (token.contains(tokenHead)) {
- token = token.substring(tokenHead.length());
- }
- if ("".equals(token)) {
- token = null;
- }
- return token;
- }
- /**
- * 从请求中获取用户名
- *
- * @param request
- * @return 用户名
- */
- public static String getUsernameFromRequest(HttpServletRequest request) {
- String username;
- try {
- String token = getToken(request);
- username = getUsernameFromToken(token);
- } catch (Exception e) {
- username = null;
- }
- return username;
- }
- /**
- * 从请求中获取部门id
- *
- * @param request
- * @return 部门id
- */
- public static String getDeptIdFromRequest(HttpServletRequest request) {
- String deptId;
- try {
- String token = getToken(request);
- deptId = getDeptIdFromToken(token);
- } catch (Exception e) {
- deptId = null;
- }
- return deptId;
- }
- /**
- * 从请求中获取用户id
- *
- * @param request
- * @return 用户id
- */
- public static String getUserIdFromRequest(HttpServletRequest request) {
- String userId;
- try {
- String token = getToken(request);
- userId = getUserIdFromToken(token);
- } catch (Exception e) {
- userId = null;
- }
- return userId;
- }
- /**
- * 从令牌中获取部门id
- *
- * @return
- */
- public static String getDeptIdFromToken(String token) {
- String deptId = null;
- try {
- Claims claims = getClaimsFromToken(token);
- deptId = (String) claims.get(DEPTID);
- } catch (Exception e) {
- deptId = null;
- }
- return deptId;
- }
- /**
- * 从令牌中获取用户id
- *
- * @return
- */
- public static String getUserIdFromToken(String token) {
- String userId = null;
- try {
- Claims claims = getClaimsFromToken(token);
- userId = (String) claims.get(USERID);
- } catch (Exception e) {
- userId = null;
- }
- return userId;
- }
- }
|