Spring security 3 http-basic authentication-success-handler

wut*_*aer 7 spring-security basic-authentication

我正在使用弹簧安全

我有表格登录

<http auto-config="true">
        <intercept-url pattern="/pages/**" access="ROLE_USER" />
        <form-login authentication-success-handler-ref="authenticationSuccessHandler" login-page="/login.html" default-target-url="/pages/index.html"
            always-use-default-target="true" authentication-failure-url="/login.html" />
        <logout logout-success-url="/login.html" invalidate-session="true" />
        <anonymous enabled='false'/>
</http>
Run Code Online (Sandbox Code Playgroud)

在这里我可以设置一个authentication-success-handler-ref,如何在我的基本身份验证中添加一个:

<http pattern="/REST/**" realm="REALM" entry-point-ref="authenticationEntryPoint">
    <intercept-url pattern="/**" access="ROLE_USER" />
    <http-basic  />
    <logout logout-url="/REST/logout" success-handler-ref="restLogoutSuccessHandler" />
</http>
Run Code Online (Sandbox Code Playgroud)

我认为abour会覆盖BasicAuthenticationFilter,但我怎么能注入我的cutom类 <http-basic />

hol*_*s83 5

您无法为BASIC身份验证设置身份验证成功处理程序.但是,您可以扩展BasicAuthenticationFilter并覆盖onSuccessfulAuthentication方法:

@Component("customBasicAuthFilter")
public class CustomBasicAuthFilter extends BasicAuthenticationFilter {

    @Autowired
    public CustomBasicAuthFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    protected void onSuccessfulAuthentication(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Authentication authResult) {
        // Do what you want here
    }
}
Run Code Online (Sandbox Code Playgroud)

在安全配置中注入它,例如:

<http entry-point-ref="basicEntryPoint">
  <custom-filter ref="customBasicAuthFilter" position="BASIC_AUTH_FILTER"/>
</http>
<authentication-manager alias="authenticationManager">
  ...
</authentication-manager>
Run Code Online (Sandbox Code Playgroud)

更新:或使用Java配置而不是XML:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
      .addFilterAt(customBasicAuthFilter, BasicAuthenticationFilter.class)
      .exceptionHandling().authenticationEntryPoint(basicEntryPoint);
}
Run Code Online (Sandbox Code Playgroud)