为什么要使用JWT?
先来看看-传统的Session认证
基于JWT认证
简单案例
/**
* @program: JWT
* @author: Mr-Jies
* @create: 2020-08-10 12:28
**/
public class JwtUtils {
private static String sign = "$#g^SK0)(-#%";
/**
* 获取token
* @param map
* @return
*/
public static String getToken(Map<String,String> map){
//时间
Calendar instance = Calendar.getInstance();
instance.add(Calendar.HOUR_OF_DAY,5);
JWTCreator.Builder builder = JWT.create();
//payload
map.forEach((k,v)->{
builder.withClaim(k,v);
});
String token = builder.withExpiresAt(instance.getTime())
.sign(Algorithm.HMAC256(JwtUtils.sign));
return token;
}
/**
* 验证token
* @param token
* @return
*/
public static DecodedJWT verify(String token){
DecodedJWT verify = JWT.require(Algorithm.HMAC256(sign)).build().verify(token);
return verify;
}
}
生成token 注意要有3个部分
String token = JWT.create()
.withHeader(new HashMap<String, Object>())//heard
.withClaim("userName", "jies")//payload
.withClaim("age", 20)
.withExpiresAt(instance.getTime())//设置过期时间
.sign(Algorithm.HMAC256("*&@#$k$k"));//sign
整合SpringBoot
用到了过滤器
- 导包
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
- 写配置文件
- 拦截器
/**
* @program: JWT
* @author: Mr-Jies
* @create: 2020-08-10 13:40
**/
public class JwtInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HashMap<String, Object> map = new HashMap<>();
//获取请求头
String token = request.getHeader("token");
try {
JwtUtils.verify(token);
map.put("state",true);
return true;
} catch (Exception e) {
e.printStackTrace();
map.put("msg",e.getMessage());
}
map.put("state",false);
//转化为json输出
String s = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=utf-8");
response.getWriter().println(s);
return false;
}
}
- configration中引入拦截器
/**
* @program: JWT
* @author: Mr-Jies
* @create: 2020-08-10 13:48
**/
@Configuration
public class JwtInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JwtInterceptor())
.addPathPatterns("/**")//拦截
.excludePathPatterns("/user/login");//放行
}
}
- 测试