首页 > 解决方案 > 如果有参数,SpringBoot websecurity 不会忽略 url

问题描述

我试图忽略 SpringBoot 中 WebSecurity 的 url。能够为精确的网址匹配做到这一点。但是如果 url 本身有一个参数,它就不能忽略它。有没有更好的方法来忽略 url,比如忽略特定的控制器。如果没有,如何使用参数?

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/v1/something");
    // was able to ignore [url]/api/v1/something but not [url]/api/v1/something?xyz=wjsbjbjbsjbw
}

标签: springspring-bootwebsecurity

解决方案


如果您在当前的 antMatcher 规范之后附加一个星号 (*),您应该可以实现您的目标。

根据定义:

映射使用以下规则匹配 URL:

  • ? 匹配一个字符
  • * 匹配零个或多个字符
  • ** 匹配路径中的零个或多个目录
  • {spring:[az]+} 匹配正则表达式 [az]+ 作为名为“spring”的路径变量

您的代码的重要片段可能如下所示:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/v1/something*");
}

您也可以使用其他重载配置方法和HttpSecurity路径相关安全配置的类型参数来实现相同的目的,如下所示:

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/api/v1/something*").permitAll();
}

如定义中所述,您还可以更进一步,当您的 AntMatcher 以/**. 但这实际上取决于您的用例。有关实现细节,请查看Spring AntPathRequestMatcher


您相应的请求映射应如下所示(以@GetMapping 为例)。重要的是,您的路径没有尾随/.

@GetMapping("/api/v1/something")
public ResponseEntity<String> getSomething(@RequestParam(value = "xyz", required = false) String xyz){
    return ResponseEntity.ok("Called with xyz param: " + xyz);
}

推荐阅读