将Spring Security转移到Java配置,身份验证 - 成功 - 处理程序 - ref去哪里?

2022-09-02 20:54:21

我们的应用程序具有用于成功登录的自定义成功处理程序。它基本上将他们重定向到会话过期时他们所在的页面。

我们正在转向Java配置,而不是弹簧xml配置。配置的其余部分进行得非常顺利,但是我们找不到在哪里放置 security:form-login 标记的身份验证-成功-处理程序-ref 属性。

<security:http auto-config='true'>
  ...
  <security:intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY"/>
  <security:form-login login-page="/login" default-target-url="/sites"
                     authentication-failure-url="/login"
                     authentication-success-handler-ref="authenticationSuccessHandler"/>
 ...

到目前为止,这是我们的配置。

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
       .authorizeRequests()
          .anyRequest().authenticated()
          .and()
        .formLogin()
          .loginPage("/login")
          .failureUrl("/login")
          .and()
        .logout()
          .permitAll()
          .and()
  }

另外,我们找不到放置默认目标url的位置,但这肯定不那么重要。

需要注意的是,我们实际上是在使用Groovy,但代码基本上与Java配置相同。


答案 1

所有设置都可以在全局配置方法内完成。添加以下内容:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
          .anyRequest().authenticated()
          .and()
        .formLogin()
          .loginPage("/login")
          .defaultSuccessUrl("/sites")
          .failureUrl("/login")
          .successHandler(yourSuccessHandlerBean) // autowired or defined below
          .and()
        .logout()
          .permitAll()
          .and()
  }

答案 2

您必须创建 Bean 扩展 或 .例如:SimpleUrlAuthenticationSuccessHandlerSavedRequestAwareAuthenticationSuccessHandler

@Bean
public SavedRequestAwareAuthenticationSuccessHandler successHandler() {
    SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
    successHandler.setTargetUrlParameter("/secure/");
    return successHandler;
}

然后你必须在bean扩展上设置它:AbstractAuthenticationProcessingFilter

UsernamePasswordAuthenticationFilter authenticationFilter = new UsernamePasswordAuthenticationFilter();
authenticationFilter.setAuthenticationSuccessHandler(successHandler());

推荐