MyWebInterceptor.java 2.99 KB
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
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);
}
}