J2EE安全策略:为tomcat页面设置访问权限(j_security_check)

一、琅序

  项目中有用到Tomcat登录验证功能,以下内容来源于网络,谢谢原作者的分享。

  原文地址:http://www.blogjava.net/asktalk/archive/2005/07/23/8221.html

 

二、为tomcat页面设置访问权限

  在web应用中,对页面的访问控制通常通过程序来控制,流程为:

  登录 -> 设置session -> 访问受限页面时检查session是否存在,如果不存在,禁止访问!

  对于较小型的web应用,可以通过tomcat内置的访问控制机制来实现权限控制。采用这种机制的好处是,程序中无需进行权限控制,完全通过对tomcat的配置即可完成访问控制。

  为了在tomcat页面设置访问权限控制,在项目的WEB-INFO/web.xml文件中,进行如下设置:

<web-app>

<!--servlet等其他配置-->

<security-constraint>
  <web-resource-collection>
      <display-name>Example Security Constraint</display-name>
      <web-resource-name>My Test</web-resource-name>
   
      <url-pattern>/ddly/admin/*</url-pattern>
  </web-resource-collection>
  
<auth-constraint>
    <role-name>role1</role-name>
    <role-name>tomcat</role-name>
</auth-constraint>

</security-constraint>

<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>My Test</realm-name>
</login-config>

</web-app>

  其中:

  <url-pattern>中指定受限的url,可以使用通配符*,通常对整个目录进行访问权限控制。

  <auth-constraint>中指定哪些角色可以访问<url-pattern>指定的url。

  <role-name>中可以设置一个或多个角色名。使用的角色名来自tomcat的配置文件${CATALINA_HOME}/conf/tomcat-users.xml。

  <login-config>中设置登录方式,<auth-method>的取值为BASIC或FORM。如果为BASIC,浏览器在需要登录时弹出一个登录窗口。如果为FORM方式,需要指定登录页面和登录失败时的提示信息显示页面。

  使用FORM方式的配置样例如下:

<login-config>
   <auth-method>FORM</auth-method>
   <realm-name>Example Form-Based Authentication Area</realm-name>
   <form-login-config>
      <form-login-page>/login.jsp</form-login-page>
      <form-error-page>/error.jsp</form-error-page>
   </form-login-config>
</login-config>

  其中的<form-login-page>指定登录页面url,<form-error-page>指定登录失败时的提示页面url。


  登录页面中,form的action,以及其中的用户名和密码两个参数的名称,都应取固定的值。登录的后台处理程序为j_security_check;用户名和密码的参数名称分别为:j_username和j_password。


  如下是登录页面(如:login.jsp)的一段示例代码:

<form method="POST" action='<%= response.encodeURL("j_security_check") %>' >
  <table border="0" cellspacing="5">
    <tr>
      <th align="right">Username:</th>
      <td align="left"><input type="text" name="j_username"></td>
    </tr>
    <tr>
      <th align="right">Password:</th>
      <td align="left"><input type="password" name="j_password"></td>
    </tr>
    <tr>
      <td align="right"><input type="submit" value="Log In"></td>
      <td align="left"><input type="reset"></td>
    </tr>
  </table>
</form>

 

 

 

 

 

 ----------------------------------------致青春----------------------------------------

posted @ 2015-05-29 10:20  马小琅  阅读(2369)  评论(0编辑  收藏  举报