Java web的安全约束--Basic验证

要进行basic验证是用户名/口令机制,当浏览器要访问受保护的资源时,服务器会要求一个用户名和口令,只有输入了合法的用户名和口令。服务器才发送资源。用户名和口令可以存储在安全域中。安全域是标识一个Web应用程序的合法用户名和口令的“数据库”,其中还包含了与用户相关的角色。

例子:使用basic和MemoryRealm登录

    1、在tomcat下的/conf/tomcat-users.xml定义了角色和用户,还有一些角色

<tomcat-users xmlns="http://tomcat.apache.org/xml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
version="1.0">
<user username="li" password="123456" roles="admin-gui,manager-gui" />
<role rolename="manager"/>
<user username="admin" password="123456" roles="manager"/>

</tomcat-user>

    2、在web.xml中定义如下:

<security-constraint>
<web-resource-collection>
<web-resource-name>adminResource</web-resource-name>
<url-pattern>/AccountServlet</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description>allManager</description>
<role-name>manager</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>

<login-config>
<auth-method>BASIC</auth-method>
<realm-name>test</realm-name>
</login-config>



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

其中<security-constraint>标签设置受保护的资源和可以访问的用户角色;

<login-config>是验证机制,访问受保护的资源,弹出的对话框不同,它的<realm-name>test</realm-name>;是弹出的对话框中显示的安全域的名

<security-role>是用来定义,使用的角色

这样就可对资源进行保护,在访问资源时,在弹出的对话框中输入之前定义的用户,密码就可以访问了

原文地址:https://www.cnblogs.com/l1019/p/6921265.html