【问题标题】:What does the authorizeRequests in Spring Security do?Spring Security 中的 authorizeRequests 有什么作用?
【发布时间】:2022-02-25 16:03:45
【问题描述】:

在我拥有此配置的那一刻起,我一直在尝试为不同的 api 端点设置多个安全配置:

http
    .antMatcher("/user/**")
    .authorizeRequests()
        .antMatchers("/user/document/**").permitAll()
        .and()
    .authorizeRequests()
        .anyRequest().authenticated()
        .and()
    .httpBasic();

此配置正在运行,但当我尝试删除第二个 authorizeRequests()(见下文)时,我也感到困惑。配置也正常。

http
    .antMatcher("/user/**")
    .authorizeRequests()
        .antMatchers("/user/document/**").permitAll()
        .anyRequest().authenticated()
        .and()
    .httpBasic();

这个方法有什么作用?我必须每次都调用它吗?

【问题讨论】:

  • 您可以重复每个方法,因为方法链。但你不需要它。为了更好的可读性,您不应重复任何方法。此外,在某些情况下,第二次调用可能会覆盖第一次调用。

标签: java spring spring-security


【解决方案1】:

引用文档:

请注意,匹配器是按顺序考虑的。

在您的配置中,/user/** 优先于 /user/document/**。因此,在这两种情况下,都不会应用第二个 antMatcher(...)。 回答你的第二个问题(我需要每次都打电话给它吗?) - 答案是NO。这是一个示例配置(同样来自文档):

http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN")
    .antMatchers("/**").hasRole("USER").and().formLogin();

【讨论】:

  • 在您的配置中,/user/* 优先于 /user/document/** 这是错误的。我重新格式化了问题,使其更清楚。
猜你喜欢
  • 2018-03-27
  • 2017-10-11
  • 2019-12-16
  • 1970-01-01
  • 2017-11-30
  • 1970-01-01
  • 2019-05-26
  • 1970-01-01
  • 2018-10-07
相关资源
最近更新 更多