1.增加JWT依赖
<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.8.1</version> </dependency>
2.JWT工具类
public class TokenUtil { //token 密钥 private static final String TOKEN_SECRET = "27f56a1ca0a347618ff39c7fdf9ab684"; //15分钟超时时间 private static final long OUT_TIME = 150 * 60 * 1000; private static Logger log = LoggerFactory.getLogger(TokenUtil.class); /** 加密 * @param userId * @return */ public static String sign(String userId) { try { Date expiration_time = new Date(System.currentTimeMillis() + OUT_TIME); Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); Map<String, Object> headerMap = new HashMap<>(2); headerMap.put("type", "JWT"); headerMap.put("alg", "HS256"); return JWT.create().withHeader(headerMap).withClaim("userId", userId).withExpiresAt(expiration_time).sign(algorithm); } catch (Exception e) { log.error(e.getMessage()); return null; } } /** 解密 * @param token * @return */ public static Map<String, Claim> verifyToken(String token) { DecodedJWT decodedJWT=null; try { JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build(); decodedJWT = verifier.verify(token); log.info("超时时间:"+decodedJWT.getExpiresAt()); log.info("载体信息:"+decodedJWT.getClaim("userId").asString()); log.info("算法:"+decodedJWT.getAlgorithm()); }catch (Exception e){ //解码异常则抛出异常 log.error(e.getMessage()); return null; } return decodedJWT.getClaims(); } }
3.使用拦截器拦截请求,以及springboot注入拦截器
@Component public class TokenInterceptor implements HandlerInterceptor { private Logger logger = LoggerFactory.getLogger(TokenInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getHeader("token"); //token验证 if (!StringEmpty.IsEmpty(token)) { Map<String, Claim> claimMap = TokenUtil.verifyToken(token); if (claimMap!=null){ //账户操作... return true; } else { //验证错误,跳转到错误页面 response.sendRedirect(request.getContextPath()+"/twjd/error"); return false; } } return false; } }
@Configuration public class InterceptorConfig implements WebMvcConfigurer { @Autowired private TokenInterceptor tokenInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { InterceptorRegistration registration = registry.addInterceptor(tokenInterceptor); //拦截配置 registration.addPathPatterns("/twjd/**"); //排除配置 registration.excludePathPatterns("/twjd/login","/twjd/error"); } }
4.用户登陆操作,验证用户是否携带token,如果携带token则验证
/** * 用户登陆 * * @param sysusers * @param request * @param response * @return */ @RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public HashMap<String, String> login(Sysuser sysusers, HttpServletRequest request, HttpServletResponse response) { Sysuser user = logService.getUser(sysusers.getName()); HashMap<String, String> tokenMap = new HashMap<>(1); //用户存且密码正确在则颁发token if (null != user && user.getPassword().equals(sysusers.getPassword())) { if (!StringEmpty.IsEmpty(user.getPassword())) { response.setHeader("token", TokenUtil.sign(user.getID())); tokenMap.put("token", TokenUtil.sign(user.getID())); //存入redis中设置过期时间1天 if (!redisUtil.exists(sysusers.getName())) { logger.info("活跃用户+1:" + sysusers.getName()); redisUtil.set(sysusers.getName(), sysusers, 1, TimeUnit.DAYS); } return tokenMap; } } else { tokenMap.put("token", "不存在此用户"); } return tokenMap; }