完整的配置
<Realm className="org.apache.catalina.realm.JDBCRealm" driverName="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/数据库名称?user=用户名&password=密码" userTable="A" userNameCol="B" userCredCol="C" digest="MD5" userRoleTable="D" roleNameCol="E"/>
可以在web.xml中也可以在tomcat目录中的conf/tomcat-users.xml中设置,示例:
web.xml中
<security-role> <role-name>dude</role-name> </security-role>
... <role rolename="tomcat"/> <role rolename="role1"/> </tomcat-users>
2.用户表
在此只说jdbc,当然要说表了,表就是你的用户都在哪放着,tomcat只要求你提供表名(A),登陆时使用的用户名(B)在哪个列可以找到,登陆时使用的密码(C)在哪个列可以找到,
userTable="A" userNameCol="B" userCredCol="C"多说两点:
1.用户表可有更多的列,只不过tomcat实现的ServletSecurity只关心这两列(用户名和密码),当然这是在认证为表单的前提下,如果你的应用不是基于表单认证,可以不要继续看下去.如果是,你的web.xml一定要有以下配置
... <login-config> <auth-method>FORM</auth-method> <realm-name>Tomcat Host Manager Application</realm-name> <form-login-config> <form-login-page>/login.html</form-login-page> <form-error-page>/deny.html</form-error-page> </form-login-config> </login-config> </web-app>
<form action="j_security_check" method="post"> name:<input name="j_username" /> password:<input type="password" name="j_password" /> <input type="submit" value="denglu" /> </form>
如果没有这个属性,用户的密码是需要明文存储的,这显然是不能接受的,digest的值还决了你的密码列的数据类型或数据长度,可选的值为:SHA, MD2, or MD5,她的说明:
When a standard realm authenticates by retrieving the stored password and comparing it with the value presented by the user, you can select digested passwords by specifying the digest attribute on your <Realm> element. The value for this attribute must be one of the digest algorithms supported by the java.security.MessageDigest class (SHA, MD2, or MD5). When you select this option, the contents of the password that is stored in the Realm must be the cleartext version of the password, as digested by the specified algorithm
http://tomcat.apache.org/tomcat-7.0-doc/realm-howto.html#Digested_Passwords
有了用户,有了角色,还要定义用户和角色之间的关系,就是用户要有哪些角色
userRoleTable="D" roleNameCol="E"
到此配置的部分可说的就结束了,有了角色,有个用户,有了用户和角色的关系,还要定义角色可以访问到的资源(当然包括url了),这个由你自已根据项目的情况着情配置,一个示例
<security-constraint> <web-resource-collection> <web-resource-name>Wildcard means whole app requires authentication</web-resource-name> <url-pattern>/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>dude</role-name> </auth-constraint> ... </security-constraint>