token的创建与解析,并配合拦截器使用
场景:
进行web应用开发时,往往需要对当前用户进行身份判断,此时可以使用token技术
1.导入依赖
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-impl</artifactId><scope>runtime</scope> </dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-jackson</artifactId><scope>runtime</scope> </dependency>
2.创建JwtUtil类
public class JwtUtil {//设置密码private static SecretKey secretKey = Keys.hmacShaKeyFor("gcKqM5Cgn5eq6OLE6eP61LXfvKkfrSqz".getBytes());//编写Token生成的静态方法,方便调用public static String createToken(Long userId, String username) {String jwt = Jwts.builder()//设置过期时间.setExpiration(new Date(System.currentTimeMillis() + 3600000*24*24))//设置token中所带的信息.setSubject("LOGIN_USER").claim("userId", userId).claim("username", username)//设置密钥,设置加密方式.signWith(secretKey, SignatureAlgorithm.HS256).compact();return jwt;}//编写解析Token的方法public static Claims parseToken(String token) {if (token == null) {throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);}try {JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();//会返回一个带着信息的claims对象return jwtParser.parseClaimsJws(token).getBody();} catch (ExpiredJwtException e) {throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);} catch (JwtException e) {throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);}}public static void main(String[] args) {System.out.println(createToken(8L, "用户-20080"));} }
3.使用自定义拦截器进行Token验证
@Component public class AuthenticationInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//从请求头中获取Token(这里的字段名因人而异)String token = request.getHeader("access-token");Claims claims = JwtUtil.parseToken(token);Long userId = claims.get("userId", Long.class);String username = claims.get("username", String.class);/***此时可以通过获取到的用户信息判断用户信息是否正确,来决定是否放行 ***/return true;}
4.创建配置类进行拦截器装载
@Configuration public class WebMvcConfiguration implements WebMvcConfigurer {//获取之前自定义的过滤器@Resourceprivate AuthenticationInterceptor authenticationInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {//装载过滤器registry.addInterceptor(this.authenticationInterceptor)//添加需要拦截的请求路径.addPathPatterns("/app/**")//添加不需要拦截的请求路径.excludePathPatterns("/app/login/**");} }