如何在Tomcat中使用htpasswd保护?
-
09-09-2019 - |
题
我已经使用 Apache 的 htpasswd 命令创建了一个用户数据库文件。该文件现在被其他几个应用程序使用,例如 apache 和 subversion。
用户的创建方式如下:
htpasswd /path/to/users.htpasswd peter
该用户文件是全局的,而不是每个目录。
如何让 Tomcat 6 使用同一个文件作为安全领域?
其他提示
与 htpasswd 最相似的可能是 内存领域。我自己在找到如何使用它的简单示例时遇到了问题,因此我将在这里发布一个简单的示例代码:
在 tomcat-users.xml 中设置角色、用户名和密码
您的 web.xml 应包含类似以下内容:
<security-constraint> <web-resource-collection> <web-resource-name> My Protected WebSite </web-resource-name> <url-pattern> /* </url-pattern> <http-method> GET </http-method> <http-method> POST </http-method> </web-resource-collection> <auth-constraint> <!-- the same like in your tomcat-users.conf file --> <role-name> test </role-name> </auth-constraint> </security-constraint> <login-config> <auth-method> BASIC </auth-method> <realm-name> Basic Authentication </realm-name> </login-config> <security-role> <description> Test role </description> <role-name> test </role-name> </security-role>
将其添加到您的 server.xml 文件中:
<Realm className="org.apache.catalina.realm.MemoryRealm"></Realm>
为了保护对 Tomcat Web 应用程序的访问,您可以实施简单的安全约束(例如在 /var/lib/tomcat7/webapps/*/WEB-INF/web.xml
)如下(只需在之前添加 </web-app>
结尾):
<!-- This security constraint protects your webapp interface. -->
<login-config>
<!-- Define the Login Configuration -->
<auth-method>BASIC</auth-method>
<realm-name>Webapp</realm-name>
</login-config>
<security-constraint>
<web-resource-collection>
<web-resource-name>Admin</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>*</role-name>
</auth-constraint>
<!-- Specifying a Secure Connection -->
<user-data-constraint>
<!-- transport-guarantee can be CONFIDENTIAL (forced SSL), INTEGRAL, or NONE -->
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<!-- Authorization, see: tomcat-users.xml -->
<security-role>
<role-name>*</role-name>
</security-role>
登录配置元素包含
auth-method
元素,它指定我们使用的身份验证方法,即BASIC
. 。这security-constraint
元素包含3个元素:web-resource-collection
,auth-constraint
, , 和user-data-constraint
. 。Web-resource-collection 指定了我们的应用程序中需要身份验证的部分。这/*
表示整个应用程序需要身份验证。auth-constraint 指定用户访问受保护资源所需的角色。用户数据约束的传输保证可以是NONE
,CONFIDENTIAL
或者INTEGRAL
. 。我们将其设置为NONE
, ,这意味着重定向到SSL
当您尝试访问受保护的资源时不需要。
还要确保你已经线路:
<Realm className="org.apache.catalina.realm.MemoryRealm" />
在你的里面 conf/server.xml
(Engine
部分)。
如果您没有更改任何配置文件,请检查该文件 conf/tomcat-users.xml
在您的安装中(locate tomcat-users.xml
)。该文件必须包含允许您使用 Tomcat Web 应用程序的凭据。
例如,将 manager-gui 角色添加到名为的用户 tomcat
密码为 s3cret
, ,将以下内容添加到上面列出的配置文件中:
<role rolename="manager-gui"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>
然后您可以从以下位置访问您的网络应用程序管理器 /manager/html
(例如。配置更改后重新加载)。
阅读更多: 经理应用程序操作指南.
然后重新启动 Tomcat,当访问您的 Web 应用程序时,它应该要求您提供正确的凭据。
也可以看看:
- Java 中的 HTTP 基本身份验证 在甲骨文网站
- 在 Java 中指定身份验证机制 在甲骨文网站
- 领域配置指南 在 Apache Tomcat 站点
- 在 tomcat 中设置基于角色的安全性
- 如何在 Tomcat 中使用基本身份验证?