java 如何在此代码中将http重定向到https(管理除外)

hmae6n7t  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(171)
@Configuration
@EnableConfigurationProperties
public class SSLConfig {

    @Value("${server.port.http}")
    private int httpPort;

    @Value("${server.port}")
    private int httpsPort;

    @Bean
    public ServletWebServerFactory serverFactory(){
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };

        tomcat.addAdditionalTomcatConnectors(createSslConnector());

        return tomcat;
    }

    private Connector createSslConnector(){
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(httpPort);
        connector.setScheme("http");
        connector.setSecure(false);
        connector.setRedirectPort(httpsPort);
        return connector;
    }

我正在使用这个解决方案。目前,所有用户管理器页面都重定向到https,但您希望管理员页面保持为http。有办法吗?管理员包含在同一个项目中。

jtjikinw

jtjikinw1#

必须添加新的安全集合以进行管理,并将用户约束设置为NONE。
尝试以下内容:

SecurityConstraint securityConstraint = new SecurityConstraint();
   securityConstraint.setUserConstraint("NONE");
   SecurityCollection collection = new SecurityCollection();
   /*for example I will choose /admin as pattern here, you can choose whatever 
   you want*/
   collection.addPattern("/admin/*"); 
   securityConstraint.addCollection(collection);
   context.addConstraint(securityConstraint);

相关问题