Spring mvc Spring Security-在拦截url访问失败后重定向到特定url

Spring mvc Spring Security-在拦截url访问失败后重定向到特定url,spring-mvc,spring-security,Spring Mvc,Spring Security,我有以下规则来访问我的应用程序中的页面: <http auto-config="true" use-expressions="true"> <!-- NON AUTHENTICATION PAGES --> <intercept-url pattern="/" access="permitAll" /> <intercept-url pattern="/about" access="permitAll" /

我有以下规则来访问我的应用程序中的页面:

<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>

例如,用户输入/上传,但他未登录,因此将重定向到/拒绝访问。

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

如果您想定制流程,使用的策略是
AuthenticationEntryPoint
,实现这一点可能比使用控制器更有意义。关于这一点,我在第二章中写了更多

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


请注意,这意味着不会使用namespace元素中的
登录页面
值。您需要在构造函数中为
LoginUrlAuthenticationEntryPoint

设置登录URL,请注意下面代码中
安全http
中的
拒绝访问页面
属性

<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>


是,Spring security会自动重定向到登录页面。我想在登录页面中显示用户必须登录的flash消息。如果我想在重定向页面中显示flash消息,我可以使用重定向属性-例如:ra.addFlashAttribute(“errorMsg”,“您未登录”);返回“重定向:登录”;实际上,Spring Security对Spring MVC一无所知,所以在
AuthenticationEntryPoint
中不能这样做。您可以执行双重重定向(首先到控制器,然后到登录页面),或者如果您真的打算使用flash scope设置,您也可以自己操作它们。或者,您可以使用更简单的方法设置错误消息,例如通过向重定向URL添加参数。
<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>