- 引入依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
- JWT工具类
public class JWTUtil {
//签名
private static final String SING = "#$er#$#%AFD(";
//生成token
public static String getToken(Map<String,Object> map) {
Calendar instance = Calendar.getInstance();
instance.add(Calendar.DATE,7);
JWTCreator.Builder builder = JWT.create();
map.forEach((k,v)->{
builder.withClaim(k, v.toString());
});
builder.withExpiresAt(instance.getTime());
String token = builder.sign(Algorithm.HMAC256(SING));
return token;
}
//验证token合法性
public static DecodedJWT verifyToken(String token) {
return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);//
}
}
- 拦截器拦截每一个请求,验证身份
前端发送请求,将token放进Header中,拦截器拦截请求后,获取token,并验证是否合格。
@Configuration
public class JWTInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Map<String,Object> map = new HashMap<>();
//获取请求头中令牌
String token = request.getHeader("token");
try{
JWTUtil.verifyToken(token);
return true;
}catch (SignatureVerificationException e) {
e.printStackTrace();
map.put("msg","无效签名");
}catch(TokenExpiredException e){
e.printStackTrace();
map.put("msg","token过期");
}catch (AlgorithmMismatchException e) {
e.printStackTrace();
map.put("msg","token算法不一致");
}catch (InvalidClaimException e) {
e.printStackTrace();
map.put("msg","token无效");
}
map.put("token",false);
String json = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
return false;
}
}
/**
并在WebMvcConfigurer配置类中注册拦截器,添加拦截目标
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JWTInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/login");
}
}
- 生成token
用户第一次登陆,如果账号密码验证成功,就会给其生成一个token,并将其返还给用户
@GetMapping("/login")
public Map<String,Object> login(String name,String password){
Map<String,Object> map = new HashMap<>();
try{
User user = iLeaderService.login(name,password);
Map<String,Object> payload = new HashMap<>();
payload.put("id",user.getId());
payload.put("name",user.getname());
payload.put("password",user.getPassword());
String token = JWTUtil.getToken(payload);
map.put("state",true);
map.put("msg","登陆成功成功");
map.put("token",token);
}catch (Exception e) {
map.put("state",false);
map.put("msg",e.getMessage());
}
return map;
}
- 获取token存储信息
public void test(HttpServletRequest request) {
String token = request.getHeader("token");
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("#$er#$#%AFD(")).build();
DecodedJWT verify = jwtVerifier.verify(token);
Integer id = verify.getClaim("userId").asInt();
String username = verify.getClaim("userName").asString();
}