如何在 Spring Boot secuirty 中为具有不同请求方法类型的同一 url 授予不同的角色权限

sta*_*ion 2 java authentication spring authorization spring-boot

我正在使用 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();

        }

    }
Run Code Online (Sandbox Code Playgroud)

我想知道如何为请求方法不同的不同网址授予不同的权限?

例如:如果我有两个网址

// GET /api/account/{id}
// POST /api/account/{id}
// PUT /api/account/{id}
Run Code Online (Sandbox Code Playgroud)

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

saj*_*jib 6

您可以在 中传递请求方法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");
Run Code Online (Sandbox Code Playgroud)