【问题标题】:How to check security access before validation (@Valid) in Controller?如何在控制器中验证(@Valid)之前检查安全访问?
【发布时间】:2022-01-02 21:18:07
【问题描述】:

我正在使用 Spring Boot 2.5 创建一个 Restful API,并且想知道在检查某些路由的角色时实现验证的正确方法。此外,对于某些路由,我需要确保只有管理员才能修改资源或其所有者。

@PreAuthorize 似乎是解决方案,但@Valid 似乎在实际方法调用之前处理,否则称为在@PreAuthorize 之前执行。

见:How to check security acess (@Secured or @PreAuthorize) before validation (@Valid) in my Controller?

这真的是唯一可用且干净的解决方案,可以使用 Spring Boot 和 Spring Security 来创建一个具有验证和角色的 Restful API 吗?

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    恐怕这是最干净的解决方案。 要检查某些路由的角色,您可以配置 HttpSecurity 以在到达控制器之前检查角色,如下所示:

    @Bean
    SecurityFilterChain app(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((requests) -> requests
            .antMatchers("/route1").hasAnyRole("ADMIN", "USER")
        )
        return http.build();
    }
    

    因此,使用此配置,您可以确保只允许 ROLE_USERROLE_ADMIN 请求 /route1

    但是现在,ROLE_USER 仅在他们是资源所有者的情况下才被允许。为此,您必须解析方法参数才能知道您正在请求哪个资源。然后,在@PreAuthorize 中,您可以执行以下操作:

    @PreAuthorize("@myBean.isResourceOwner(resourceId, authentication)")
    @PutMapping("/{resourceId}")
    public void update(@PathVariable Long resourceId) {
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-11
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-26
      • 2017-05-28
      相关资源
      最近更新 更多