我是靠谱客的博主 高兴爆米花,最近开发中收集的这篇文章主要介绍【springBoot】springBoot配置拦截器,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

springBoot配置拦截器

拦截器:

package com.ycwl.smartPark.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ycwl.smartPark.annotation.IgnoreToken;
import com.ycwl.smartPark.constant.BaseContextHandler;
import com.ycwl.smartPark.exception.CheckTokenException;
import com.ycwl.smartPark.exception.MissTokenException;
import com.ycwl.smartPark.exception.TokenExpireException;
import com.ycwl.smartPark.model.pc.jwt.JwtInfo;
import com.ycwl.smartPark.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.ZoneId;

@Slf4j
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取类上面的注解
        IgnoreToken ignoreClassToken = handlerMethod.getBeanType().getAnnotation(IgnoreToken.class);
        // 获取方法上的注解
        IgnoreToken ignoreMethodToken = handlerMethod.getMethodAnnotation(IgnoreToken.class);
        System.out.println("1111");
        System.out.println(ignoreClassToken);
        System.out.println("2222");
        System.out.println(ignoreMethodToken);
        if (ignoreClassToken != null || ignoreMethodToken != null) {
            // 放行
            return super.preHandle(request, response, handler);
        }

        // 验证白名单
        if (getWhite(request.getRequestURI())) {
            return true;
        }

        /*
        验证token
         */
        // 获取 token
        String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            log.error("==>  请求 header 缺少 Token [{}]", token);
            throw new MissTokenException("请求头缺少token");
        }


        // 解析 token  & 验证 token 有效期
        JwtInfo jwtInfo;
        try {
            jwtInfo = jwtTokenUtil.parsingToken(token);
            log.info("用户信息:" + jwtInfo.toString());
            LocalDateTime expireTime = jwtInfo.getExpireTime();
            if (LocalDateTime.now(ZoneId.systemDefault()).isAfter(expireTime)) {
                throw new TokenExpireException("token过期");
            }
            BaseContextHandler.setToken(token);
            BaseContextHandler.setName(jwtInfo.getName());
            BaseContextHandler.setUserId(jwtInfo.getUserId());
            BaseContextHandler.setAccount(jwtInfo.getAccount());
            BaseContextHandler.setPhone(jwtInfo.getPhone());
            BaseContextHandler.setRoleId(jwtInfo.getRoleId());
            BaseContextHandler.setUserExpireTime(jwtInfo.getExpireTime());
        } catch (CheckTokenException e) {
            throw new CheckTokenException("token无效");
        }

        return true;
    }

    public static void sendJsonMessage(HttpServletResponse response, Object obj) {

        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json; charset=utf-8");

        try (PrintWriter writer = response.getWriter()) {
            writer.print(objectMapper.writeValueAsString(obj));
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("响应json数据给前端异常 -> {}", e.getMessage(), e);
        }

    }


    /**
     * 在请求完全结束后调用, 常用于清理资源等工作
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }

    public String getToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            if (request.getCookies() != null) {
                for (Cookie cookie : request.getCookies()) {
                    if (("token").equals(cookie.getName())) {
                        token = cookie.getValue();
                    }
                }
            }
        }
        return token;
    }


    //白名单swagger2
    private boolean getWhite(String path) {
        return StringUtils.containsAny(
                path,
                "springfox", "swagger", "v2",
                "webjars", "doc.html", "favicon.ico"
        );
    }


}

自定义注解

package com.ycwl.smartPark.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.TYPE})
public @interface IgnoreToken {

}

最后

以上就是高兴爆米花为你收集整理的【springBoot】springBoot配置拦截器的全部内容,希望文章能够帮你解决【springBoot】springBoot配置拦截器所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部