安全域是Tomcat的內置功能,主要有以下幾種安全域:
JDBCRealm
DataSourceRealm
JNDIRealm
MemoryRealm
JAASRealm
在conf/server.xml中配置應用的<Context......>下面的<Realm className="org.apache.catalina.realm.MemoryRealm" />
從一個XML文件中讀取用戶信息,默認的就是tomcat-users.xml
tomcat-users.xml中的角色定義
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="guest"/>
<user username="lee" password="lee" roles="guest"/>
<user username="suoxin" password="suoxin" roles="tomcat,role1"/>
</tomcat-users>
在應用下的web.xml中加入<security-constraint>元素
<security-constraint>
<web-resource-collection>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
<role-name>guest</role-name>
</auth-constraint>
</security-constraint>
在應用下的web.xml中加入<login-config>元素
<login-config>
<auth-method>FORM</auth-method>
<!--這里FORM是基于表單的驗證,會跳轉到mylogin.jsp,如果出錯就到myerror.jsp,
還有基于對話筐的是BASIC關鍵字,但是不安全在網絡傳輸中。摘要驗證DIGEST會采
用MD5(Message Digest Algorithm)加密傳輸-->
<form-login-config>
<form-login-page>/mylogin.jsp</form-login-page>
<form-error-page>/myerror.jsp</form-error-page>
</form-login-config>
</login-config>
mylogin.jsp的action和name必須嚴格規范寫
<form name="form1" id="form1" method="post" action="j_security_check">
<input type="text" name="j_username"/>
<input type="text" name="j_password"/>
<input type="submit" name="Submit" value="提交" />
</form>