antMatcher()与antMatchers()的Spring安全应用程序

Ole*_*Ole 5 java spring-mvc spring-security spring-boot

只是想看看我是否正确地解释了这个问题答案.

如果我们只需要保护这样一条路径:

http.antMatcher("/api/**").authorizeRequests()....
Run Code Online (Sandbox Code Playgroud)

然后用antMatcher().

如果我们需要保护多个这样的URL路径:

http
.authorizeRequests()
    .antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
    .antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
    ...
Run Code Online (Sandbox Code Playgroud)

然后用antMatchers().

这个问题有两个答案,但每个答案中提供的例子与另一个案例中给出的例子相矛盾.第一个答案说作者不需要antMatcher(),第二个答案总是以`antMatcher()IIUC开头.

dse*_*sep 10

HttpSecurity.antMatcher()HttpSecurity实例的默认请求匹配器从AnyRequestMatcher 更改AntPathRequestMatcher.ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry.antMatchers()用于将授权规则应用于与当前HttpSecurity实例关联的端点子集.

示例代码:

http
    .antMatcher("/api/**")
    .httpBasic()
        .disable()
    .authorizeRequests()
        .antMatchers("/api/user/**", "/api/ticket/**", "/index")
            .hasRole("ROLE_USER");
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,对于匹配/ api/**的所有端点禁用基本授权.此外,匹配/ api/user/**/ api/ticket/**的端点将要求请求的身份验证包含ROLE_USER.但是,当用户尝试访问/索引时,将会遇到基本的身份验证提示.输入凭据后,无论请求的身份验证是否包含ROLE_USER,都将授予用户对端点的访问权限.这是因为.antMatcher("/ api/**")将整个HttpSecurity实例的范围限制为特定的AntMatcher.

下面的示例将确保HttpSecurity的范围包括以前的三个AntMatchers,而不是其他:

http
    .requestMatchers()
        .antMatchers("/api/user/**", "/api/ticket/**", "/index")
        .and()
    .httpBasic()
        .disable()
    .authorizeRequests()
        .any()
            .hasRole("ROLE_USER");
Run Code Online (Sandbox Code Playgroud)

  • @Ole 在同一个 HttpSecurity 实例上调用 antMatcher() 两次只会替换原始的 antMatcher。要将相同的 HttpSecurity 配置应用于多个 antMatchers,请使用 http.requestMatchers()。antMatchers(). 另一种方法是创建多个 SecurityConfigurer,每个 SecurityConfigurer 使用自己的 antMatcher,然后用 \@order 注释它们,以确保 spring 加载所有这些。 (2认同)