安全域这是Tomcat服务器用来保护Web应用资源的一种机制。一个用户可以拥有一个或多个角色,每个角色限定了可访问的Web资源,这样就将用户和Web资源对应起来了。在org.apache.catalina.Realm接口中声名了将用户名、口令和角色相管理的方法,Tomcat5提供了4个实现这一接口的类,分别为:MemoryRealm(XML文件读取)、JDBCRealm(JDBC驱动程序读取)、DataSourceRealm(JNDI数据源读取)、JNDIRealm(JNDI provider读取LDAP的目录服务器信息)。
Web资源的设置需要在web.xml文件中加入<security-constraint>、<login-config>、<security-role>元素。例如在Tomcat的admin应用中的配置:
<security-constraint> <display-name>Tomcat Server Configuration Security Constraint</display-name> <web-resource-collection> <web-resource>Protected Area</web-resource> <url-pattern>*.htm</url-pattern> <url-pattern>*.jsp</url-pattern> <url-pattern>*.do</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint> </security-constraint>上面的代码表明:只有admin角色才能访问admin应用中的*.jsp、*.do和*.html资源。另一个例子是jsp-examples应用:
<sercurity-constraint> <display-name>Tomcat Server Configuration Security Constraint</display-name> <web-resource-collection> <web-resource>Protected Area</web-resource> <url-pattern>/security/protected/*</url-pattern> <http-method>DELETE</http-method> <http-method>GET</http-method> <http-method>POST</http-method> <http-method>PUT</http-method> </web-resource-collection> <auth-constraint> <role-name>tomcat</role-name> <role-name>role1</role-name> </auth-constraint> </security-constraint>上面的代码表明:只要tomcat和role1角色才可以以DELETE、GET、POST和GET方式访问jsp-exzmples应用URL为/security/protected/下的资源。在web.xml中加入<login-config>元素-系统会以对话框的方式进行登陆
<login-config> <auth-method>FORM</auth-method> <realm-name>Tomcat Configuration Form-Baseed Authenticaton Area</realm-name> <from-login-config > <from-login-page>/login/login.jsp</from-login-page> <from-error-page>/error.jsp</from-error-page> <from-login-config> </login-config><auth-method>有三个可选项:BASIC、DIGEST、FORM。BASIC-基本验证:访问受保护资源时,会弹出一对话框。要求输入用户名和密码,如果连续3次失败后,会显示一个错误页面。这个方法的缺点是用户名和密码的数据传输采用的是Base64编码(可读文本),是非常不安全的。DIGEST-摘要验证:数据采用MD5对用户名和密码进行加密,然后再传输,显然这种方法很安全。FORM-表单验证:可以使用自定义的登陆页面,但用户名对应的文本框名称必须是j_username,密码为j_password,且表单action值为j_security_check。在web.xml中加入<security-role>元素-指明这个Web应用应用的所有角色的名字
<security-role> <description>The role that is required to lon in to the Administration Application.</description> <role-name>admin</role-name> <role-name>friend</role-name> </security-role>你可以调用HttpRequeset接口的getRemoteUser()方法返回当前用户的名字:<%=request.getRemoteUser()%>
内存域-由org.apache.catalina.realm.MemoryRelam类实现小猫启动时,自动读取<
