创建token
public class JWTUtil { private static final long EXPIRE_TIME = 3 * 60 * 1000;//默认3分钟 //私钥 private static final String TOKEN_SECRET = "privateKey"; public static String createToken(UserEntity userModel) { try { // 设置过期时间 Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); log.info(String.valueOf(date)); // 私钥和加密算法 Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); // 设置头部信息 Map<String, Object> header = new HashMap<>(2); header.put("Type", "Jwt"); header.put("alg", "HSA256"); // 返回token字符串 return JWT.create() .withHeader(header) .withClaim("username", userModel.getUsername()) .withExpiresAt(date) .sign(algorithm); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 检验token是否正确 * * @param **token** * @return */ public static boolean verifyToken(String token, String username) { log.info("验证token.."); try { Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); JWTVerifier verifier = JWT.require(algorithm) .withClaim("username",username).build(); // 验证不通过会抛出异常。 verifier.verify(token); return true; } catch (Exception e) { log.info("verifyToken = {}",e.getMessage()); return false; } } // 通过withClaim添加在token里面的数据都可以通过这种方式获取 public static String getUsername(String token){ DecodedJWT jwt = JWT.decode(token); String username = String.valueOf(jwt.getClaim("username")); if (StringUtils.hasLength(username)){ return username; } return null; } }
创建拦截器,拦截请求
@Slf4j @Component public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 当前端是通过在请求里面以 token="xxxx.xxx.zzz"的方式传递时,通过getHeader("token") // 的方式获取。 String token = request.getHeader("token"); log.info("token = {}",token); if (token == null){ setReturnInfo((HttpServletResponse) response,401,"请携带token"); return false; } // 解析token中的数据,JWTUtil.getUsername(); // 在这里可以通过findUserByUsername的方式从数据源中获取数据 // 假定登录用户是super, 并传递给此方法传递参数 if ( !JWTUtil.verifyToken(token,"super")){ setReturnInfo((HttpServletResponse) response,401,"token已过期"); return false; } return true; } private static void setReturnInfo(HttpServletResponse httpResponse,int status,String msg) throws IOException { log.info("token = null"); httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); httpResponse.setHeader("Access-Control-Allow-Origin", "*"); httpResponse.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=utf-8"); Map<String,String> result =new HashMap<>(); result.put("status",String.valueOf(status)); result.put("msg",msg); httpResponse.getWriter().print(JSONUtils.toJSONString(result)); // 前端可根据返回的status判断 } }
标签:username,return,String,验证,创建,token,static,public From: https://www.cnblogs.com/qxqbk/p/17349690.html