如何在不更改tomcat-users.xml的情况下为静态tomcat webapps提供基本的http身份验证?



我可以访问tomcat管理器并上传war-files。其中一个war是静态web项目(压缩html +媒体文件,重命名为*.war)。我想添加一个Web-INF/web.xml文件,以保护与基本http授权的内容。

我知道如何通过在tomcat-users.xml中添加全局用户和分配角色来做到这一点,但是我想在我的war文件中定义所有用户名和密码。

    可以在不触及tomcat的tomcat-users.xml的情况下完成吗?
  1. 如果是,我如何在我的静态项目的web.xml中指定这个?

Thx,尤文

我找到了一个解决方案:http://wiki.metawerx.net/wiki/SecuringYourSiteWithContainerManagedSecurity

该页描述了如何定义指向自己的WEB-INF/users.xml的自己的META-INF/context.xml。不幸的是,到users.xml文件的链接必须是绝对的,并且我不想对配置文件中的OS/文件系统路径做任何假设。

这是我当前的WEB-INF/web.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
    version="2.5">
    <display-name>SuperCoolTool</display-name>
    <description>What an awesome app!</description>
    <security-role>
        <role-name>manager</role-name>
    </security-role>
    <security-role>
        <role-name>keyuser</role-name>
    </security-role>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>
                Entire Application
            </web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>keyuser</role-name>
            <role-name>manager</role-name>
        </auth-constraint>
    </security-constraint>
    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>Evaluation Area</realm-name>
    </login-config>
</web-app> 

一个匹配的META-INF/context.xml看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Realm className="org.apache.catalina.realm.MemoryRealm"
           pathname="[PATH-TO-YOUR-WEBAPP]/WEB-INF/users.xml"/>
</Context>

如果你知道tomcat放置所有已部署应用的目录,你可以使用相对路径(因为它们是相对于catalina进行解析的)。env基地。变量,即tomcat home)。

例如,如果你使用eclipse IDE部署,通常应用程序部署在wtpwebapps中,所以你可以使用:

<Realm className="org.apache.catalina.realm.MemoryRealm"
pathname="wtpwebapps/YOUR_APP_NAME/WEB-INF/users.xml"/>

还不完美,但至少你没有使用全路径。

另一种选择是实现您自己的Realm,它扩展MemoryRealm并在调用super.setPathname();

之前预处理路径名。

你也可以选择DataSourceRealm,它没有这个问题,适合生产。

对于独立于servlet容器的方法,您可以使用基于过滤器的安全框架(例如Spring安全,…)

最新更新