笔者会在此系列文章中分享SSM框架的单体架构项目中常用的技术要点,欢迎批评指正。
什么是JWT令牌(token)
简单来说, JWT令牌就是一张数字通行证,用户登录的凭证,在拿到该凭证的前提下才能访问我们后端的各种业务接口。
令牌由Header - 头部,Payload - 载荷, 和Signature - 签名三部分组成,其中值得我们关心的数据有载荷中的注册声明(有效时长),私有声明(自定义数据, Map集合),以及签名中的密钥。
在项目开发中使用JWT令牌来校验登录状态, 主要步骤如下: 在登录接口中给用户下发令牌 -> 创建令牌拦截器 -> 在SpringMVC配置类中注册拦截器
具体实现
在使用JWT之前必须要前导入其依赖:
<!-- JWT依赖-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
1.下发令牌
在登录接口中我们可以根据用户的ID和项目的密钥来为每一位用户生成独一味二的token,并返回给前端。
由于生成令牌的代码较为固定,我们可以创建一个工具类,专门用于令牌的生成与解析:
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
public class JwtUtil {
/**
* 生成jwt令牌
* 使用Hs256算法, 私匙使用固定秘钥
*
* @param secretKey jwt秘钥
* @param ttlMillis jwt过期时间(毫秒)
* @param claims 设置的信息
* @return
*/
public static String createJWT(String secretKey, long ttlMillis, Map<String, Object> claims) {
// 指定签名的时候使用的签名算法,也就是header那部分
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
// 生成JWT的时间
long expMillis = System.currentTimeMillis() + ttlMillis;
Date exp = new Date(expMillis);
// 设置jwt的body
JwtBuilder builder = Jwts.builder()
// 设置私有声明
.setClaims(claims)
// 设置签名使用的签名算法和签名使用的秘钥
.signWith(signatureAlgorithm, secretKey.getBytes(StandardCharsets.UTF_8))
// 设置过期时间
.setExpiration(exp);
return builder.compact();
}
/**
* 令牌解密
*
* @param secretKey jwt秘钥 此秘钥一定要保留好在服务端, 不能暴露出去
* @param token 加密后的token
* @return
*/
public static Claims parseJWT(String secretKey, String token) {
// 得到DefaultJwtParser
Claims claims = Jwts.parser()
// 提供签名的秘钥
.setSigningKey(secretKey.getBytes(StandardCharsets.UTF_8))
// 设置需要解析的jwt
.parseClaimsJws(token).getBody();
return claims;
}
}
- 算法签名比较固定,直接一行代码就可以搞定。
- 这里的setExpiration要传入的时间是当前时间戳 + 传入的时间参数(毫秒)。
- signWith方法第二个形参(密钥)数据类型是字节数组,因此要使用getBytes(StandardCharsets.UTF_8)来转换数据类型并显示指明编码格式。
- 私有声明claims可以在调用该方法前进行封装,再传递到方法中,私有声明中通常会封装用户ID这样的常用字段以便于数据传递。
接下来,就可以在用户完成登录后为其生成令牌
@Autowired
private EmployeeService employeeService;
@Autowired
private JwtProperties jwtProperties;
@PostMapping("/login")
@ApiOperation("员工登录")
public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
log.info("员工登录:{}", employeeLoginDTO);
Employee employee = employeeService.login(employeeLoginDTO);
//登录成功后,生成jwt令牌
Map<String, Object> claims = new HashMap<>();
claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
String token = JwtUtil.createJWT(
jwtProperties.getAdminSecretKey(),
jwtProperties.getAdminTtl(),
claims);
EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
.id(employee.getId())
.userName(employee.getUsername())
.name(employee.getName())
.token(token)
.build();
return Result.success(employeeLoginVO);
}
- 笔者此处将密钥以及过期时间设置在了yml配置文件中,并封装在JwtProperties里,这里通过注入jwtProperties来获取密钥和过期时间,既便于维护,又保证安全
- 这里将 “用户ID : id” 这一字段封装到了私有声明中,目的是便于在业务层获取ID,这在后面拦截器中会讲到。
- 最后,将前端所需要的数据封装进EmployeeLoginVO中返回
配置拦截器
下发令牌后每一次前端访问业务接口时都会携带该token,这时我们就必然要设置拦截器来校验这个token
拦截器类要实现HandlerInterceptor接口并重写preHandle方法,在preHandle方法体中完成我们的拦截逻辑
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* jwt令牌校验的拦截器
*/
@Slf4j
@Component
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
@Autowired
private JwtProperties jwtProperties;
/**
* 校验jwt
* * @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//判断当前拦截到的是Controller的方法还是其他资源
if (!(handler instanceof HandlerMethod)) {
//当前拦截到的不是动态方法,直接放行
return true;
}
//1、从请求头中获取令牌
String token = request.getHeader(jwtProperties.getAdminTokenName());
//2、校验令牌
try {
log.info("jwt校验:{}", token);
Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
log.info("当前员工id:", empId);
BaseContext.setCurrentId(empId);
//3、通过,放行
return true;
} catch (Exception ex) {
//4、不通过,响应401状态码
response.setStatus(401);
return false;
}
}
}
- 笔者在这里使用parseJWT( )方法解析令牌并拿到claims来校验令牌,如果此时令牌有误或者令牌过期,则必然会抛出异常,执行catch代码块中的内容响应401状态码
- 这里解析令牌之后笔者基于ThreadLocal共享了empId,这样service层的接口就可以便捷获取empId
注册拦截器
拦截器要想生效,就必须在SpringMVC配置类中完成注册:
import com.sky.interceptor.JwtTokenAdminInterceptor;
import com.sky.json.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
/**
* 配置类,注册web层相关组件
*/
@Slf4j
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
@Autowired
private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;
/**
* 注册自定义拦截器
*
* @param registry
*/
protected void addInterceptors(InterceptorRegistry registry) {
log.info("开始注册自定义拦截器...");
registry.addInterceptor(jwtTokenAdminInterceptor)
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin/employee/login");
}
}
- 在实现了WebMvcConfigurationSupport接口的配置类中重写addInterceptors方法,然后调用registry进行注册
- addInterceptor()的形参就是要注册的拦截器,这里通过@Autowired直接注入拦截器即可
- addPathPatterns()用于指明该拦截器生效范围,笔者此处的配置就是对admin包下的所有类都生效
- excludePathPatterns()则指明哪些接口不生效,一般都是登录接口
至此,就可以保证你的项目可以完美校验用户的登录状态了