在cxsbg包下创建interceptor包,在interceptor包中新建登录拦截器,实现拦截功能
package com.cxsbg.interceptor;
import com.cxsbg.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component //注入
//实现登录拦截器,验证token是否有效,如果有效就放行
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取请求头中的token
String token = request.getHeader("token");
//判断token是否为空,如果为空,说明未登录,不放行
if(!StringUtils.hasText(token)){
//发送错误码
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
//判断token是否有效,如果无效,不放行
try {
Claims claims = JwtUtil.parseJWT(token);
String subject = claims.getSubject();
System.out.println(subject);
}catch (Exception e){
//发送错误码
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
return true;
}
}