Spring security 3 http-basic authentication-success-handler

时间:2013-05-24 12:05:01

标签: 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>

在这里我可以设置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>

我认为abour会覆盖BasicAuthenticationFilter,但是如何为<http-basic />注入我的cutom类

3 个答案:

答案 0 :(得分: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
    }
}

使用以下内容将其注入安全配置:

<http entry-point-ref="basicEntryPoint">
  <custom-filter ref="customBasicAuthFilter" position="BASIC_AUTH_FILTER"/>
</http>
<authentication-manager alias="authenticationManager">
  ...
</authentication-manager>

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

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

答案 1 :(得分:3)

作为一种解决方法,您可以将 http-basic 表单登录结合使用:

<http auto-config="true">
    ...
    <http-basic  />
    <form-login authentication-success-handler-ref="authenticationSuccessHandler" ... />
    ...
</http>

BasicAuthenticationFilter可以使用。

修改 如果你想设置你的BasicAuthenticationFilter的覆盖版本,我认为你需要:

  1. 按照解释here
  2. 将其添加到BASIC_AUTH_FILTER位置的过滤器链中
  3. 通过 http 标记的 entry-point-ref 属性设置相应的BasicAuthenticationEntryPoint入口点。

答案 2 :(得分:0)

除了使用AuthenticationSuccessHandler之外,您还可以依靠Spring Security的event mechanism并使用ApplicationListener接口来收听AuthenticationSuccessEvent

@Component
public class AuthenticationEventListener implements
    ApplicationListener<AuthenticationSuccessEvent>
{

    @Override
    public void onApplicationEvent (AuthenticationSuccessEvent event) {
       // do what you want here
       // example: persist event to the database
    }
}

另请参见以下答案:https://stackoverflow.com/a/11384001/474034