如何在Spring Boot安全性中为具有不同请求方法类型的同一个URL赋予不同的角色权限

时间:2018-08-10 16:26:28

标签: java spring spring-boot authentication authorization

我正在使用Spring Boot安全性来认证和授权其余的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则授予用户和管理员访问权限。

2 个答案:

答案 0 :(得分:2)

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

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

它与Spring安全上下文一起使用,并且您可以检查用户角色,权限等。

供参考,请参阅本文https://www.baeldung.com/spring-security-method-security

答案 1 :(得分:2)

您可以在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");