一、JDK8使用JWT
新建工具类 JWTUtils
添加jwt依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
定义一些常量
/**
* 两个小时的过期时间
*/
private static final long EXPIRE = 1000*60*60*2;
/**
* 秘钥
*/
private static final String SECRET = "xdtokne";
/**
* 令牌前缀
* @param user
* @return
*/
private static final String TOKEN_PREFIX = "haima";
/**
* 谁颁布的令牌
*/
private static final String SUBJECT = "haima";
用JWT生成token
public static String generateJWTToken(User user) {
String token = Jwts.builder().setSubject(SUBJECT)
.claim("head_img",user.getHeadImg()) // payload部分
.claim("id", user.getId())
.claim("name", user.getName())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
.signWith(SignatureAlgorithm.HS256, SECRET).compact();
token = TOKEN_PREFIX + token;
return token;
}
校验JWT
public static Claims checkToken(String token) {
try {
Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
return claims;
} catch (Exception e) {
return null;
}
}
使用测试方法,测试JWT
User实体 类
@Data
@ToString
public class User {
private Integer id;
private String name;
private String pwd;
private String headImg;
private String phone;
private Date createTime;
}
测试方法
@SpringBootTest
class OnlineXdApplicationTests {
@Test
public void testGeneJwt(){
User user = new User();
user.setId(66);
user.setName("二当家小D");
user.setHeadImg("png");
String token = JWTUtils.generateJWTToken(user);
System.out.println(token);
try {
Thread.sleep(4000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
Claims claims = JWTUtils.checkToken(token);
System.out.println(claims.get("name"));
}
}
二、使用拦截器进行登录拦截
新建拦截器 实现 HandlerInterceptor接口并且重写里面的方法 ,在 preHandle 方法里如下编码
/**
* 进入到controller 之前的方法
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
try {
String accessToken = request.getHeader("token");
if (accessToken == null) {
accessToken = request.getParameter("token");
}
if (StringUtils.isNotBlank(accessToken)) {
Claims claims = JWTUtils.checkToken(accessToken);
if (claims == null) {
// 告诉登录过期,请重新登录
sendJsonMessage(response, JsonData.buildError("登录过期,重新登录"));
return false;
}
Integer id = (Integer) claims.get("id");
String name = (String) claims.get("name");
request.setAttribute("user_id", id);
request.setAttribute("name", name);
return true;
}
} catch (Exception e) {
}
// 登录失败
sendJsonMessage(response, JsonData.buildError("登录过期,重新登录"));
return false;
}
/**
* 响应json数据给前端
* @param response
* @param buildError
*/
private static void sendJsonMessage(HttpServletResponse response, JsonData buildError) {
try {
ObjectMapper objectMapper = new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.print(objectMapper.writeValueAsString(buildError));
writer.close();
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}
}
拦截器配置,实现 WebMvcConfigurer 接口,重写 addInterceptors 方法
首先把上面写的类注入进来
@Bean
LoginInterceptor loginInterceptor() {
return new LoginInterceptor();
}
然后
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor())
// 拦截全部
.addPathPatterns("/api/v1/pri/*/*/**")
// 不会被拦截
.excludePathPatterns("/api/v1/pri/user/login","/api/v1/pri/user/register")
;
WebMvcConfigurer.super.addInterceptors(registry);
}
注册截图
登录截图