Spring Security - need 403 error, not redirect

前端 未结 4 1010
囚心锁ツ
囚心锁ツ 2020-12-24 11:13

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 redire

相关标签:
4条回答
  • 2020-12-24 11:51

    There's an article on the spring forums here that outlines how to get your app determining between the two methods. So far I'm using the following code to secure my data controllers:

    <bean id="ep403" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"/>
    
    <sec:http pattern="/data/**" entry-point-ref="ep403" use-expressions="true">
        <sec:intercept-url pattern="/**" access="isAuthenticated()"/>
    </sec:http>
    
    <bean id="epauth" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
        <constructor-arg value="/login.html"/>
    </bean>
    
    <sec:http pattern="/**" entry-point-ref="epauth" use-expressions="true">
        <sec:intercept-url pattern="/**" access="isAuthenticated()"/>
    </sec:http>
    

    So the whole DelegatingAuthenticationEntryPoint solution in the article I linked is a bit more heavyweight, but I imagine it does the job just fine as well.

    0 讨论(0)
  • 2020-12-24 11:56

    you need to

    • Create a RequestMatcher to determine which requests should get a 403 (AntPathRequestMatcher may suffice in your case).
    • Configure the HttpSessionRequestCache to check the matcher and not store those pages for post-login redirect.
    • Use a DelegatingAuthenticationEntryPoint to either 403 the request outright or redirect to login according to the matcher.

    See the example here:

    http://distigme.wordpress.com/2012/11/01/ajax-and-spring-security-form-based-login/

    0 讨论(0)
  • 2020-12-24 12:09

    It should return a 403 error unless you configure it to go to another url with this tag:

    <sec:access-denied-handler error-page="/urlToGoIfForbidden" />
    
    0 讨论(0)
  • 2020-12-24 12:13

    For java configuration you need to do

    http.exceptionHandling().authenticationEntryPoint(alwaysSendUnauthorized401AuthenticationEntryPoint);
    

    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);
        }
    }
    

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

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

    0 讨论(0)
提交回复
热议问题