首頁  >  文章  >  Java  >  SpringBoot透過ThreadLocal怎麼實現登入攔截

SpringBoot透過ThreadLocal怎麼實現登入攔截

WBOY
WBOY轉載
2023-05-22 12:04:421310瀏覽

    1 前言

    註冊登入可以說是平時開發中最常見的東西了,但是一般進入到公司之後,像這樣的功能早就開發完了,除非是新的專案。這兩天就碰巧遇到了這樣一個需求,完成pc端的註冊登入功能。

    實現這樣的需求有很多種方式:像

    1)HandlerInterceptor WebMvcConfigurer ThreadLocal

    2)Filter過濾器

    #3)安全框架Shiro(輕量級框架)

    4)安全框架Spring Securety(重量級框架)

    而我採用的是第一種Spring HandlerInterceptor WebMvcConfigurer ThreadLocal技術來實現。

    2 特定類別

    2.1HandlerInterceptor

    HandlerInterceptor是springMVC中為攔截器提供的接口,類似於Servlet開發中的過濾器Filter,用於處理器進行預處理和後處理,需要重寫三個方法。

    preHandle:

    呼叫時間:controller方法處理之前

    執行順序: 鍊式Intercepter情況下,Intercepter依照宣告順序一個接一個執行

    #若回傳false,中斷執行,注意:不會進入afterCompletion

    postHandle:

    呼叫前提:preHandle傳回true

    呼叫時間:Controller方法處理完之後,DispatcherServlet進行視圖渲染之前,也就是說在這個方法中可以對ModelAndView進行操作

    執行順序:鍊式Interceptor情況下,Intercepter按照宣告順序執行

    備註:postHandle雖然是post開頭,但是post請求,get請求都能處理

    afterCompletion:

    呼叫前提:preHandle傳回true

    呼叫時間:DispatcherServlet進行視圖的渲染之後

    多用於清理資源

    2.2WebMvcConfigurer

    WebMvcConfigurer設定類別其實是Spring內部的一種設定方式,採用JavaBean的形式來代替傳統的xml設定檔形式進行針對框架個性化定制,可以自訂一些Handler,Interceptor,ViewResolver,MessageConverter。基於java-based方式的spring mvc配置,需要建立一個配置類別並實作WebMvcConfigurer介面;

    在Spring Boot 1.5版本都是靠重寫WebMvcConfigurerAdapter的方法來新增自訂攔截器,訊息轉換器等。在SpringBoot 2.0版本之後,該類別已經被標記為@Deprecated(不建議使用)。官方推薦直接實作WebMvcConfigurer或直接繼承WebMvcConfigurationSupport,方式一實作WebMvcConfigurer介面(建議),方式二繼承WebMvcConfigurationSupport類別

    3 程式碼實踐

    1)編寫攔截器HeadTokenInterceptor使其繼承HandlerInterceptor使其繼承##

    package com.liubujun.config;
    import com.liubujun.moudle.UserToken;
    import com.liubujun.util.SecurityContextUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.http.HttpStatus;
    import org.springframework.stereotype.Component;
    import org.springframework.util.StringUtils;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.xml.ws.handler.Handler;
    import java.io.IOException;
    /**
     * @Author: liubujun
     * @Date: 2022/5/21 16:12
     */
    @Component
    @Slf4j
    public class HeadTokenInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String authorization = request.getHeader("Authorization");
            if (authorization == null ) {
                unauthorized(response);
                return false;
            }
            //这里一般都会解析出userToken的值,这里为了方便就直接new了
            UserToken userToken  = new UserToken();
            SecurityContextUtil.addUser(userToken);
            return false;
        }
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        }
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            SecurityContextUtil.removeUser();
        }
        private void unauthorized(HttpServletResponse response) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            try {
                response.getWriter().append(HttpStatus.UNAUTHORIZED.getReasonPhrase());
            } catch (IOException e) {
                log.error("HttpServletResponse writer error.msg",HttpStatus.UNAUTHORIZED.getReasonPhrase());
                log.error(e.getMessage(),e);
            }
        }
    }

    2)編寫MyWebMvcConfigurer使其繼承WebMvcConfigurationSupport

    package com.liubujun.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.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import java.util.ArrayList;
    /**
     * @Author: liubujun
     * @Date: 2022/5/21 16:40
     */
    @Configuration
    public class MyWebMvcConfigurer extends WebMvcConfigurationSupport {
        @Autowired
        private HeadTokenInterceptor headTokenInterceptor;
        /**
         * 类似于白名单,在这边添加的请求不会走拦截器
         * @param registry
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            ArrayList<String> pattres = new ArrayList<>();
            pattres.add("/login/login");
            registry.addInterceptor(headTokenInterceptor).excludePathPatterns(pattres).addPathPatterns("/**");
            super.addInterceptors(registry);
        }
        /**
         * 添加静态资源
         * @param registry
         */
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("xxx.html")
                    .addResourceLocations("classpath:/META-INF/resources");
            super.addResourceHandlers(registry);
        }
    }

    3)編寫ThreadLocal類別存放使用者資訊

    package com.liubujun.util;
    import com.liubujun.moudle.UserToken;
    import org.springframework.core.NamedThreadLocal;
    /**
     * @Author: liubujun
     * @Date: 2022/5/23 9:41
     */
    public class SecurityContextUtil {
        private static ThreadLocal<UserToken> threadLocal = new NamedThreadLocal<>("user");
        public static void addUser(UserToken user){
            threadLocal.set(user);
        }
        public static UserToken getUser(){
            return threadLocal.get();
        }
        public static void removeUser(){
            threadLocal.remove();
        }
        public static String getPhoneNumber(){
            return threadLocal.get().getPhoneNumber();
        }
        public static Integer getId(){
            return threadLocal.get().getId();
        }
        public static String getUserText(){
            return threadLocal.get().getUserText();
        }
    }

    4)編寫測試controller

    @RestController
    @RequestMapping(value = "/login",produces = {"application/json;charset=UTF-8"})
    public class Login {
        @PostMapping("/login")
        public String login(){
            return "登录请求不需要拦截";
        }
        @PostMapping("/other")
        public String other(){
            return "其他的请求需要拦截";
        }
    }

    5)測試

    測試login接口,(不傳token直接放行)

    SpringBoot透過ThreadLocal怎麼實現登入攔截

    #測試其他接口,不傳token被攔截到

    SpringBoot透過ThreadLocal怎麼實現登入攔截

    以上是SpringBoot透過ThreadLocal怎麼實現登入攔截的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述:
    本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除