【问题标题】:How do I know whether HttpServletRequest is subject to <security-constraint> or not?我如何知道 HttpServletRequest 是否受 <security-constraint> 约束?
【发布时间】:2023-03-02 22:48:01
【问题描述】:

我的 web.xml 中有一个带有安全约束的 servlet,如下所示:

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Admin</web-resource-name>
        <url-pattern>/admin/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

以上强制切换到 https 协议并且工作正常。但是在受保护的页面上,有一些 relative 链接到不安全的页面。当用户点击它们时,它们会通过我想要避免的 https 打开。将相对链接转换为绝对链接不是一种选择。 Servlet 规范没有提供强制不安全连接的方法,所以我将实现一个过滤器,将用户重定向到 http:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    if(!isSubjectToAuthConstraint(request)) {
        // Check protocol and redirect to http if https
        // ....
    } else {
        // Do nothing, managed by servlet spec
        filterChain.doFilter(request, response);
    }
}

所以我需要知道请求是否受到安全约束。我如何以编程方式知道它?有可能吗?

【问题讨论】:

    标签: java servlets security servlet-filters


    【解决方案1】:

    嘿,通常情况下,https 端口是 443。通过在浏览器中输入 https://www.example.com:443/welcome.html,浏览器会将其扩展为 https://www.example.com/welcome.html

    也许这就是你需要的:

    String serverAddress = "";    
    String serverName = request.getServerName( );
    String serverPort = "" + request.getServerPort( );
    
    if( request.isSecure( ) ) {
      serverAddress = "https://" + serverName + ":" + serverPort;
    } else {
      serverAddress = "http://" + serverName + ":" + serverPort;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 2011-02-02
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多