8

您好,我正在使用 Spring Security

对于表单登录,我有

<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,但我怎样才能注入我的cutom类 <http-basic />

4

3 回答 3

6

您不能为 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);
}
于 2013-05-27T14:04:58.073 回答
3

作为一种解决方法,您可以将http-basicform-login结合使用:

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

BasicAuthenticationFilter 将起作用。

编辑。 如果您想设置 BasicAuthenticationFilter 的覆盖版本,我认为您需要:

  1. 将其添加到 BASIC_AUTH_FILTER 位置的过滤器链,如此处所述
  2. 通过http标签的entry-point-ref属性设置对应的 BasicAuthenticationEntryPoint 入口点。
于 2013-05-24T12:35:31.193 回答
2

AuthenticationSuccessHandler您可以依赖 Spring Security 的事件机制AuthenticationSuccessEvent并使用 ApplicationListener 接口来监听,而不是使用 an :

@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

于 2019-02-20T10:33:43.997 回答