防止重定向到登录Spring Security

2022-09-02 20:56:26

我有Spring MVC + Spring Security项目。

<http auto-config="true" access-denied-page="/security/accessDenied" use-expressions="true" disable-url-rewriting="true">

... 
<intercept-url pattern="/dashboard/myaccount/**" access="hasAnyRole('ROLE_PERSON', 'ROLE_DEALER')"/>
...

<form-login login-page="/security/login" authentication-failure-url="/security/login?error=true"
                default-target-url="/security/success" username-parameter="email"
                password-parameter="secret"/>
<logout invalidate-session="true" logout-success-url="/index" logout-url="/security/logout"/>

如果用户进入登录页面,如果成功,将被重定向到“/security/success”,其中我使用会话对象在控制器中做更多的事情(记录userID,...等)

我的问题是,当一个GUEST用户要去/dashboard/myaccount(这需要AUTH)时,他被重定向到LOGIN页面(我不想要,我更喜欢404抛出)。在那之后,Spring Security不会重定向到/security/success。而是重定向到 /dashboard/myaccount。

我宁愿找到一种方法来完全禁用此重定向到登录页面,以防GUEST尝试访问AUTH页面。

有什么办法可以做到这一点吗?

断续器


答案 1

我们添加了一个新的身份验证EntryPoint:

<http auto-config="true" access-denied-page="/security/accessDenied" use-expressions="true"
      disable-url-rewriting="true" entry-point-ref="authenticationEntryPoint"/>

<beans:bean id="authenticationEntryPoint" class="a.b.c..AuthenticationEntryPoint">
    <beans:constructor-arg name="loginUrl" value="/security/login"/>
</beans:bean>

public class AuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {    
    public AuthenticationEntryPoint(String loginUrl)  {
        super(loginUrl);
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.sendError(403, "Forbidden");
    }
}

答案 2

在SpringSecurity 4的注释配置中,您可以执行以下操作:

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    // ....
    http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {

        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException authException) throws IOException, ServletException {
            if (authException != null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().print("Unauthorizated....");
            }
        }
    });
    // ....
}

}