【问题标题】:Spring Security - redirect to specific url after intercept-url access failsSpring Security - 在拦截 url 访问失败后重定向到特定 url
【发布时间】:2012-07-20 23:17:39
【问题描述】:

我有这些规则来访问我的应用中的页面:

<http auto-config="true" use-expressions="true">
        <!-- NON AUTHENTICATION PAGES -->
        <intercept-url pattern="/" access="permitAll" />
        <intercept-url pattern="/about" access="permitAll" />       

        <!-- LOGIN FILTER -->
        <intercept-url pattern="/login" access="!isAuthenticated()" />
        <intercept-url pattern="/j_spring_security_check" access="!isAuthenticated()" />
        <intercept-url pattern="/logout" access="!isAuthenticated()" />

        <!-- RESOURCES AND OTHER URLs FILTER -->
        <intercept-url pattern="/resources/**" access="permitAll" />
        <intercept-url pattern="/**" access="isAuthenticated()" />

        <!-- FORM LOGIN -->
        <form-login login-page="/login" default-target-url="/upload" authentication-failure-url="/loginfailed"  />
        <logout logout-success-url="/logout" />
    </http>

我需要的是在访问失败时重定向到某个 url(例如 /access-denied)并在控制器中处理此事件。

@RequestMapping(value = "/access-denied", method = RequestMethod.GET)
    public String accessDenied(Model model, RedirectAttributes ra) {

    // do what I want

    return "redirect:login";
}

例如,用户进入 /upload 但他没有登录,所以它会被重定向到 /access-denied。

【问题讨论】:

    标签: spring-mvc spring-security


    【解决方案1】:

    注意下面代码中security-http 中的access-denied-page 属性。

    <security:global-method-security
                pre-post-annotations="enabled" />
        <security:http auto-config="false" use-expressions="true"
                disable-url-rewriting="true" entry-point-ref="loginUrlAuthenticationEntryPoint"
                access-denied-page="/access-denied">
            <security:intercept-url pattern="/someurl"
                    access="isAuthenticated()" />
    </security:http>
    

    【讨论】:

      【解决方案2】:

      这可能有助于解释为什么您需要自己进行重定向,因为 Spring Security 会自动执行此操作。当访问被拒绝时,未经身份验证的用户的默认行为是将他们重定向到登录页面(这似乎是您想要做的)。

      如果您想自定义流程,使用的策略是AuthenticationEntryPoint,实现它可能比使用控制器更有意义。我在a previous answer 中写了更多关于此的内容。

      如果您只想插入一些额外的功能,您可以扩展 LoginUrlAuthenticationEntryPoint 并覆盖 commence 方法,调用超类进行重定向。

      请注意,这意味着不会使用命名空间元素中的 login-page 值。您需要在 LoginUrlAuthenticationEntryPoint 的构造函数中设置登录 URL。

      【讨论】:

      • 是的,Spring security 会自动重定向到登录页面。我想在用户必须登录的登录页面中显示 Flash 消息。如果我想在重定向页面中显示 Flash 消息,我可以使用 RedirectAttributes - 例如:ra.addFlashAttribute("errorMsg", "You are not logged in." );返回“重定向:登录”;
      • 嗯,Spring Security 在实践中对 Spring MVC 一无所知,所以你不能在AuthenticationEntryPoint 中这样做。您可以进行双重重定向(首先到您的控制器,然后到登录页面),或者如果您真的准备使用它们,您可以自己操作闪存范围设置。或者,您可以使用更简单的方法来设置错误消息,例如向重定向 URL 添加参数。
      猜你喜欢
      • 2013-06-04
      • 2011-07-12
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      • 2012-08-15
      • 2016-10-01
      相关资源
      最近更新 更多