我无法在SO上找到答案(例如这里。 Spring Security: Commence method in class extending 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的最简单方法是什么?
答案 0 :(得分: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代码状态(未经身份验证),并且您不会重定向客户端。
答案 1 :(得分:3)
完整解决方案:
1)在http元素:
配置authenticationEntryPoint<http entry-point-ref="authenticationEntryPoint" ...>
</http>
它配置ExceptionTranslationFilter的authenticationEntryPoint。
2)在http-basic元素
配置authenticationEntryPoint<http-basic entry-point-ref="authenticationEntryPoint"/>
它配置BasicAuthenticationFilter的authenticationEntryPoint