小编典典

antMatcher()和antMatchers()的Spring安全性应用

spring-boot

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

http.antMatcher("/api/**").authorizeRequests()....

然后使用antMatcher()

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

http
.authorizeRequests()
    .antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
    .antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
    ...

然后使用antMatchers()


阅读 7917

收藏
2020-05-30

共1个答案

小编典典

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

示例代码:

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

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

下面的示例将确保HttpSecurity的范围包括之前的三个AntMatchers,并且仅包含其他内容:

http
    .requestMatchers()
        .antMatchers("/api/user/**", "/api/ticket/**", "/index")
        .and()
    .httpBasic()
        .disable()
    .authorizeRequests()
        .any()
            .hasRole("ROLE_USER");
2020-05-30