Tomcat web程序安全机制 (转载)
在tomat web服务器中,可以有两种主要的方式来对用户,角色,以及领域进行定义。一种使用简单的xml用户定义的内存realm的验证方式,另外一种是建立数据库连接的jdbc realm验证方式。这两种安全机制定制用户信息来源。一,内存(memoryrealm)验证方式:
web程序的拥护,角色,分组在tomcat的/conf/tomat-users.xml文件中定义。这个xml文件列出web服务器允许的用户名称,密码以及对应的分组等。
例如:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="role1" password="tomcat" roles="role1"/>
</tomcat-users>
这里就定义了两个角色,三个用户以及对应的密码。
要使以上的配置文件作用于定义域,就要在server.xml把这个文件定义成为一个数据资源。其目的就是高速web服务器能够在这个文件中找到相关的用户信息。这个定义在tomcat是默认定义的。定义在<GlobalNamingResources>元素中:
<!-- Global JNDI resources -->
<GlobalNamingResources>
<!-- Test entry for demonstration purposes -->
<Environment name="simpleValue" type="java.lang.Integer" value="30"/>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users -->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>
可以看到pathname="conf/tomcat-users.xml"调用上面的那个配置好的文件。虽然这种方式比较简单,但存在着一定问题,比如手动输入,一旦数据多了就很麻烦等。而且保密效果不是很好,xml各式的文件谁都可以打开直接看到。
二,JDBC realm
首先也是在server.xml文件中<Realm>元素中配置一个使用mysql数据库的realm
在TOMCAT的server.xml中配置JDBC域验证
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mydb"
connectionName="root" connectionPassword="novell"
userTable="users" userNameCol="user_name" userCredCol="user_pass"
userRoleTable="user_roles" roleNameCol="role_name" />
<!--当然别望了在Mysql中建立相应的数据表和字段 -->
当中的系数名字不解释了...
对应的表格
create table users(user_name varchar(15) null primary key,
user_pass varhcar(20) not null);
create tabel user_roles( user_name varchar(15) not null,
role_naem varchar(20) not null,
primary key(user_name,role_name));
现在简单介绍一下基本的验证方式
首先我们应该在web.xml文件中对需要保护的资源定义一个<security-constraint>比如你要限制url为当前web目中的所有文件/*
<security-constraint>
<web-resource-collection>
<web-resource-name>BasicLogin</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<!-- NOTE: This role is not present in the default users file -->
<role-name>tomcat</role-name>
</auth-constraint>
<user-data-constraint>
<description> no description</description>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>default</realm-name>
</login-config>
其中<web-resource-collection>标记中url-pattern制定保护了url,http-method定义了限定web的请求方法,<auth-constrain>标记了role-name制定了合法用户的角色。<user-data-constraint>中定义了不需要通信的保证。当然了还需要申明使用了基本的验证方式和使用默认的realm.声明部分在上面红色部分给出,即<login-config>.这样的话当浏览器请求
页:
[1]