有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Spring安全性解除方法的安全性

我已经为一个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模式更改的解决方案,因为它会影响许多其他模块


共 (1) 个答案

  1. # 1 楼答案

    下面是允许请求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();
    }