Servlet安全

Servlet安全的4大要素
1、认证——口令认证
2、授权——确定客户的身份后,再确定他可以做的事情
3、机密性——用户付款时,银行卡号不能让其它人看到
4、数据完整性、机密性——加密响应,确保没人能看到或涂改响应

HTTP如何认证
1、浏览器发出请求访问资源
2、容器查找容器的安全表中的URL,如果找到URL,再确定被访问资源是否是一个受限资源,是则响应一个未授权状态码401
3、用户输入用户名密码,再次请求
4、容器检查用户名密码(认证),容器接着检查该用户的角色是否可以访问受限资源(授权),响应;如果未通过认证,再次响应401

安全实现方式
声明方式、程序方式

声明方式实现步骤
1、和平时一样写一个servlet

@WebServlet("/hello")
public class Hello extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("Hello, 2019!");
    }
}
Java Code

2、确定应用中有哪些角色,为容器用户文件中的用户增加角色;tomcat的用户文件是位于conf目录下的tomcat-users.xml

领域(realm),存储认证信息的地方,tomcat的realm就是tomcat-users.xml文件。容器认证时会使用该文件的设置,这个文件应用于web-apps下部署的所有应用。

<?xml version="1.0" encoding="UTF-8"?>
<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">
              
  <role rolename="admin"/>
  <role rolename="member"/>
  <role rolename="guest"/>
  <user username="Mike" password="123" roles="admin,member"/>
  <user username="Jim" password="123" roles="guest"/>              
</tomcat-users>
tomcat-users.xml

3、启用认证
在web.xml中添加认证类型,可以是BASIC、DIGGEST、FORM、CLIENT-CERT

<login-config>
    <auth-method>BASIC</auth-method>
</login-config>
web.xml

3、确定哪些角色可以访问哪些servlet;通过web.xml可以告诉容器谁能访问哪些servlet。

(1)在web.xml中定义角色

  <security-role>
    <role-name>admin</role-name>
  </security-role>
  <security-role>
    <role-name>guest</role-name>
  </security-role>
  <security-role>
    <role-name>member</role-name>
  </security-role>
web.xml

(2)定义限制资源

以声明的方式,使用URL模式和请求方法——共同指定受限定的资源只能由<autauth-constraint>中定义的角色访问

  <security-constraint>
    <web-resource-collection>
      <web-resource-name>UpdateRecipes</web-resource-name>
      <!-- 定义要限定的资源,可以配置多个url-pattern -->
      <url-pattern>/hello/*</url-pattern>
      <!-- 定义请求方法 -->
      <http-method>GET</http-method>
      <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
      <!-- 定义哪些角色可以访问限定资源 -->
      <role-name>admin</role-name>
      <role-name>member</role-name>
    </auth-constraint>
  </security-constraint>
web.xml










猜你喜欢

转载自www.cnblogs.com/Mike_Chang/p/10474147.html