引入依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.1</version>
</dependency>
- jwt配置
jwt工具类
@Slf4j
public class JwtUtil {
/**
* 默认签名
*/
private static final String SING = "!@#$%^&*A1D2FRT5";
/**
* 转换成毫秒 默认失效时间2个小时 这里写在配置文件了。
* 测试的时候 可以直接给定 7200
*/
private static final long EXPIRE_TIME= SpringContextUtils.getBean(ShiroProperties.class).getJwtTimeOut() * 1000;
/**
* 根据jwt token获取用户名
* @param token
* @return
*/
public static String getUsername(String token){
String result = null;
try{
DecodedJWT jwt = JWT.decode(token);
result = jwt.getClaim("userName").asString();
}catch (JWTDecodeException e){
log.error("error {}",e.getMessage());
}
return result;
}
/**
* 根据jwt token 获取用户id
* @param token
* @return
*/
public static Long getUserId(String token){
Long userId = null;
try{
DecodedJWT jwt = JWT.decode(token);
userId = jwt.getClaim("userId").asLong();
}catch (JWTDecodeException e){
log.error("error {}",e.getMessage());
}
return userId;
}
/**
* 获取token
* @param username 用户名称
* @param secret 密码
* @return
*/
public static String getToken(String username,Long userId,String secret){
try{
return JWT.create()
//存放信息 后面可以根据name取出
.withClaim("userId",userId)
.withClaim("userName",username)
//过期时间
.withExpiresAt(new Date(System.currentTimeMillis()+EXPIRE_TIME))
//设置签名
.sign(Algorithm.HMAC256(ObjectUtil.isNull(secret)?SING:secret));
}catch (Exception e){
log.error("error:{}", e);
return null;
}
}
/**
* 验证token
* 如果token验证不通过,则会报异常
* @param token
*/
public static DecodedJWT verify(String sing,String token) {
sing = ObjectUtil.isNull(sing)?sing=SING:sing;
return JWT.require(Algorithm.HMAC256(sing)).build().verify(token);
}
}
jwt拦截器(验证token)
@Log4j2
public class JwtInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HashMap<String, Object> hashMap = new HashMap<>();
//获取token
String token = request.getHeader("token");
try {
//验证token
JwtUtil.verify(null, token);
return true;
} catch (Exception e) {
log.info(e);
hashMap.put("mag","token无效");
String json = JsonUtil.toJSONString(hashMap);
response.setContentType("application/json;charset=UTF-8");
//将错误信息告知前端
response.getWriter().println(json);
}
return false;
}
}
路由配置 (设置不登录拦截url)
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JwtInterceptor())
//拦截所有路由
.addPathPatterns("/**")
//不拦截路由
.excludePathPatterns("/**/login");
}
}
- 登录实现
service
/**
* 用户登录接口
* @param userName
* @param passWord
* @return
*/
Result login(String userName, String passWord);
serviceImpl
@Override
public Result login(String userName, String passWord) {
//查询用户
SysUser sysUser = getOne(Wrappers.<SysUser>query().lambda()
.eq(SysUser::getUserName, userName)
.eq(SysUser::getIsEnable,0)
.eq(SysUser::getUserPassword, passWord));
if (ObjectUtil.isNull(sysUser)) {
return Result.defFailed(YumErrorCode.USER_LOGIN_NOT_USER.getMessage());
}
//找到用户 生成jwt
String token = JwtUtil.getToken(sysUser.getUserName(), sysUser.getId(), null);
SysUserVO sysUserVO = BeanUtil.copyProperties(sysUser, SysUserVO.class);
sysUserVO.setToken(token);
sysUserVO.setUserPassword(null);
return Result.defSuccess(sysUserVO);
}
controller
@GetMapping("/login")
public Result login(String userName,String passWord) {
return sysUserService.login(userName,passWord);
}
测试
-
不登录分页查询用户信息
-
登录
-
将返回的token放入请求的header
1.放入错误的token
2.放入正确的token