JWTutils工具类
package com.itheima.utils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.Map; public class JwtUtils { private static String signKey="itheima"; private static long expire=0L; public static String generateJwt(Map<String,Object> claims){ String jwt= Jwts.builder().addClaims(claims).signWith(SignatureAlgorithm.HS256,signKey) .setExpiration(new Date(System.currentTimeMillis()+expire)).compact(); return jwt; } public static Claims parseJWT(String jwt){ Claims claims=Jwts.parser().setSigningKey(signKey).parseClaimsJwt(jwt).getBody(); return claims; } }
拦截器
package com.itheima.interceptor; import com.alibaba.fastjson.JSONObject; import com.itheima.utils.JwtUtils; import com.itheima.pojo.Result; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @Component @Slf4j public class LoginCheckInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception { System.out.println("preHandle"); String url=req.getRequestURL().toString(); log.info("请求url",url); if(url.contains("login")){ return true; } String jwt=req.getHeader("token"); log.info("jwt",jwt); try { JwtUtils.parseJWT(jwt); }catch (Exception e){ if(!StringUtils.hasLength(jwt)){ Result error=Result.error("NOT_LOGIN"); String notLogin= JSONObject.toJSONString(error); resp.getWriter().write(notLogin); return false; } } log.info("放行"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion"); } }
配置webconfig
package com.itheima.config; import com.itheima.interceptor.LoginCheckInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class webConfig implements WebMvcConfigurer { @Autowired private LoginCheckInterceptor loginCheckInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**"). excludePathPatterns("/login"); } }
运行结果
直接访问会弹出页面(token过期)