1、引入jwt的两个依赖
java-jwt,jjwt
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.19.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
2、使用jwt创建token,并响应给前端
HashMap<String, Object> map = new HashMap<>();
map.put("username",user.getUsername());
JwtBuilder builder = Jwts.builder();
String token = builder.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 1000 + 60 * 60 * 24))
.signWith(SignatureAlgorithm.HS256, "yogo123456")
.setId(user.getUserId() + "")
.setClaims(map)
.compact();
return new ResultVO(ResultVOCode.SUCCESS,token,user);
3、创建拦截器,拦截前端token
1、前端token约定添加到header中,需要预检(OPTIONS)
@Component
public class CheckTokenIncepter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//放行预检
String method = request.getMethod();
if ("OPTIONS".equalsIgnoreCase(method)){
return true;
}
ResultVO resultVO = new ResultVO();
String token = request.getHeader("token");
// String token = request.getParameter("token");
if (token == null || token.length() == 0){
resultVO.setCode(ResultVOCode.FAILER);
resultVO.setMsg("请先登录");
doResponse(response,resultVO);
}else {
JwtParser parser = Jwts.parser();
parser.setSigningKey(ConstContent.tokenPwd);
try {
Jws<Claims> claimsJws = parser.parseClaimsJws(token);
// Claims body = claimsJws.getBody();
// String tokenParam1 = body.get(ConstContent.tokenParam1, String.class);
// System.out.println("tokenParam1------"+tokenParam1);
return true;
}catch (Exception e){
resultVO.setCode(ResultVOCode.FAILER);
resultVO.setMsg("token失效 请先登录");
doResponse(response,resultVO);
}
}
return false;
}
private void doResponse(HttpServletResponse response, ResultVO resultVO){
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
try {
PrintWriter writer = response.getWriter();
String str = new ObjectMapper().writeValueAsString(resultVO);
writer.print(str);
writer.flush();
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private CheckTokenIncepter checkTokenIncepter;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(checkTokenIncepter)
.addPathPatterns("/goods/**")
.addPathPatterns("/shopCart/**")
.excludePathPatterns("/user/**");
}
}
网友评论