SpringBoot之HandlerInterceptor攔截器的使用

2020-10-26 12:01:22

聆聽 沉澱 傳播 … 關注微信公眾號【架構技術之美】,瞭解更多技術和學習資料

前言

平常專案開發過程中,會遇到登入攔截許可權校驗引數處理防重複提交等問題,那攔截器就能幫我們統一處理這些問題。

一、實現方式

1.1 自定義攔截器

自定義攔截器,即攔截器的實現類,一般有兩種自定義方式:

  1. 定義一個類,實現org.springframework.web.servlet.HandlerInterceptor介面。
  2. 定義一個類,繼承已實現了HandlerInterceptor介面的類,例如org.springframework.web.servlet.handler.HandlerInterceptorAdapter抽象類。

1.2 新增Interceptor攔截器到WebMvcConfigurer設定器中

自定義設定器,然後實現WebMvcConfigurer設定器。

以前一般繼承org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter類,不過SrpingBoot 2.0以上WebMvcConfigurerAdapter類就過時了。有以下2中替代方法:

  1. 直接實現org.springframework.web.servlet.config.annotation.WebMvcConfigurer介面。(推薦)
  2. 繼承org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport類。但是繼承WebMvcConfigurationSupport會讓SpringBoot對mvc的自動設定失效。不過目前大多數專案是前後端分離,並沒有對靜態資源有自動設定的需求,所以繼承WebMvcConfigurationSupport也未嘗不可。

二、HandlerInterceptor 方法介紹

  1. preHandle:預處理,在業務處理器處理請求之前被呼叫,可以進行登入攔截,編碼處理、安全控制、許可權校驗等處理;
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	return true;
}
  1. postHandle:後處理,在業務處理器處理請求執行完成後,生成檢視之前被呼叫。即呼叫了Service並返回ModelAndView,但未進行頁面渲染,可以修改ModelAndView,這個比較少用。
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable ModelAndView modelAndView) throws Exception {
}
  1. afterCompletion:返回處理,在DispatcherServlet完全處理完請求後被呼叫,可用於清理資源等。已經渲染了頁面。
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
}

三、攔截器(Interceptor)實現

3.1 實現HandlerInterceptor

此攔截器演示了通過註解形式,對使用者許可權進行攔截校驗。

package com.nobody.interceptor;

import com.nobody.annotation.UserAuthenticate;
import com.nobody.context.UserContext;
import com.nobody.context.UserContextManager;
import com.nobody.exception.RestAPIError;
import com.nobody.exception.RestException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @Description
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Slf4j
@Component
public class UserPermissionInterceptor implements HandlerInterceptor {

    private UserContextManager userContextManager;

    @Autowired
    public void setContextManager(UserContextManager userContextManager) {
        this.userContextManager = userContextManager;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) {

        log.info(">>> UserPermissionInterceptor preHandle -- ");

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            // 獲取使用者許可權校驗註解(優先獲取方法,無則再從類獲取)
            UserAuthenticate userAuthenticate =
                    handlerMethod.getMethod().getAnnotation(UserAuthenticate.class);
            if (null == userAuthenticate) {
                userAuthenticate = handlerMethod.getMethod().getDeclaringClass()
                        .getAnnotation(UserAuthenticate.class);
            }
            if (userAuthenticate != null && userAuthenticate.permission()) {
                // 獲取使用者資訊
                UserContext userContext = userContextManager.getUserContext(request);
                // 許可權校驗
                if (userAuthenticate.type() != userContext.getType()) {
                    // 如若不丟擲異常,也可返回false
                    throw new RestException(RestAPIError.AUTH_ERROR);
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) {
        log.info(">>> UserPermissionInterceptor postHandle -- ");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) {
        log.info(">>> UserPermissionInterceptor afterCompletion -- ");
    }
}

3.2 繼承HandlerInterceptorAdapter

package com.nobody.interceptor;

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

import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @Description
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Slf4j
@Component
public class UserPermissionInterceptorAdapter extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) {
        log.info(">>> UserPermissionInterceptorAdapter preHandle -- ");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) {
        log.info(">>> UserPermissionInterceptorAdapter postHandle -- ");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) {
        log.info(">>> UserPermissionInterceptorAdapter afterCompletion -- ");
    }
}

四、設定器(WebMvcConfigurer)實現

4.1 實現WebMvcConfigurer(推薦)

package com.nobody.config;

import com.nobody.context.UserContextResolver;
import com.nobody.interceptor.UserPermissionInterceptor;
import com.nobody.interceptor.UserPermissionInterceptorAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @Description
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {

    private UserPermissionInterceptor userPermissionInterceptor;

    private UserPermissionInterceptorAdapter userPermissionInterceptorAdapter;

    private UserContextResolver userContextResolver;

    @Autowired
    public void setUserPermissionInterceptor(UserPermissionInterceptor userPermissionInterceptor) {
        this.userPermissionInterceptor = userPermissionInterceptor;
    }

    @Autowired
    public void setUserPermissionInterceptorAdapter(
            UserPermissionInterceptorAdapter userPermissionInterceptorAdapter) {
        this.userPermissionInterceptorAdapter = userPermissionInterceptorAdapter;
    }

    @Autowired
    public void setUserContextResolver(UserContextResolver userContextResolver) {
        this.userContextResolver = userContextResolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 可以新增多個攔截器,一般只新增一個
        // addPathPatterns("/**") 表示對所有請求都攔截
        // .excludePathPatterns("/base/index") 表示排除對/base/index請求的攔截
        // 多個攔截器可以設定order順序,值越小,preHandle越先執行,postHandle和afterCompletion越後執行
        // order預設的值是0,如果只新增一個攔截器,可以不顯示設定order的值
        registry.addInterceptor(userPermissionInterceptor).addPathPatterns("/**")
                .excludePathPatterns("/base/index").order(0);
        // registry.addInterceptor(userPermissionInterceptorAdapter).addPathPatterns("/**")
        // .excludePathPatterns("/base/index").order(1);
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(userContextResolver);
    }
}

4.2 繼承WebMvcConfigurationSupport

package com.nobody.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import com.nobody.interceptor.UserPermissionInterceptor;
import com.nobody.interceptor.UserPermissionInterceptorAdapter;

/**
 * @Description
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Configuration
public class WebAppConfigurerSupport extends WebMvcConfigurationSupport {

    @Autowired
    private UserPermissionInterceptor userPermissionInterceptor;

    // @Autowired
    // private UserPermissionInterceptorAdapter userPermissionInterceptorAdapter;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 可以新增多個攔截器,一般只新增一個
        // addPathPatterns("/**") 表示對所有請求都攔截
        // .excludePathPatterns("/base/index") 表示排除對/base/index請求的攔截
        registry.addInterceptor(userPermissionInterceptor).addPathPatterns("/**")
                .excludePathPatterns("/base/index");
        // registry.addInterceptor(userPermissionInterceptorAdapter).addPathPatterns("/**")
        // .excludePathPatterns("/base/index");
    }
}

五、其他主要輔助類

5.1 使用者上下文類

package com.nobody.context;

import com.nobody.enums.AuthenticationTypeEnum;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @Description 使用者上下文
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Getter
@Setter
@ToString
public class UserContext {
    // 使用者名稱稱
    private String name;
    // 使用者ID
    private String userId;
    // 使用者型別
    private AuthenticationTypeEnum type;
}

5.2 校驗存取許可權註解

package com.nobody.annotation;

import com.nobody.enums.AuthenticationTypeEnum;

import java.lang.annotation.*;

/**
 * @Description 校驗存取許可權註解
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface UserAuthenticate {
    /**
     * 是否需要校驗存取許可權 預設不校驗
     * 
     * @return
     */
    boolean permission() default false;

    /**
     * 驗證型別,預設遊客
     * 
     * @return
     */
    AuthenticationTypeEnum type() default AuthenticationTypeEnum.VISITOR;
}

5.3 使用者上下文操作類

package com.nobody.context;

import com.nobody.enums.AuthenticationTypeEnum;
import com.nobody.exception.RestAPIError;
import com.nobody.exception.RestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.UUID;

/**
 * @Description 使用者上下文操作類
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Component
public class UserContextManager {

    private static final String COOKIE_KEY = "__userToken";

    // @Autowired
    // private RedisService redisService;

    /**
     * 獲取使用者上下文資訊
     * 
     * @param request
     * @return
     */
    public UserContext getUserContext(HttpServletRequest request) {
        String userToken = getUserToken(request, COOKIE_KEY);
        if (!StringUtils.isEmpty(userToken)) {
            // 從快取或者第三方獲取使用者資訊
            // String userContextStr = redisService.getString(userToken);
            // if (!StringUtils.isEmpty(userContextStr)) {
            // return JSON.parseObject(userContextStr, UserContext.class);
            // }
            // 因為演示,沒整合Redis,故簡單new物件
            UserContext userContext = new UserContext();
            userContext.setName("Mr.nobody");
            userContext.setUserId("0000001");
            userContext.setType(AuthenticationTypeEnum.ADMIN);
            return userContext;
        }
        throw new RestException(RestAPIError.AUTH_ERROR);
    }

    public String getUserToken(HttpServletRequest request, String cookieKey) {
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (Objects.equals(cookie.getName(), cookieKey)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 儲存使用者上下文資訊
     * 
     * @param response
     * @param userContextStr
     */
    public void saveUserContext(HttpServletResponse response, String userContextStr) {
        // 使用者token實際根據自己業務進行生成,此處簡單用UUID
        String userToken = UUID.randomUUID().toString();
        // 設定cookie
        Cookie cookie = new Cookie(COOKIE_KEY, userToken);
        cookie.setPath("/");
        response.addCookie(cookie);
        // redis快取
        // redisService.setString(userToken, userContextStr, 3600);
    }

}

5.4 方法引數解析器類

package com.nobody.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 對有UserContext引數的介面,進行攔截注入使用者資訊
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@Component
@Slf4j
public class UserContextResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UserContextManager userContextManager;

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        log.info(">>> resolveArgument -- begin...");
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        // 從快取獲取使用者資訊賦值到介面引數中
        return userContextManager.getUserContext(request);
    }

    /**
     * 只對UserContext引數進行攔截賦值
     * 
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if (methodParameter.getParameterType().equals(UserContext.class)) {
            return true;
        }
        return false;
    }
}

六、測試驗證

package com.nobody.controller;

import com.alibaba.fastjson.JSON;
import com.nobody.annotation.UserAuthenticate;
import com.nobody.context.UserContext;
import com.nobody.context.UserContextManager;
import com.nobody.enums.AuthenticationTypeEnum;
import com.nobody.pojo.model.GeneralResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @Description
 * @Author Mr.nobody
 * @Date 2020/10/25
 * @Version 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserContextManager userContextManager;

    @GetMapping("login")
    public GeneralResult<UserContext> doLogin(HttpServletResponse response) {
        UserContext userContext = new UserContext();
        userContext.setUserId("0000001");
        userContext.setName("Mr.nobody");
        userContext.setType(AuthenticationTypeEnum.ADMIN);
        userContextManager.saveUserContext(response, JSON.toJSONString(userContext));
        return GeneralResult.genSuccessResult(userContext);
    }

    @GetMapping("personal")
    @UserAuthenticate(permission = true, type = AuthenticationTypeEnum.ADMIN)
    public GeneralResult<UserContext> getPersonInfo(UserContext userContext) {
        return GeneralResult.genSuccessResult(userContext);
    }
}

啟動服務後,在瀏覽器先呼叫personal介面,因為沒有登入,所以會報錯沒有許可權:
在這裡插入圖片描述
控制檯輸出:
在這裡插入圖片描述

啟動服務後,在瀏覽器先存取login介面進行登入,再存取personal介面,驗證通過,正確返回使用者資訊:

在這裡插入圖片描述
在這裡插入圖片描述

七、Github專案

專案工程可從Github獲取,https://github.com/LucioChn/springboot-common.git