【问题标题】:Spring Security show 404 if user is not authorize如果用户未授权,则 Spring Security 显示 404
【发布时间】:2015-06-05 22:54:19
【问题描述】:

我的spring安全配置是

<http pattern="/resources/**" security="none"/>
    <http pattern="/login**" security="none"/>
    <http pattern="/invalidsession**" security="none"/>
    <http pattern="/forgotpassword**" security="none"/>
    <http pattern="/accessdenied**" security="none"/>
    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/common/**" access="hasAnyRole('SITE_ADMIN','CLIENT_ADMIN')" />
        <intercept-url pattern="/site/**" access="hasRole('SITE_ADMIN')" />
        <intercept-url pattern="/**" access="hasRole('CLIENT_ADMIN')" />
        <!-- access denied page 
        <access-denied-handler error-page="/accessdenied" />
        -->
        <access-denied-handler ref="my403" />
        <form-login login-page="/login" 
             username-parameter="username"
            password-parameter="password"  authentication-failure-url="/login?error" 
            authentication-success-handler-ref="myAuthenticationSuccessHandler"
            />
        <logout logout-success-url="/login?logout" />
        <session-management invalid-session-url="/invalidsession" />
    </http>

当 SITE_ADMIN 用户打开一个不存在的页面时,它会显示拒绝访问页面而不是 404 页面。这样做是因为 &lt;intercept-url pattern="/**" access="hasRole('CLIENT_ADMIN')" /&gt;。 Spring 安全性在 pagenotfound 之前检查授权。如果页面不存在并且 SITE_ADMIN 当前正在记录,我如何显示 404。

【问题讨论】:

    标签: java spring spring-mvc spring-security


    【解决方案1】:

    不确定您为什么要这样做,但您可以通过实现 AuthenticationEntryPoint 并为您的 CLIENT_ADMIN 设置 commence method set 404 并为其他所有人保留默认值来完成它

    类似

       @Component
      public class EntryPointUnauthorizedHandler implements AuthenticationEntryPoint{
                @Override
     public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,AuthenticationException e) throws IOException, ServletException {
         // use SecurityContextHolder.getContext() for your security checks
         httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Access Denied");
                    }
    
                }
    

    现在您可以在 http-security 配置中添加入口点

    【讨论】:

      【解决方案2】:

      这个要求将很难满足:Spring 安全过滤器调度程序 servlet 看到请求之前进行 Web 授权测试。

      那么可以做些什么呢?这里有一些路径,但我从未尝试过。

      1/ 使用自定义AccessDeniedHandler。它的 handle 方法将获取请求和响应,因此它可以尝试使用虚拟响应将它们直接传递给 DispatcherServlet。困难的部分是分析响应以查看它是否是 404 错误页面,以及是否将虚拟响应复制到真实响应中,否则继续使用默认的 AccessDeniedHandlerImpl 方法。看起来很hacky ...

      2/ 放弃网络安全,只在所有服务方法上一致地使用方法安全。这样,仅当 DispatcherServlet 成功找到请求的控制器时才会调用安全性。缺点是您将无法获得静态页面的安全性。但是这种方式如果更多弹簧方式

      无论如何,我永远不会尝试这样做。我不允许某人进入特定的层次结构,我不希望他确切知道存在哪些页面。我不是特别喜欢混淆的安全性,但我更喜欢隐藏对用户没有直接用处的所有内容。

      【讨论】:

      • 感谢您的评论。我把这件事告诉了我的经理,他说不要这样做。
      猜你喜欢
      • 2015-10-21
      • 2013-05-18
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 2013-03-15
      • 2020-07-28
      • 2020-06-01
      相关资源
      最近更新 更多