Tomcat下webapps访问认证BASIC Authentication设置

今天主要练习了tomcat下访问认证的设置,也更深入一点的了解了tomcat-user.xml

首先在$CATALINA_HOME/conf/tomcat-users.xml中添加用来登陆指定webapps的用户,如下

<tomcat-users>
    <role rolename="tomcat"/>
    <role rolename="manager"/>
    <user username="tomcat" password="tomcat" roles="tomcat"/>
    <user username="manager" password="manager" roles="manager"/>
</tomcat-users>

之后在需要添加登陆认证的webapps下修改其web.xml文件,这里以tomcat自带的examples为例,修改$CATALINA_HOME/webapps/examples/WEB-INF/web.xml,添加(修改)security-constraint字段,如下

<security-constraint>
  <display-name>Example Security Constraint</display-name>
  <web-resource-collection>
     <web-resource-name>Protected Area</web-resource-name>
     <url-pattern>/*</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>manager</role-name>
  </auth-constraint>
</security-constraint>

其中url-pattern定义了需要保护的路径,http-method定义了需要保护的http methods(http methods共有九种,具体的定义我也还不是很清楚),role-name定义了可以访问的role-name,和tomcat-users.xml中对应。
之后写login-congif字段,这里用BASIC方式认证,还可以用form认证的方法,区别是BASIC认证是在http包头部加上了认证字段,而from认证是通过页面的方式进行,需要手动添加登陆页面,登陆失败页面等。

<login-config>
  <auth-method>BASIC</auth-method>
</login-config>

如果form认证,需要加上页面字段。

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

之后要再添加之前提及的security-role

<security-role>
  <role-name>manager</role-name>
</security-role>
<security-role>
  <role-name>tomcat</role-name>
</security-role>