【问题标题】:How to give different role permissions to same url with different request method types in spring boot secuirty如何在spring boot secuirty中为具有不同请求方法类型的相同url赋予不同的角色权限
【发布时间】:2018-08-10 16:26:28
【问题描述】:

我正在使用 Spring Boot Security 来验证和授权我的其余 http api。 我看到我们可以像这样设置授权设置

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@EnableWebSecurity
    @Configuration
    class WebSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()
//              .anyRequest().permitAll()
                .antMatchers("/user/health_check/*").permitAll()
                .antMatchers("/user/registration").permitAll()
    .antMatchers("/user/login","/user/logout").hasAnyRole("USER","ADMIN","MANAGER")
                .antMatchers("/admin/*").fullyAuthenticated()
                .and().httpBasic()
                .and().csrf().disable();

        }

    }

我想知道如何对请求方法不同的不同url赋予不同的权限?

例如: 如果我有两个像

这样的网址
// GET /api/account/{id}
// POST /api/account/{id}
// PUT /api/account/{id}

我希望只授予对 PUT 的管理员访问权限和对 GET 的用户访问权限以及对 POST 的用户和管理员访问权限。我该如何实现?

【问题讨论】:

    标签: java spring spring-boot authentication authorization


    【解决方案1】:

    您可以在antMatchers中传递请求方法。

    试试这个:

                http
                    .httpBasic().and()
                    .authorizeRequests()
                    .antMatchers(HttpMethod.GET, "/api/account/**").hasRole("ADMIN")
                    .antMatchers(HttpMethod.POST, "/api/account/**").hasRole("ADMIN")
                    .antMatchers(HttpMethod.PUT, "/api/account/**").hasRole("ADMIN");
    

    【讨论】:

      【解决方案2】:

      你可以在控制器的方法上使用@PreAuthorize注解:

      @GetMapping("/api/account/{id}")
      @PreAuthorize("hasAutority('readAccountById')")
      public Account getAccount(@PathVariable Integer id){
         ...
      }
      

      它适用于 Spring 安全上下文,您可以检查用户角色、权限等等。

      参考看这篇文章https://www.baeldung.com/spring-security-method-security

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-09
        • 1970-01-01
        • 2019-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多