添加依赖
<!--jwt加密--> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.10.3</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency>
生成token核心代码
//生成token JwtBuilder builder = Jwts.builder(); String token = builder.setSubject(username) //主题,就是token中携带的数据 .setIssuedAt(new Date()) //创建时间 .setId(users.get(0).getUserId() + "") //设置用户id为token id .setClaims(new HashMap() {{ }}) //map可以存放用户角色 权限信息 .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)) //设置过期时间 .signWith(SignatureAlgorithm.HS256, "caowei666") //设置加密算法 和 密码 .compact();
自定义校验token拦截器
import com.fasterxml.jackson.databind.ObjectMapper; import com.qfedu.fmmall.vo.ResultVo; import io.jsonwebtoken.*; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @Component public class CheckTokenInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //前端header中如果有自定义值则会执行预检请求 if(request.getMethod().equalsIgnoreCase("options")) { return true; } String token = request.getHeader("token"); if(token == null) { //提示请先登录 ResultVo resultVo = new ResultVo(401, "请先登录!", null); doResponse(response, resultVo); return false; }else { try { //解析token JwtParser parser = Jwts.parser(); parser.setSigningKey("caowei666"); //如果token正确(密码正确,有效期内)则不会报异常 Jws<Claims> claimsJws = parser.parseClaimsJws(token); return true; }catch (ExpiredJwtException e) { ResultVo resultVo = new ResultVo(401, "登录过期!", null); doResponse(response, resultVo); }catch (UnsupportedJwtException e){ ResultVo resultVo = new ResultVo(401, "token不合法!", null); doResponse(response, resultVo); }catch (Exception e){ ResultVo resultVo = new ResultVo(401, "请先登录!", null); doResponse(response, resultVo); } return false; } } private void doResponse(HttpServletResponse response, ResultVo resultVo) throws IOException { response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); PrintWriter writer = response.getWriter(); String s = new ObjectMapper().writeValueAsString(resultVo); writer.print(s); writer.flush(); writer.close(); } }
注册拦截器
@Configuration public class InterceptorConfig implements WebMvcConfigurer { @Autowired private CheckTokenInterceptor checkTokenInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(checkTokenInterceptor) .addPathPatterns("/**") .excludePathPatterns("/user/**"); } }
标签:拦截器,ResultVo,jwt,response,token,new,import,resultVo From: https://www.cnblogs.com/wscw/p/17804372.html