package com.lyms.talkonlineweb.config;
import com.alibaba.fastjson.JSON;
import com.lyms.talkonlineweb.annotation.TokenRequired;
import com.lyms.talkonlineweb.result.BaseResponse;
import com.lyms.talkonlineweb.result.CheckResult;
import com.lyms.talkonlineweb.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
@Log
public class MyWebInterceptor implements HandlerInterceptor {
// 拦截路径
private String excludePath;
public MyWebInterceptor(String excludePath){
this.excludePath=excludePath;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("excludePath:"+excludePath);
System.out.println(request.getServletPath());
System.out.println(handler);
TokenRequired clientRequired = null;
if(handler instanceof HandlerMethod){
clientRequired=findAnnotation((HandlerMethod) handler, TokenRequired.class);
}
// if(handler instanceof ResourceHttpRequestHandler){
// clientRequired=findAnnotation((ResourceHttpRequestHandler) handler, TokenRequired.class);
// }
if (null == clientRequired)
return true;
return validateToken(request, response);
}
private boolean validateToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
String token=request.getHeader("Authorization");
CheckResult checkResult=JwtUtils.validateJWT(token);
if(!checkResult.isSuccess()){
BaseResponse baseResponse=new BaseResponse();
baseResponse.setErrorcode(1);
baseResponse.setErrormsg("无效token");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setContentType("application/json;charset=UTF-8");
PrintWriter printWriter=response.getWriter();
printWriter.write(JSON.toJSONString(baseResponse));
printWriter.flush();
printWriter.close();
return false;
}
if(checkResult.isSuccess()){
Claims claims=checkResult.getClaims();
log.info(claims.toString());
}
return true;
}
private <T extends Annotation> T findAnnotation(HandlerMethod handler, Class<T> annotationType) {
T annotation = handler.getBeanType().getAnnotation(annotationType);
if (annotation != null)
return annotation;
return handler.getMethodAnnotation(annotationType);
}
}