美文网首页
SpringBoot通过拦截器获取登录信息

SpringBoot通过拦截器获取登录信息

作者: qubor | 来源:发表于2021-01-29 17:12 被阅读0次
    1. 配置拦截器及参数解析器
    package org.jeecg.modules.yiqing.config;
    
    import org.jeecg.modules.yiqing.common.interceptor.AuthInterceptor;
    import org.jeecg.modules.yiqing.common.resolver.CurrentUserMethodArgumentResolver;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.method.support.HandlerMethodArgumentResolver;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    import java.util.List;
    
    @Configuration
    public class AppAuthConfiguration implements WebMvcConfigurer {
    
        //关键,将拦截器作为bean写入配置中
        @Bean
        public AuthInterceptor getSecurityInterceptor() {
            return new AuthInterceptor();
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            // 注册拦截器
            InterceptorRegistration ir = registry.addInterceptor(getSecurityInterceptor());
            // 配置拦截的路径
            ir.addPathPatterns("/**");
            // 配置不拦截的路径
            ir.excludePathPatterns("**/doc.html");
            //ir.excludePathPatterns("**/**");
            // 还可以在这里注册其它的拦截器
            //registry.addInterceptor(new AppAuthInterceptor()).addPathPatterns("/api/**");
        }
    
        @Override
        public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
            argumentResolvers.add(currentUserMethodArgumentResolver());
        }
    
        @Bean
        public CurrentUserMethodArgumentResolver currentUserMethodArgumentResolver() {
            return new CurrentUserMethodArgumentResolver();
        }
    }
    
    1. 拦截器
    package org.jeecg.modules.yiqing.common.interceptor;
    
    import com.xkcoding.http.util.StringUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.jeecg.common.system.vo.LoginUser;
    import org.jeecg.common.util.TokenUtils;
    import org.jeecg.config.shiro.ShiroRealm;
    import org.jeecg.modules.yiqing.common.annotation.IgnoreSecurity;
    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.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.lang.reflect.Method;
    
    @Slf4j
    @Component
    public class AuthInterceptor extends HandlerInterceptorAdapter {
        @Autowired
        private ShiroRealm shiroRealm;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            // 如果不是映射到方法直接通过
            if (!(handler instanceof HandlerMethod)) {
                return true;
            }
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            String requestPath = request.getRequestURI();
            log.info("Method: " + method.getName() + ", IgnoreSecurity: " + method.isAnnotationPresent(IgnoreSecurity.class));
            log.info("requestPath: " + requestPath);
            if (requestPath.contains("/v2/api-docs") || requestPath.contains("/swagger") || requestPath.contains("/configuration/ui")) {
                return true;
            }
            if (requestPath.contains("/sys/common/static/logs/")){
                return true;
            }
            if (requestPath.contains("/error")) {
                return true;
            }
            if (requestPath.contains("/sys/login")) {
                return true;
            }
            if (requestPath.contains("/randomImage")){
                return true;
            }
            if (method.isAnnotationPresent(IgnoreSecurity.class)) {
                return true;
            }
            //String token = request.getHeader("ACCESS_TOKEN");
            String token = TokenUtils.getTokenByRequest(request);
            log.debug("token: " + token);
            if (StringUtil.isEmpty(token)) {
                throw new Exception("无效token");
            }
            LoginUser loginUser = shiroRealm.checkUserTokenIsEffect(token);
            request.setAttribute("currentUser", loginUser);
            return true;
        }
    }
    

    3.参数解析器

    package org.jeecg.modules.yiqing.common.resolver;
    
    import org.jeecg.common.system.vo.LoginUser;
    import org.jeecg.modules.yiqing.common.annotation.CurrentUser;
    import org.springframework.core.MethodParameter;
    import org.springframework.web.bind.support.WebDataBinderFactory;
    import org.springframework.web.context.request.NativeWebRequest;
    import org.springframework.web.context.request.RequestAttributes;
    import org.springframework.web.method.support.HandlerMethodArgumentResolver;
    import org.springframework.web.method.support.ModelAndViewContainer;
    import org.springframework.web.multipart.support.MissingServletRequestPartException;
    
    public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
        @Override
        public boolean supportsParameter(MethodParameter parameter) {
            return parameter.getParameterType().isAssignableFrom(LoginUser.class) && parameter.hasParameterAnnotation(CurrentUser.class);
        }
    
        @Override
        public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
            LoginUser loginUser = (LoginUser) webRequest.getAttribute("currentUser", RequestAttributes.SCOPE_REQUEST);
            if (loginUser != null) {
                return loginUser;
            }
            throw new MissingServletRequestPartException("currentUser");
        }
    }
    

    4.CurrentUser注解

    package org.jeecg.modules.yiqing.common.annotation;
    
    import java.lang.annotation.*;
    
    @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface CurrentUser {
    }
    

    相关文章

      网友评论

          本文标题:SpringBoot通过拦截器获取登录信息

          本文链接:https://www.haomeiwen.com/subject/rlxctltx.html