【问题标题】:How to restrict access to certain URLs a specific port?如何限制对特定端口的某些 URL 的访问?
【发布时间】:2013-07-16 15:36:23
【问题描述】:

我的 Web 配置声明了三个连接器,端口 8080 上的 http 和端口 8081 和 8082 上的 https。

在我的 servlet 中,我想将对某些 url 模式的访问限制到特定端口,例如对 /Admin 的请求应该被拒绝,除非它在端口 8082 上。这很简单,我可以在 servlet 的服务方法中检查端口号。

但我还需要能够允许客户更改端口。如果客户希望仅在端口 9000(而不是 8083)上允许管理请求,则此策略失败。

我能想到的一种方法是在 server.xml 中向连接器添加一个附加属性,并在 servlet 中访问它。这可能吗?

为了详细说明,我想在server.xml中添加如下内容

<Connector port="9000" connectorType="admin"....

然后以某种方式在我的 servlet 中对此进行编程,如下所示。我意识到getConnectorProperties 不存在,这只是一个例子。

 if (request.getRequestURL().startsWith("/admin")) {
   String connectorType = request.getConnectionProperties().get("connectorType");
   if (! "admin".equals(connectorType)) {
     // return unauthorized

关于如何解决这个问题的任何其他建议?

【问题讨论】:

    标签: tomcat tomcat7


    【解决方案1】:

    您似乎在为不同的端口使用不同的上下文根 (=apps)。这不应该以编程方式完成。接受不同端口或协议的应用程序在server.xml 中配置了不同的Service 组件:

    <Server>
        <!-- Define one Service for the open app -->
        <Service name="myOpenApp">
            <Connector port="8080"/>
            <Engine name="myOpenApp" defaultHost="localhost">
                <Host name="localhost"> <!-- default appBase is webapps -->
                    <Context docBase="path/to/my/open/app"/>
                    <!-- docBase is relative to appBase but may also refer an absolute path -->
                </Host>
            </Engine>
        </Service>
    
        <!-- and another for the restricted -->
        <Service name="onlyForAdmins">
            <Connector port="8081" SSLEnabled="true" scheme="https"/>
            <Connector port="8082" SSLEnabled="true" scheme="https"/>
            <Engine name="onlyForAdmins" defaultHost="localhost">
                <Host name="localhost"> <!-- default appBase is webapps -->
                    <Context docBase="path/to/admins/only"/>
                    <!-- docBase is relative to appBase but may also refer an absolute path -->
                </Host>
            </Engine>
        </Service>
    </Server>
    

    请注意,这是一个极简示例。

    如果您需要更复杂的 URL 模式,您可以使用应用程序的web.xmls(servlet-mappings 等)。

    基本上,这不是授权错误...这是一个未映射的 URL。您的应用程序只是不支持非 SSL 端口上的管理资源。所以你会得到404 page not found

    【讨论】:

    • 幕后发生了什么?在这种情况下我们是否创建了两个实例?
    • 什么实例?仍然只有一个过程。但是两个......服务:)。服务将连接器绑定到引擎。您可以进一步阅读their docs
    猜你喜欢
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    相关资源
    最近更新 更多