2024-01-24|今天做了什么

今天做了什么:

  1. 观看 B 站视频《鸟宝的春天11_security编码实现

    1. 参考视频中示例使用 SecurityFilterChain DSL 语法实现用户名密码登录功能。

    2. 扩展 WebAuthenticationDetails ,修改客户端 IP 获取方式,并记录服务端 IP。

      public class CustomWebAuthenticationDetails extends WebAuthenticationDetails {
          private static final long serialVersionUID = 4441359628463408329L;
          @Getter
          private final String serverAddress;
      
          public CustomWebAuthenticationDetails(final HttpServletRequest request, final String serverAddress) {
              super(HttpRequestUtils.getClientIp(request), extractSessionId(request));
              this.serverAddress = serverAddress;
          }
      
          protected static String extractSessionId(final HttpServletRequest request) {
              final HttpSession session = request.getSession(false);
              return (session != null) ? session.getId() : null;
          }
      }
      

      获取客户端 IP 使用了 HttpRequestUtils 类,实际上就是从 Request 的 header 中获取 IP。

       		private static final List<String> CLIENT_IP_HEADER_NAMES = Arrays.asList("X-Forwarded-For",
                  "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR");
      
      		public static String getClientIp(HttpServletRequest request, String... otherHeaderNames) {
              if (request == null) {
                  return null;
              }
              if (ArrayUtils.isNotEmpty(otherHeaderNames)) {
                  CLIENT_IP_HEADER_NAMES.addAll(Arrays.asList(otherHeaderNames));
              }
      
              String ip;
              for (String header : CLIENT_IP_HEADER_NAMES) {
                  ip = request.getHeader(header);
                  if (!NetUtils.isUnknown(ip)) {
                      return NetUtils.getMultistageReverseProxyIp(ip);
                  }
              }
      
              ip = request.getRemoteHost();
              return NetUtils.getMultistageReverseProxyIp(ip);
          }
      
Share this post:

Related content