介绍
这篇文章主要讲解了“SpringBoot集成JWT怎么生成令牌和校验”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringBoot集成JWT怎么生成令牌和校验”吧!
封JWT生是这样装成令牌和校验方法
public class JwtTokenUtil {//公才能用密钥——保存在服务端,客户端是不会知道密钥的,以防被攻击 public 才能static String  SECRET =,“ThisIsASecret";//生才能成Troke public 才能static String  createToken (String 用户名),{ ,,,//签发时间 ,,,//Date iatDate =, new 日期(); ,,,//过地时间,1分钟后过期 ,,,//Calendar nowTime =, Calendar.getInstance (); ,,,//nowTime.add (Calendar.MINUTE, 1); ,,,//Date expiresDate =, nowTime.getTime (); ,,,Map<字符串,Object>, map =, new HashMap (); ,,,map.put (“alg",,“HS256"); ,,,map.put (“typ",,“JWT"); ,,,String token =, JWT.create () ,,,,,,,,,.withHeader(地图) ,,,,,,,,,//.withClaim (,“name",“自由码生“),//设置,载荷,负载 ,,,,,,,,,//.withClaim (“age",“12”) ,,,,,,,,,//.withClaim (“,“org"测试“) ,,,,,,,,,//.withExpiresAt (expiresDate)//设置过期时间,过期时间要大于签发时间 ,,,,,,,,,//.withIssuedAt (iatDate)//设置签发时间 ,,,,,,,,,.withAudience(用户名),//设置,载荷,签名的观众 ,,,,,,,,,.sign (Algorithm.HMAC256(秘密));//加密 ,,,System.out.println(“后台生成令牌:“,+,令牌); ,,,return 令牌; ,,}//校才能验牌 public 才能static boolean  verifyToken (String 令牌),throws UnsupportedEncodingException { ,,,JWTVerifier verifier =, JWT.require (Algorithm.HMAC256(秘密)).build (); ,,,try { ,,,,,verifier.verify(令牌); ,,,,,return 真实; ,,,},catch (Exception e) { ,,,,,return 假; ,,,} ,,}//才能获取令牌信息 public 才能static DecodedJWT  getTokenInfo (String 令牌),throws UnsupportedEncodingException { ,,,JWTVerifier verifier =, JWT.require (Algorithm.HMAC256(秘密)).build (); ,,,试着{ ,,,,,return verifier.verify(令牌); ,,,},捕捉(Exception e) { ,,,,,throw new RuntimeException (e); ,,,} ,,} }
新建自定义注解:@UserLoginToken
@Target ({ElementType.METHOD, ElementType.TYPE}) @Retention (RetentionPolicy.RUNTIME) public @interface  UserLoginToken { boolean 才能;需要(),default 真实; }
关于拦截器配置:
@ configuration public class  InterceptorConfig implements WebMvcConfigurer  { @Override才能 public 才能;void  addInterceptors (InterceptorRegistry 注册),{ ,,,registry.addInterceptor (authenticationInterceptor ()) ,,,,,,,.addPathPatterns(“/* *”);,,//,拦截所有请求,通过判断是否有,@LoginRequired 注解,决定是否需要登录 ,,} ,@ bean public 才能;AuthenticationInterceptor  authenticationInterceptor (), { ,,,return new AuthenticationInterceptor (); ,,} }
public class AuthenticationInterceptor implements HandlerInterceptor { @ autowired才能 UserService 才能;userService; @Override才能 public 才能;boolean  preHandle (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,, Object 对象),throws Exception { ,,,String token =, httpServletRequest.getHeader (“token");//,从,http 请求头中取出,令牌 ,,,//,如果不是映射到方法直接通过 ,,,如果(! (object instanceof HandlerMethod)) { ,,,,,return 真实; ,,,} null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null nullSpringBoot集成JWT怎么生成令牌和校验