【问题标题】:Why does HttpSecurity configuration via DSL not seem to work the same as explicit configuration?为什么通过 DSL 的 HttpSecurity 配置似乎与显式配置不同?
【发布时间】:2023-08-22 09:01:01
【问题描述】:

我为我的自定义身份验证机制编写了一个 DSL 来配置 HttpSecurity 时遇到了麻烦,但是当应用程序运行时,我应用的大部分配置似乎都没有生效,而一切都运行良好当我在 webapp 中手动配置它时。

首先,手动配置,这导致我的EntryPoint 被触发,authenticationProvider 被查询,过滤器被添加到链中,我的rememberMeServices 被添加到该过滤器。一切都正确。

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
          .antMatchers("/auth/callback").permitAll()
          .anyRequest().authenticated()
          .and()
        .authenticationProvider(authProvider)
        .rememberMe()
          .rememberMeServices(rememberMeServices)
          .and()
        .exceptionHandling()
          .authenticationEntryPoint(entryPoint)
          .and()
        .addFilterAfter(filter, UsernamePasswordAuthenticationFilter.class);
    /* The following code is basically what gets run when the DSL is in use
    http
        .apply(new EPIdentityDsl())
          // lots of setters called here, removed for clarity
          .and()
        .authorizeRequests().anyRequest().authenticated();
    */
  }

}

但是,DSL 中的代码看起来像这样,并且在使用它时,authenticationEntryPoint 永远不会触发。 rememberMeServices 确实已配置,看起来过滤器已正确添加到链中,但我只是收到 403 响应的错误页面,而不是看到 entryPoint 重定向。

public class EPIdentityDsl extends AbstractHttpConfigurer<EPIdentityDsl, HttpSecurity> {
  @Override
  public void init(HttpSecurity http) throws Exception {
    // any method that adds/removes another configurer
    // must be done in the init method
    log.debug("dsl init");
    http
        .exceptionHandling()
          .and()
        .rememberMe();
  }

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
          .antMatchers(filterProcessesUrl).permitAll()
          .and()
        .authenticationProvider(authProvider)
        .exceptionHandling()
          .authenticationEntryPoint(entryPoint)
          .and()
        .rememberMe()
          .rememberMeServices(rememberMeServices)
          .and()
        .addFilterAfter(filter, UsernamePasswordAuthenticationFilter.class);

  }
}

显然,我在文档或其他内容中缺少一些微妙的交互,导致我的基于 DSL 的 entryPoint 配置丢失。知道为什么吗?如果我不得不猜测,那可能是我指定路径的方式有问题,但我无法弄清楚。

【问题讨论】:

  • 遇到了完全相同的问题 :) 我的 dsl 设置了身份验证入口点,但在运行时不使用它...
  • 遇到同样的问题 :(

标签: spring-boot spring-security dsl


【解决方案1】:

我遇到了类似的问题。我通过将 entryPoint 移动到 init 来解决它

【讨论】:

    最近更新 更多