6

我无法在 SO 上找到答案(例如这里 。Spring Security: Commence method in class extends BasicAuthenticationEntryPoint no being called

我只想覆盖 BasicAuthenticationEntryPoint 而不覆盖其他过滤器和其他人员:

<bean id="authenticationEntryPoint" name="authenticationEntryPoint"
      class="com.myclass.BasicAuthenticationEntryPoint">
    <property name="realmName" value="myapp" />
</bean>

不幸的是,它不起作用,我需要配置过滤器。

<security:http auto-config="true" ..
<sec:custom-filter ref="basicAuthenticationFilter"
                                before="BASIC_AUTH_FILTER" />

</sec:http>

<bean id="basicAuthenticationFilter"
      class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
    <constructor-arg name="authenticationManager" ref="authenticationManager" />
    <constructor-arg name="authenticationEntryPoint" ref="authenticationEntryPoint" />
</bean>

然后我有这个警告。

WARN 2015-10-29 09:44:05,330 [localhost-startStop-1::DefaultFilterChainValidator] [user:system] Possible error: Filters at position 2 and 3 are both instances of org.springframework.security.web.authentication.www.BasicAuthenticationFilter

因此我需要禁用自动配置,但我不想这样做:

<security:http auto-config="false" ...

在 SpringSecurity 4 中覆盖 BasicAuthenticationEntryPoint 的最简单方法是什么?

4

2 回答 2

6

这适用于 Spring Security 3(我认为它应该适用于 Spring 4),无需配置任何过滤器:

public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {

        response.setStatus( HttpServletResponse.SC_UNAUTHORIZED);
    }
}

更新 :

CustomBasicAuthenticationEntryPoint 是一个 Spring Bean。你必须告诉 Spring 这件事。就像在您的帖子中一样(我刚刚在答案中更改了它的名称):

<bean id="authenticationEntryPoint" name="authenticationEntryPoint"
      class="com.myclass.CustomBasicAuthenticationEntryPoint">
    <property name="realmName" value="myapp" />
</bean>

您还需要告诉 Spring Security 将此 bean 用作入口点而不是默认的入口点:

<security:http entry-point-ref="authenticationEntryPoint" ...

默认配置在未通过身份验证时将客户端重定向到登录页面。当您覆盖此默认行为时,您只会发送 401 代码状态(未经身份验证)并且您不会重定向客户端。

于 2015-10-29T11:20:37.957 回答
3

完整解决方案:

1)在http元素配置authenticationEntryPoint:

<http entry-point-ref="authenticationEntryPoint" ...>
</http>

它配置 ExceptionTranslationFilter 的 authenticationEntryPoint。

2) 在 http-basic 元素中配置 authenticationEntryPoint

<http-basic entry-point-ref="authenticationEntryPoint"/>

它配置 BasicAuthenticationFilter 的 authenticationEntryPoint

于 2015-11-02T08:04:28.653 回答