2.创建用户和签名实体类com.auth0 java-jwt3.18.2 io.jsonwebtoken jjwt0.9.1 com.alibaba fastjson1.2.79
- 用户信息表
@Data @AllArgsConstructor @NoArgsConstructor public class SysUser { private String id; private String name; private String password; private String webToken; }
- 签名信息表
@Data @Component public class TokenInfo implements Serializable { private static final long serialVersionUID = -3574431640051881254L; private String salt; private String name; private int expiresSecond; }3.token配置
@Slf4j @Component public class TokenConfiguration extends RuntimeException implements HandlerInterceptor { private final static TokenInfo tokenInfo = new TokenInfo(); private static final String KEY = "token"; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("拦截请求" + request.getRequestURI()); // 如果不是映射到方法直接通过,可以访问资源. if (!(handler instanceof HandlerMethod)) { return true; } //为空就返回错误 String token = request.getHeader(KEY); if (StringUtils.isEmpty(token)) { log.error("token信息不存在{}",token); throw new RuntimeException(); } log.info("token:{}",token); //判断token信息是否正确 parseToken(token); log.info("token解析正确!"); //判断是否过期 Long tokenOutTime = getWebTokenTime(token); Long currentTime = System.currentTimeMillis(); if (tokenOutTime < currentTime){ throw new RuntimeException(); } //判断token信息是否正确 parseToken(token); log.info("token正确!"); return true; } static { tokenInfo.setExpiresSecond(15*42*60*60*100L); //token失效时间15天 tokenInfo.setName("monkey"); tokenInfo.setSalt("ikingTech"); } public String getToken(Object object) { try { // 生成签名密钥 byte[] apiKeySecretBytes = DatatypeConverter.parsebase64Binary(tokenInfo.getSalt()); Key signingKey = new SecretKeySpec(apiKeySecretBytes, SignatureAlgorithm.HS256.getJcaName()); // 添加构成JWT的参数 JwtBuilder builder = Jwts.builder() .setHeaderParam("typ", "JWT") .claim(KEY, object) .setIssuer(tokenInfo.getName()) .signWith(SignatureAlgorithm.HS256, signingKey); //当前时间 long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); // 添加Token过期时间(ms) long outMillis = tokenInfo.getExpiresSecond(); if (outMillis >= 0) { long expMillis = nowMillis + outMillis; Date exp = new Date(expMillis); builder.setExpiration(exp).setNotBefore(now); } // 生成JWT String token = builder.compact(); log.info("token:" + token); return token; }catch (Exception e){ log.info("token加密失败!"); throw new RuntimeException(); } } public static SysUser parseToken(String token) { try { Claims claims = Jwts .parser() .setSigningKey(DatatypeConverter.parsebase64Binary(tokenInfo.getSalt())) .parseClaimsJws(token) .getBody(); return JSON.parseObject(JSON.toJSONString(claims.get(KEY)), SysUser.class); }catch (Exception e){ log.info("token解析失败!"); throw new RuntimeException(); } } public static Long getWebTokenTime(String token) { try{ Claims claims = Jwts .parser() .setSigningKey(DatatypeConverter.parsebase64Binary(tokenInfo.getSalt())) .parseClaimsJws(token) .getBody(); return claims.getExpiration().getTime(); }catch (Exception e){ log.info("token获取失效时间失败!"); throw new RuntimeException(); } } public static SysUser getLoginUserInfo(){ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes == null) { log.error("获取ServletRequestAttributes失败。"); return null; } HttpServletRequest request = attributes.getRequest(); String token = request.getHeader(KEY); return parseToken(token); } }4.过滤器过滤登录页面,放行swagger
@Configuration public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Autowired private TokenConfiguration tokenConfiguration; @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(tokenConfiguration) // .addPathPatterns("/select") //拦截first开头的url .excludePathPatterns("/login")//拦截除了的url .excludePathPatterns("/swagger-resources @PostMapping(value = "/login") public String login(@RequestBody SysUser user){ if ("杨过".equals(user.getName()) && "1234".equals(user.getPassword())){ user.setId("1"); user.setWebToken(tokenConfiguration.getToken(user)); return "登录成功!success"; }else { return "用户名或密码错误!failed"; } } @GetMapping(value = "/select") public SysUser select(){ SysUser user = new SysUser(); user.setName("杨过"); user.setPassword("1234"); user.setId("1"); user.setWebToken(tokenConfiguration.getToken(user)); return user; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)