第一步:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.19.0</version>
</dependency>
第二步再utls文件夹里面:
public class JwtUtils {
/** 过期时间,单位:秒,默认半小时过期 **/
private static final long EXPIRATION = 60 * 30L;
/** 密钥,一般长度较长,内容较复杂 **/
private static final String SECRET = "my_secret";
/**
* @description 创建token
* @author xBaozi
* @date 20:49 2022/3/31
**/
public static String createToken(Map<String, String> claimMap) {
// 当前时间戳加上设定的毫秒数(1秒 == 1000毫秒)
Date expiration = new Date(System.currentTimeMillis() + EXPIRATION * 1000);
// 设置JWT头部
Map<String, Object> map = new HashMap<>();
map.put("alg", "HS256");
map.put("typ", "JWT");
// 创建token
JWTCreator.Builder builder = JWT.create();
//使用Lambda创建payload
claimMap.forEach((k,v)->{
builder.withClaim(k,v);
});
// 添加头部,可省略保持默认,默认即map中的键值对
return builder.withHeader(map)
// 设置过期时间
.withExpiresAt(expiration)
// 设置签名解码算法
.sign(Algorithm.HMAC256(SECRET));
}
/**
* @description 验证token
* @author xBaozi
* @date 23:36 2022/3/31
**/
public static DecodedJWT verifyToken(String token) {
return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
}
}
第三步:创建JwtInterceptor文件夹:
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 {
//验证令牌
JwtUtils.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 (Exception e) {
e.printStackTrace();
map.put("msg", "token无效!!");
}
//设置状态
map.put("state", false);
//将map转为json
String json = new ObjectMapper().writeValueAsString(map);
// 相应json数据
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
return false;
}
}
第四步:
在config文件夹下面配置:
@Configuration
public class JwtConfig implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JwtInterceptor())
//添加拦截路径
.addPathPatterns("/**")
//添加放行路径
.excludePathPatterns("/user/login");
}
}
第五步测试用:
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
// 这里只做演示,就不写Service层了
// @Autowired
// private UserService userService;
/**
* @description 登录功能
* @author xBaozi
* @date 0:02 2022/4/1
* @param user user对象,默认有值
**/
@GetMapping("/login")
public Map<String,Object> login(User user){
log.info("用户名: [{}]",user.getName());
log.info("密码: [{}]",user.getPassword());
Map<String, Object> map = new HashMap<>();
try{
Map<String,String> payload = new HashMap<>();
payload.put("id",user.getId());
payload.put("name",user.getName());
// 生成JWT的令牌
String token = JwtUtils.createToken(payload);
map.put("state",true);
map.put("msg","认证成功");
// 响应token
map.put("token",token);
}catch (Exception e){
map.put("state",false);
map.put("msg",e.getMessage());
}
return map;
}
@PostMapping("/other")
public Map<String,Object> test(HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
//处理自己业务逻辑
String token = request.getHeader("token");
DecodedJWT verify = JwtUtils.verifyToken(token);
log.info("用户id: [{}]",verify.getClaim("id").asString());
log.info("用户name: [{}]",verify.getClaim("name").asString());
map.put("state",true);
map.put("msg","请求成功!");
return map;
}
}
运行截图:
如果更加详细的可以参考博主:Spring Boot整合JWT_springboot jwt-CSDN博客
版权归原作者 大大散户 所有, 如有侵权,请联系我们删除。