本文基于Tomcat文件文件中的角色和用户配置BASIC认证,是最简单的BASIC认证实现方案。


1. 在<tomcat_home>/conf目录下的tomcat-users.xml文件中添加如下内容

<rolerolename="basicrole"/><userusername="basicuser"password="password"roles="basicrole"/>


2. 在<TOMCAT_HOME>/conf/server.xml的<Engine>节点中添加MemoryRealm安全域,关于Realm的详细解释可参考这里。

<RealmclassName="org.apache.catalina.realm.MemoryRealm"/>


3. 配置web.xml的web-app节点下添加如下内容,将Web Project Name替换为自己的工程名称即可。

<security-constraint><web-resource-collection><web-resource-name>WebProjectName</web-resource-name><!--匹配所有请求--><url-pattern>/*</url-pattern></web-resource-collection><auth-constraint><!--只允许basicrole角色的用户访问--><role-name>basicrole</role-name></auth-constraint></security-constraint><login-config><!--值可以是BASIC/DIGEST/CLIENT_CERT/FORM--><auth-method>BASIC</auth-method><!--认证提示信息--><realm-name>favccxxbasicrealm</realm-name></login-config><security-role><role-name>basicrole</role-name></security-role>


4. 在浏览器中访问你的web工程,弹出如下所示的登录对话框,说明BASIC认证配置成功。