gpt4 book ai didi

java - antMatcher() 与 antMatchers() 的 Spring 安全应用

转载 作者:搜寻专家 更新时间:2023-10-31 08:31:39 26 4
gpt4 key购买 nike

只是想看看我是否在解释 answer to this question正确的方法。

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

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()

this question中有两个答案,但它们每个中提供的示例与另一个中给出的示例相矛盾。第一个答案说作者不需要 antMatcher(),第二个答案说总是从 `antMatcher() IIUC 开始。

最佳答案

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

示例代码:

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

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

下面的示例将确保 HttpSecurity 的范围包括前面的三个 AntMatcher 而没有其他内容:

http
.requestMatchers()
.antMatchers("/api/user/**", "/api/ticket/**", "/index")
.and()
.httpBasic()
.disable()
.authorizeRequests()
.any()
.hasRole("USER");

编辑如果您使用#hasRole(),那么您的角色不应以“ROLE_”开头,因为这是自动插入的。

关于java - antMatcher() 与 antMatchers() 的 Spring 安全应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47298079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com