web.xml中的Security Constraint元素

<security-constriant>元素是tomcat用来指示服务器对客户端访问服务端资源进行安全约束。如果不通过验证则报403错误

<security-constraint>

    <web-resource-collection>

      <web-resource-name>test</web-resource-name>

      <url-pattern>/index.jsp</url-pattern>

      <http-method>GET</http-method>

      <http-method>POST</http-method>

      <http-method>PUT</http-method>

    </web-resource-collection>

    <auth-constraint>

      <role-name>pluto</role-name>

    </auth-constraint>

  </security-constraint>

  

  <login-config>

    <auth-method>FORM</auth-method>

    <form-login-config>·

      <form-login-page>/login.jsp</form-login-page>

      <form-error-page>/login.jsp?error=1</form-error-page>

    </form-login-config>

  </login-config>

  <security-role>

    <role-name>pluto</role-name>

  </security-role> 

<security-constriant>包含4个可能的子元素,分别是:web-resource-collection、auth-constraint、user-data-constraint和display-name。

1.web-resource-collection 此元素确定要保护的资源,所有security-constraint元素都必须包含至少一个此项。此元素下面有一个给出任意标识名称的<web-resource-name>、一个确定要保护的URL的url-pattern元素、一个指出此保护所适用的HTTP命令(缺省为所有方法)的http-method元素和一个提供资料的可选description元素组成。如上例中就是当你以GET、POST、PUT方法访问"/index.jsp"时将被限制。我们平时默认是GET方法访问如果把<http-method>GET</http-method>这行注释掉就不会报错了

2.auth-constraint元素指出哪些用户应该具有受保护资源的访问权。此元素应该包含一个或多个标识具有访问权限的用户role-name元素,以及可选的description元素。如果security-constraint中没有auth-constraint子元素,任何身份的用户都可以访问相应的资源,也就是说security-constraint这时实际上不起作用。此元素需要和<login-config>配合使用,<login-config>要紧跟security-constraint后面

3.user-data-constraint 此可选元素指出在访问相关资源时使用的传输层保护

<login-conifg>有四种认证类型

BASIC:HTTP规范,Base64

DIGEST:HTTP规范,数据完整性强一些,但不是SSL

CLIENT-CERT:J2EE规范,数据完整性很强,公共钥匙(PKC)

FORM:J2EE规范,数据完整性非常弱,没有加密,允许有定制的登录界面

如上例,登录界面即login.jsp。这里的FORM方式需要说明的是,登录界面的固定元素

<form name="loginform" method="post" action="j_security_check"> 
<INPUT name="j_username" type="text"> 
<INPUT name="j_password" TYPE="password"> 
<input type="submit" value="登 录" > 
</form> 

 form的action必须是“j_security_check”,method="post",用户名name="j_username",密码name="j_password"这些都是固定的元素。

然后这里的username,password要填什么呢?tomcat的conf目录下有个tomcat-users.xml文件,里面可以添一行<user name="mao" password="mao" roles="tomcat,pluto"/>,这里的意思是tomcat和pluto角色的用户名密码都是“mao”。

现在访问"/index.jsp"界面,跳转到login.jsp,填写用户名、密码“mao”之后就能访问到index.jsp的内容了

还有一点很重要security-constraint只对外部访问有作用,对内部跳转是不起作用的。

比如访问一个servlet,如果是以response.sendRedirect("/xiangmuming/index.jsp")的方式,还是会报403错误,如果是以request.getRequestDispatcher("/index.jsp").forword(request,response)的方式跳转就能够访问了

request.getRequestDispatcher().forward(),是属于服务器跳转,地址栏地址不变,旧的request,response全部传给页面

request.sendRedirect(),属于页面跳转,相当于访问两次,地址改变,request,response全是新的,就是访问了两次

猜你喜欢

转载自xiaoxiaoher.iteye.com/blog/2394725