【问题标题】:Spring Security permit paths with the same suffixSpring Security 允许具有相同后缀的路径
【发布时间】:2019-03-07 05:10:19
【问题描述】:

在我的 JWT 身份验证 API 中,我希望这些路径无需任何身份验证即可访问,并且所有其他端点都被禁止/禁用:

  • GET /apis/id/{id}
  • POST /apis
  • 补丁/apis/id/{id}
  • 删除 /apis/id/{id}
  • GET /swagger-ui.html

如您所见,上述大多数端点都以/apis/id 开头,POST 具有/apis。这是我的配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests()
           .mvcMatchers(HttpMethod.GET,"/apis/id/**").permitAll()
           .mvcMatchers(HttpMethod.PATCH,"/apis/id/**").permitAll()
           .mvcMatchers(HttpMethod.DELETE,"/apis/id/**").permitAll()
           .mvcMatchers(HttpMethod.POST,"/apis", "/apis/").permitAll()
           .antMatchers(HttpMethod.GET,"/csrf","/v2/api-docs","/swagger-resources/configuration/ui",  "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**","/swagger-resources/configuration/ui","/swagger-resources/configuration/security", "/configuration/security").permitAll()// for Swagger UI
        .anyRequest().denyAll();
    }
}

只有 GET /apis/id/{id}/swagger-ui.html 才能通过。具有相同配置的其他端点(POST 除外)都被拒绝(403)。我添加了一个异常处理程序并打印出AuthenticationException 消息,它说:

访问此资源路径需要完全身份验证

如何公开这些端点?我觉得我缺少一些配置。

我正在使用的框架:

  • Spring Boot 2.0.4 版
  • Spring Security 5.1.0 版

【问题讨论】:

    标签: java spring spring-mvc spring-security


    【解决方案1】:

    您可以查看this answer 以了解您的问题的可能解释。

    调用antMatcher(String) 将覆盖之前的调用 mvcMatcher(String), requestMatchers(), antMatcher(String), regexMatcher(String)requestMatcher(RequestMatcher)

    现在您了解了根本问题,现在可以将代码更改为如下内容:

    http
        .requestMatchers()
            .antMatchers("/apis/id/**", "/csrf","/v2/api-docs","/swagger-resources/configuration/ui",  "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**","/swagger-resources/configuration/ui","/swagger-resources/configuration/security", "/configuration/security").permitAll()
            .anyRequest().authenticated();
    

    【讨论】:

    • 嘿@Royts,如果我需要为所有“/apis/id/**”而不是“/apis/id/get/**”使用令牌进行身份验证,我该怎么做?
    • 与上面的答案相同。假设你使用spring security来验证你的token,你只需要把你不想验证的所有api放在antmatchers().permitAll()中,否则.anyRequest().authenticated();将验证所有未标记的api作为 .permitAll()
    • 在上面的例子中,我们已经允许了一些在 antMatchers 中提到的模式的路径,除了我们正在验证的那些模式,我需要对像 /web/** 这样的父模式进行身份验证和不对 /web/get/** 进行身份验证
    • 您上面的示例不起作用,因为 .permitAll() 方法适用于 AuthorizedUrl。而 requestMatchers().antMatchers 返回 RequestMatcherConfigurer
    • 也许你可以尝试像docs.spring.io/spring-security/site/docs/current/reference/…这样实现多个http配置。不过我还没有尝试过这种情况。
    猜你喜欢
    • 2020-06-10
    • 1970-01-01
    • 2016-05-01
    • 2016-01-31
    • 1970-01-01
    • 2022-10-24
    • 2017-01-09
    • 1970-01-01
    • 2022-11-18
    相关资源
    最近更新 更多