spring boot中通过添加拦截器,根据 token 获取当前用户,完成登录拦截,并获取当前用户信息

拦截器在获取token信息时,可以直接通过redis获取到用户信息

public class UserContext {
    public static final Logger logger = LoggerFactory.getLogger(UserContext.class);

    /**
     * 登录用户上下文存储
     */
    private static final ThreadLocal context = new ThreadLocal<>();

    @Data
    public static class UserHolder {

        private Long userId;

        private String mobile;

        private String token;

        private String realName;

        private String userName;

        private String jobNo;
        private String ip;
    }

    public static void clear() {
        UserContext.context.remove();
    }

    public static void addUserContext(AuthDomain authDomain, String token) {
        if (authDomain != null) {
            Long userId = authDomain.getId();
            String mobile = authDomain.getPhone();
            String realName = authDomain.getRealname();
            UserContext.clear();
            UserHolder userHolder = new UserHolder();
            userHolder.setUserId(userId);
            userHolder.setMobile(mobile);
            userHolder.setToken(token);
            userHolder.setRealName(realName);
            userHolder.setUserName(authDomain.getUsername());
            userHolder.setJobNo(authDomain.getJobNo());
            userHolder.setIp(authDomain.getIp());
            context.set(userHolder);
        }
    }

    public static UserHolder getUserHolder() {
        return context.get();
    }


    public static void addUserContextForDebug() {

        UserContext.clear();
        UserHolder userHolder = new UserHolder();
        userHolder.setUserId(110L);
        userHolder.setMobile("17792631125");
        userHolder.setToken("5cb6d9a58a15bd0543048a8e");
        userHolder.setRealName("jecy");
        userHolder.setJobNo("110");
        userHolder.setUserName("admin");
        context.set(userHolder);

    }
}
/**
 * @author lige
 */
public class SecurityInterceptor extends HandlerInterceptorAdapter {
    Logger log = LoggerFactory.getLogger(SecurityInterceptor.class);
    private static String [] whiteUrlArrys = {"/login","/swagger","/logout"};
    private RedisClient redisClient;
    boolean isOpenDebug;
    public SecurityInterceptor(RedisClient redisClient,boolean isOpenDebug) {

        this.redisClient = redisClient;
        this.isOpenDebug = isOpenDebug;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HttpRequestContext.setContext(request);
            if (openDebug(isOpenDebug)) {
                return true;
            }
            if(isWhiteURI(request)) {
                return true;
            }
           return loginHandler(request,response);
        } else {
            return super.preHandle(request, response, handler);
        }
    }

    private boolean loginHandler(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String token = request.getHeader(AuthConstant.ACCESS_TOKEN);
        AuthDomain authDomain = null;
        if (StringUtils.isBlank(token)) {
            redirectToLogin(request, response);
            return false;
        } else {
            String redisContent = redisClient.get(token);
            if (StringUtils.isBlank(redisContent)) {
                redirectToLogin(request, response);
                return false;
            }
            authDomain =  JSONObject.parseObject(redisContent, AuthDomain.class);
            String ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            authDomain.setIp(ip);
        }
        UserContext.addUserContext(authDomain, token);
        return true;
    }

        private void redirectToLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setStatus(401);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=" + "utf-8");
        String noLogin = "{\n" +
                "\"status\": \"10000\"\n," +
                "\"msg\":\"当前登录信息已失效,请退出重新操作\"\n" +

                "}";
        response.getWriter().write(noLogin);
    }

    public static boolean isWhiteURI(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        return Arrays.stream(whiteUrlArrys).anyMatch(s->url.contains(s));
    }

    private boolean openDebug(boolean isOpenDebug) {
        if (isOpenDebug) {
            UserContext.addUserContextForDebug();
            return true;
        }
        return false;

    }

在来截器里面处理请求。

你可能感兴趣的:(spring,boot)