TOMCAT的安全控制策略是根據Servlet 2.4規范來實現的。
1.在$CATALINA/conf/server.xml文件中配置:
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" debug="0" resourceName="UserDatabase"/>
這里UserDatabase是一個jndi的名稱,也需要在server.xml中配置,對應于$CATALINA/conf/tomcat-users.xml文件
2.tomcat-users.xml文件里面定義了用戶和角色
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="manager"/>
<role rolename="admin"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="manager" password="tomcat" roles="manager"/>
<user username="admin" password="tomcat" roles="admin"/>
</tomcat-users>
3.在相應的應用的web.xml文件中加入<security-constraint><login-config> <security-role>標簽,如下所示:
<!-- Security is active on entire directory -->
<security-constraint>
<display-name>Tomcat Server Configuration Security Constraint</display-name>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<!-- Define the context-relative URL(s) to be protected -->
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<!-- Anyone with one of the listed roles may access this area -->
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<!-- Login configuration uses form-based authentication -->
<login-config>
<auth-method>FORM</auth-method>
<realm-name>Tomcat Server Configuration Form-Based Authentication Area</realm-name>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>
<!-- Security roles referenced by this web application -->
<security-role>
<description>
The role that is required to log in to the Administration Application
</description>
<role-name>admin</role-name>
</security-role>
4.在 <login-config>標簽的<auth-method>FORM</auth-method>屬性中,可以看到這里的authentication method 設置為FORM,這是一種基于表單的用戶認證方式。基于form的用戶認證需要在<form-login-page>/login.jsp</form-login-page>定義的登陸頁面中提供一個包括用戶名和密碼的html表單,這個表單相對應于用戶名和密碼的元素必須是j_username和j_password,并且表單的ACTION必須為j_security_check。譬如:
<form method="POST" action="j_security_chack">
<input type="text" name="j_username">
<input type="password" name="j_password">
</form>
在驗證通過之后,login頁面會自動轉向該應用的默認頁面(index.html,index.jsp等等)。
除了FORM驗證方式之外,還有BASIC和CLIENT-CERT這兩種用戶認證方式,前者是基本的用戶認證方式,要求瀏覽器彈出一個對話框,錄入用戶名和密碼。后者是使用客戶數字證書來認證請求。
5.以上四步完成之后便可以通過在tomcat-users.xml文件中添加用戶和角色來實現訪問控制了。還是比較方面的。