有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在Spring中只将安全路径的子路径列为白名单?

我使用的spring-boot-starter-security默认情况下会自动保护我的所有@GetMappingrest端点

问题:如何仅显式地将不应受保护的子路径列为白名单

我尝试了以下方法:

@Configuration
public class DocumentsSecurityConfiguration implements WebSecurityConfigurer<WebSecurity> {
    @Override
    public void init(WebSecurity builder) { }

    //should allow unauthenticated access
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/documents/**");
    }
}

但是:localhost:8080/documents根路径应该保持安全。只有像/documents/123这样的子路径应该保持打开状态

问题:当我现在访问根路径/documents时,它不再安全

我的错了吗


共 (2) 个答案

  1. # 1 楼答案

    这种行为是一种优化,请参见^{}

    Using a pattern value of /** or ** is treated as a universal match, which will match any request. Patterns which end with /** (and have no other wildcards) are optimized by using a substring match — a pattern of /aaa/** will match /aaa, /aaa/ and any sub-directories, such as /aaa/bbb/ccc.

    有一些可能的方法可以解决你的问题:

    • 使用^{}
    • 实现一个自定义^{}
    • 使用^{}
  2. # 2 楼答案

    我猜可能是这样的:

    @Configuration
    @EnableWebSecurity
    @Order(SecurityProperties.BASIC_AUTH_ORDER)
    @Slf4j
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        private static final String[] AUTH_WHITE_LIST = {
            // swagger-ui
              "/v2/api-docs"
            , "/swagger-resources"
            , "/swagger-resources/**"
            , "/configuration/security"
            , "/swagger-ui.html"
            , "/webjars/**"
            , "/security/**"
            // spring actuator
            , "/actuator"
            , "/actuator/**"
        };
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.anonymous().and()
                    .authorizeRequests().antMatchers(AUTH_WHITE_LIST).permitAll();
        }
    }
    

    请关注订单,spring security基于文件管理器,基本上订单很重要。如果任何其他匹配器拒绝该请求,它将不会到达该配置

    对于你提到的问题

    我认为你必须编写一个自定义过滤器来处理它。仅允许使用某些附加路径的“/documents”,但停止访问“/documents”

    我个人建议你调整url的设计,也许在这种情况下将其改为“/documents/all”比“/documents”更好?尽管这有点违背了互联网上的rest api教程

    代码来自我的一个项目,但一些不相关的部分已被删除。希望这能有所帮助