# 代码随记

# 简单的登录权限注解

package io.rushb.common.annotation;

import java.lang.annotation.*;

/**
 * @author FLAMINGO
 * @since 2021/6/18 16:52
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Login {
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package io.rushb.service.authentication;

import io.rushb.common.annotation.Login;
import io.rushb.common.util.RRException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author FLAMINGO
 * @since 2021/6/18 16:19
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }
        if (annotation == null) {
            return true;
        }
        // 从header中获取token
        String token = request.getHeader("token");
        // 如果header中不存在token,则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        // token为空
        if (StringUtils.isBlank(token)) {
            throw new RRException("token无效,请重新登录");
        }
        // 查询token信息
        String username = AuthenticationPool.get(token);
        if (username == null) {
            throw new RRException("token失效,请重新登录", 511);
        }
        return true;
    }
}

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
上次更新: 2 years ago