| | |
| | | package com.gkhy.exam.framework.web.service; |
| | | |
| | | import cn.hutool.crypto.digest.DigestUtil; |
| | | import com.gkhy.exam.common.api.ResultCode; |
| | | import com.gkhy.exam.common.constant.CacheConstant; |
| | | import com.gkhy.exam.common.domain.model.LoginUser; |
| | | import com.gkhy.exam.common.exception.ApiException; |
| | | import com.gkhy.exam.common.utils.RedisUtils; |
| | | import com.gkhy.exam.common.utils.StringUtils; |
| | | import io.jsonwebtoken.Claims; |
| | | import io.jsonwebtoken.ExpiredJwtException; |
| | | import io.jsonwebtoken.Jwts; |
| | | import io.jsonwebtoken.SignatureAlgorithm; |
| | | import lombok.extern.slf4j.Slf4j; |
| | |
| | | * 从token中获取JWT中的负载 |
| | | */ |
| | | private Claims getClaimsFromToken(String token) { |
| | | Claims claims = null; |
| | | try { |
| | | claims = Jwts.parser() |
| | | return Jwts.parser() |
| | | .setSigningKey(SECRET) |
| | | .parseClaimsJws(token) |
| | | .getBody(); |
| | | } catch (Exception e) { |
| | | log.error("JWT格式验证失败:{}", token); |
| | | } |
| | | return claims; |
| | | } |
| | | |
| | | /** |
| | |
| | | try { |
| | | Claims claims = getClaimsFromToken(token); |
| | | username = claims.getSubject(); |
| | | } catch (Exception e) { |
| | | username = null; |
| | | } catch (ExpiredJwtException e) { |
| | | log.error("JWT过期:{}", token); |
| | | throw new ApiException(ResultCode.UNAUTHORIZED); |
| | | } |
| | | return username; |
| | | } |
| | |
| | | String tagUsername = getUserNameFromToken(token); |
| | | String username=tagUsername.substring(0,tagUsername.lastIndexOf("_")); |
| | | if(StringUtils.isBlank(username)||!username.equals(userDetails.getUsername())){ |
| | | return false; |
| | | throw new ApiException(ResultCode.UNAUTHORIZED); |
| | | } |
| | | String tokenKey=redisUtils.generateKey(CacheConstant.SYS_USER_TOKEN+md5Encode(token)); |
| | | String userKey=redisUtils.generateKey(CacheConstant.SYS_USER_TOKEN+username); |
| | | String cacheToken= (String) redisUtils.get(tokenKey); |
| | | if(StringUtils.isBlank(cacheToken)||isTokenExpired(cacheToken)){ |
| | | return false; |
| | | throw new ApiException(ResultCode.UNAUTHORIZED); |
| | | } |
| | | if(isNeedUpdate(cacheToken)){ |
| | | String newToken=createToken(tagUsername); |
| | |
| | | } |
| | | return true; |
| | | } |
| | | |
| | | |
| | | |
| | | |
| | |
| | | |
| | | |
| | | |
| | | public void delTokenCache(HttpServletRequest request){ |
| | | String token=getToken(request); |
| | | String tokenKey=redisUtils.generateKey(CacheConstant.SYS_USER_TOKEN+md5Encode(token)); |
| | | redisUtils.del(tokenKey); |
| | | String tagUsername = getUserNameFromToken(token); |
| | | String username=tagUsername.substring(0,tagUsername.lastIndexOf("_")); |
| | | if(!StringUtils.isBlank(username)){ |
| | | String userKey=redisUtils.generateKey(CacheConstant.SYS_USER_TOKEN+username); |
| | | redisUtils.del(userKey); |
| | | } |
| | | } |
| | | |
| | | |
| | | } |