Condivisione della tecnologia

In Springboot, threadlocal viene utilizzato per archiviare le informazioni sull'identità dell'utente nel filtro.

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Questo articolo descrive principalmente il metodo per impostare le informazioni jwt nel filtro per salvare le informazioni sull'identità tramite la classe filtro di Springboot.
Processo: Richiesta->Filtro->Analizza le informazioni sul corpo della richiesta->Inseriscilo in threadlocal

Definisci filtro: un filtro (Filter) che utilizza la specifica Servlet, registrata tramite l'annotazione @WebFilter per intercettare tutte le richieste HTTP corrispondenti al percorso /api.

L'annotazione @WebFilter("/api") specifica che il filtro verrà applicato a tutte le richieste che accedono al percorso /api.
@Annotazione componente:

@Component è un'annotazione del framework Spring, che indica che JwtFilter è un componente Spring che può essere gestito dal contenitore Spring e supporta l'iniezione di dipendenze.
Metodo doFilter:
Il metodo doFilter definisce il modo in cui il filtro intercetta ed elabora le richieste e le risposte che entrano nel Servlet o nel contenitore Servlet.
Firma del metodo:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException;
  • 1
  • 2

Questo metodo accetta tre parametri: richiesta ServletRequest, risposta ServletResponse e catena FilterChain.
Potrebbe lanciare IOException o ServletException.
Richiesta e risposta:

I primi due parametri del metodo doFilter rappresentano la richiesta corrente e gli oggetti di risposta. In questo metodo è possibile leggere i dati della richiesta e modificare le richieste e le risposte.
In genere, alla fine del metodo doFilter, è necessario chiamare chain.doFilter(richiesta, risposta) per continuare l'esecuzione del filtro successivo o della risorsa di destinazione nella catena di filtri.

Se desideri modificare nuovamente il contenuto della richiesta, puoi utilizzare HttpServletRequestWrapper HttpServletRequestWrapper è una classe wrapper che estende l'interfaccia HttpServletRequest, consentendoti di modificare o estendere l'elaborazione della richiesta. Gli scopi per l'utilizzo di HttpServletRequestUriWrapper (che può essere una classe wrapper personalizzata che eredita da HttpServletRequestWrapper) in genere includono:

Modifica l'URI della richiesta:

Potresti voler modificare l'URI della richiesta, ma non l'oggetto HttpServletRequest originale. Usando HttpServletRequestUriWrapper, puoi racchiudere la richiesta originale e fornire un URI modificato.
Mantieni invariata la richiesta originale:

L'utilizzo di un wrapper mantiene invariato l'oggetto della richiesta originale consentendo allo stesso tempo di modificare alcuni aspetti della richiesta in un determinato punto della catena di filtraggio.
Filtraggio e preelaborazione:

Prima di chiamare filterChain.doFilter, puoi aggiungere qualsiasi logica di preelaborazione nel metodo doFilter, come la modifica dei parametri della richiesta, la modifica dei percorsi della richiesta, l'aggiunta o la modifica delle intestazioni della richiesta, ecc.

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

@WebFilter("/api")
@Component
@Slf4j
public class JwtFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
        // noting to do
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        var httpRequest = (HttpServletRequest) servletRequest;
        var requestBodyPayload = StreamUtils.copyToString(servletRequest.getInputStream(), StandardCharsets.UTF_8);

        // 解析Body参数,并存入threadLocal管理
        var jwtInfo = JwtUtil.getJwtInfoFromReq(requestBodyPayload);
        JwtUtil.setJwtInfo(jwtInfo);

        // 读取过body,需要重新设置body
        var wrapper = new HttpServletRequestUriWrapper(httpRequest, httpRequest.getRequestURI(), requestBodyPayload);

        // 将请求传递到下一个过滤器(或者最终到达控制器方法)
        filterChain.doFilter(wrapper, servletResponse);
    }

    @Override
    public void destroy() {
        JwtUtil.removeJwtInfo();
        MDC.clear();
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

informazioni jwt:

@Slf4j
@Component
public class JwtUtil {

    /** 线程jwt信息维护 */
    private static final ThreadLocal<JwtInfo> REQUEST_BASE_INFO_THREAD_LOCAL = new ThreadLocal<>();

    /** 解析jwt信息 */
    public static JwtInfo getJwtInfoFromReq(String requestBodyPayload) {
        var jwtInfo = new JwtInfo();
        try {
            var requestBody = JsonUtil.getJsonNode(requestBodyPayload);
            log.info("[JwtUtil] RequestBody -> {}", requestBody);

            // 解析requestBody,转为jwtInfo对象
          
            jwtInfo.setRequestId(requestBody.get("RequestId") != null ? requestBody.get("RequestId").asText() : "");
            jwtInfo.setRegion(requestBody.get("Region") != null ? requestBody.get("Region").asText() : "");
            log.info("[JwtUtil] JwtInfo -> {}", jwtInfo);
        } catch (Exception e) {
            log.error("[JwtUtil] Parse RequestBodyInfo Error, Error Message -> {}", e.getMessage(), e);
        }
        return jwtInfo;
    }

    /** 获取jwt信息 */
    public static JwtInfo getJwtInfo() {
        var jwtInfo = REQUEST_BASE_INFO_THREAD_LOCAL.get();
        if (Objects.isNull(jwtInfo)) {
            final var requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (Objects.nonNull(requestAttributes)) {
                var requestBodyPayload = "";
                try {
                    requestBodyPayload = StreamUtils.copyToString(requestAttributes.getRequest().getInputStream(),
                            StandardCharsets.UTF_8);
                } catch (Exception e) {
                    log.error("[JwtUtil] Parse RequestBodyInfo Error, Error Message -> {}", e.getMessage());
                }
                jwtInfo = getJwtInfoFromReq(requestBodyPayload);
                setJwtInfo(jwtInfo);
            }
        }
        return jwtInfo;
    }

    /** 将jwt信息存入threadLocal中 */
    public static void setJwtInfo(JwtInfo jwtInfo) {
        REQUEST_BASE_INFO_THREAD_LOCAL.set(jwtInfo);
        // 将traceId写入日志变量
        MDC.put("traceId", jwtInfo.getRequestId());
    }

    public static void setJwtInfo(String appId, String ownerUin) {
        var jwtInfo = new JwtUtil.JwtInfo();
        jwtInfo.setRequestId(UUID.randomUUID().toString());

        setJwtInfo(jwtInfo);
    }

    /** 从threadLocal中删除jwt信息 */
    public static void removeJwtInfo() {
        REQUEST_BASE_INFO_THREAD_LOCAL.remove();
    }

    @Data
    public static class JwtInfo {

      
        @JsonPropertyDescription("请求requestId")
        private String requestId;


        @JsonPropertyDescription("请求的Region")
        private String region;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77

Ottieni il contenuto in jwt e invia altre richieste http:

   public static JsonNode sendHttpRequest(String method, String action, String url, Map<String, Object> body)
            throws IOException, InterruptedException {

        // 设置通用参数
        var jwtInfo = JwtUtil.getJwtInfo();
        if (jwtInfo != null) {
            body.put("RequestId", jwtInfo.getRequestId());
            body.put("AppId", Integer.valueOf(jwtInfo.getAppId()));
            body.put("Uin", jwtInfo.getUin());
            body.put("Region", jwtInfo.getRegion());
        }

        // 设置action
        body.put("Action", action);

        // 发送http请求,拿到请求结果
        HttpConnectUtil.ResponseInfo responseInfo = switch (method) {
            case "GET" -> HttpConnectUtil.sendGetByJson(url, JsonUtil.toJson(body));
            case "POST" -> HttpConnectUtil.sendPost(url, JsonUtil.toJson(body), new HashMap<>(2));
            default -> new HttpConnectUtil.ResponseInfo();
        };

        // 检查Api3格式返回结果,并解析
        var jsonResponse = JsonUtil.getJsonNode(responseInfo.getContent()).get("Response");
        var jsonError = jsonResponse.get("Error");
        if (jsonError != null) {
            var errorCode = jsonError.get("Code").asText();
            var errorMessage = jsonError.get("Message").asText();
            throw new ApiException(ErrorCode.INTERNAL_ERROR,
                    String.format("错误码:[%s],错误信息:[%s]", errorCode, errorMessage));
        }
        return jsonResponse;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33