Spring Security-需要403错误,不能重定向 [英] Spring Security - need 403 error, not redirect

查看:126
本文介绍了Spring Security-需要403错误,不能重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Security 3.0.4.我有一堆受Spring Security保护的Web服务.当我以未经身份验证的用户身份访问它们时,Spring Security会重定向到登录页面.取而代之的是,我想返回HTTP 403错误.我该如何实现?

I am using Spring Security 3.0.4. I have a bunch of web service which are protected by Spring Security. When I access them as an unauthenticated user, Spring Security redirects to login page. Instead of that, I want to return HTTP 403 error. How can I achieve that?

这是我的安全配置:

<http auto-config="false" use-expressions="true" >

    <intercept-url pattern="/authorization.jsp" access="permitAll"/>
    <intercept-url pattern="/registration.jsp" access="permitAll"/>
    <intercept-url pattern="/api/authorization/auth" access="permitAll"/>
    <intercept-url pattern="/api/authorization/new" access="permitAll"/>
    <intercept-url pattern="/api/accounts/new" access="permitAll"/>
    <intercept-url pattern="/app/**" access="permitAll"/>
    <intercept-url pattern="/extjs/**" access="permitAll"/>

    <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />

    <form-login login-page="/authorization.jsp"
            default-target-url="/index.jsp"
            authentication-failure-url="/registration.jsp?login_error=1"
            always-use-default-target="true"
            />

    <logout logout-success-url="/authorization.jsp"
            logout-url="/j_spring_security_logout"
            invalidate-session="true"/>        

</http>

推荐答案

对于Java配置,您需要做

For java configuration you need to do

http.exceptionHandling().authenticationEntryPoint(alwaysSendUnauthorized401AuthenticationEntryPoint);

总是SendUnauthorized401AuthenticationEntryPoint是类实例的地方

Where alwaysSendUnauthorized401AuthenticationEntryPoint is innstance of class

public class AlwaysSendUnauthorized401AuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public final void commence(HttpServletRequest request, HttpServletResponse response,
                               AuthenticationException authException) throws IOException {
        LOGGER.debug("Pre-authenticated entry point called. Rejecting access");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

这将禁用Spring的默认行为(将未经身份验证的请求重定向到登录表单).

This disables default behavior of Spring (redirecting unauthenticated requests to login form).

旁注: 在这种情况下,与 SC_FORBIDDEN(403)相比,HTTP代码 SC_UNAUTHORIZED(401)是更好的选择.

Side note: for such case HTTP code SC_UNAUTHORIZED(401) is better choice than SC_FORBIDDEN(403).

这篇关于Spring Security-需要403错误,不能重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆