参考:

学习-Springboot禁止内置Tomcat不安全的HTTP方法_liutinghui989的博客-CSDN博客

在此省略起因,过程,反正领导让研究咱就研究。

代码:

package com.yunan.framework.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpConfig {
   @Value("${http.port}")
   private int httpPort;

   @Bean
   public ServletWebServerFactory servletContainer() {
      //TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
      TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
         @Override
         protected void postProcessContext(Context context) {
            SecurityConstraint constraint = new SecurityConstraint();
            constraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            collection.addMethod("HEAD");
            collection.addMethod("PUT");
            collection.addMethod("PATCH");
            collection.addMethod("DELETE");
            collection.addMethod("OPTIONS");
            collection.addMethod("TRACE");
            collection.addMethod("COPY");
            collection.addMethod("SEARCH");
            collection.addMethod("PROPFIND");
            constraint.addCollection(collection);
            constraint.setAuthConstraint(true);
            context.addConstraint(constraint);
            context.setUseHttpOnly(true);
            constraint.addCollection(collection);
            context.addConstraint(constraint);
         }
      };
      tomcat.addAdditionalTomcatConnectors(new Connector[] { createStandardConnector() });
      tomcat.addConnectorCustomizers(connector -> {
         connector.setAllowTrace(true);
      });
      return tomcat;
   }

   private Connector createStandardConnector() {
      Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
      connector.setPort(this.httpPort);
      return connector;
   }
}

结果:用jmeter测试 options请求,(trace请求返回有点出入)

 至此,我认为我结束了这次研究,问就是不理解。做到让自己信服就可以了(捂脸

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐