2
13693261870
2022-09-16 653761a31dfeb50dd3d007e892d69c90bf0cdafc
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
package com.landtool.lanbase.modules.api.intercept;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 
import com.landtool.lanbase.common.exception.LanbaseException;
import com.landtool.lanbase.modules.api.annotation.Login;
import com.landtool.lanbase.modules.api.utils.JwtUtils;
 
import io.jsonwebtoken.Claims;
 
/**
 * @author lanbase
 * @Description: TODO(api interceptor)
 * @date 2017-9-27 14:41
 */
@Component
public class ApiInterceptor extends HandlerInterceptorAdapter {
 
    @Autowired
    private JwtUtils jwtUtils;
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //接口方法如果没有Login注解,则不需要校验token
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }
 
        if(annotation == null){
            return true;
        }
 
        //获取token
        String token = request.getHeader(jwtUtils.getHeader());
        if(StringUtils.isBlank(token)){
            token = request.getParameter(jwtUtils.getHeader());
        }
 
        //校验token
        if(StringUtils.isBlank(token)){
            throw new LanbaseException(jwtUtils.getHeader() + "不能为空", HttpStatus.UNAUTHORIZED.value());
        }
        Claims claims = jwtUtils.getClaimByToken(token);
        if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){
            throw new LanbaseException(jwtUtils.getHeader() + "已经失效", HttpStatus.UNAUTHORIZED.value());
        }
 
        return true;
    }
 
}