【问题标题】:How to unsecure a method with Spring security如何使用 Spring 安全性解除方法的安全性
【发布时间】:2015-12-07 14:52:45
【问题描述】:

我已经为一个 RESTful Web 服务项目实现了 Spring Security。它具有具有相同 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 模式进行更改的解决方案,因为它会影响许多其他模块。

【问题讨论】:

  • 发布您的安全配置!!

标签: java spring spring-mvc spring-security spring-annotations


【解决方案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();
}

【讨论】:

  • 感谢 James 的快速回复,但在我的情况下,我无法使用“http .authorizeUrls() .antMatchers("/charity/accounts").permitAll();”因为目前这个相同的 url 模式也用于其他两种方法(getAccount 和 updateAccount 方法),我需要授权。我只需要从 createAccount 方法中删除 Authorization 而不是其他方法。
  • @zulox,很抱歉我没有注意到网址格式。请找到更新的答案部分。
【解决方案2】:

这就是我们有角色、授权的原因。首先我们可以定义谁可以 GET/PUT/POST 并相应地授予用户权限。

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

要使 GET 不安全,您可以添加 @PreAuthorize("isAnonymous()") 或 @Secured("MY_CUSTOM_ANONYM_ROLE")

【讨论】:

  • @PreAuthorize("isAnonymous()") 上的有趣提示。它还允许对带有 @Secured("..") 注释的类中的方法进行解密,以防您只需要对整个类中的一个方法进行解密。
猜你喜欢
  • 1970-01-01
  • 2014-03-07
  • 2014-01-02
  • 2011-10-04
  • 2012-12-03
  • 2014-03-25
  • 1970-01-01
  • 2021-12-15
  • 2014-01-04
相关资源
最近更新 更多