如何解除具有 Spring 安全性的方法

How to unsecure a method with Spring security

我已经为 RESTful Web 服务项目实现了 Spring 安全性。它具有具有相同 url 模式但具有不同请求方法类型的请求映射。

@RequestMapping(value = "/charity/accounts", method = RequestMethod.POST)
public AccountResponseDto createAccount(HttpServletResponse response, @RequestBody AccountRequestDto requestDTO) {
    // some logics here
}

@RequestMapping(value = "/charity/accounts", method = RequestMethod.GET)
public AccountResponseDto getAccount(HttpServletResponse response) {
    // some logics here
}

@RequestMapping(value = "/charity/accounts", method = RequestMethod.PUT)
public void updateAccount(HttpServletResponse response, @RequestBody AccountRequestDto requestDTO){
    // some logics here
}

目前所有这些方法都需要授权才能执行,但我需要取消对createAccount(...)方法的授权。是否有基于注释的解决方案?

注意: 我需要一个不会影响 url 模式更改的解决方案,因为它会影响许多其他模块。

下面是允许请求 signupabout 的示例配置:

@EnableWebSecurity
@Configuration
public class CustomWebSecurityConfigurerAdapter extends
   WebSecurityConfigurerAdapter {
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) {
    auth
      .inMemoryAuthentication()
        .withUser("user")  // #1
          .password("password")
          .roles("USER")
          .and()
        .withUser("admin") // #2
          .password("password")
          .roles("ADMIN","USER");
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeUrls()
        .antMatchers("/signup","/about").permitAll();
  }
}

您可以参考Spring Security Java Config了解详细信息。

关于您的控制器的建议。如果所有前缀为 /charity 的请求都由 CharityController 处理,则可以通过以下方式映射请求:

@Controller
@RequestMapping(value="/charity")
class CharityController {
            @RequestMapping(value = "/accounts", method = RequestMethod.GET)
            public AccountResponseDto getAccount(HttpServletResponse response){

            }
}

更新

以下应该适合您。

protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers(HttpMethod.POST, new String [] {"/charity/accounts", "/charity/people"}).permitAll();
}

这就是为什么我们有角色、权限..首先我们可以定义谁可以 GET/PUT/POST 并相应地向用户授予权限。

然后我们可以相应地在GET/PUT/POST方法上注释为@Secured("ROLE_ADMIN")。

要不保护 GET,您可以添加 @PreAuthorize("isAnonymous()") 或 @Secured("MY_CUSTOM_ANONYM_ROLE")