REST API的基于角色的访问控制

时间:2019-10-09 11:14:02

标签: spring-boot api-gateway

如何对REST API进行角色验证?

我有2个角色,分别为adminmanager。如何使用RBAC(基于角色的访问控制)限制REST API的访问?例如,/users角色可以访问admin POST,/users角色可以访问manager GET。

1 个答案:

答案 0 :(得分:0)

您可以使用Spring Security来实现。

Spring Security

Spring Security是一个高度可定制的框架,被广泛用于处理任何用Java开发的基于Enterprise的应用程序中出现的身份验证和访问控制(授权)问题。

Ex:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {



    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeRequests().antMatchers("/user/login").permitAll().antMatchers(HttpMethod.OPTIONS)

                .permitAll()
                .antMatchers(HttpMethod.GET, "/user").hasRole("ADMIN")
                .antMatchers(HttpMethod.GET, "/user/list").hasAnyRole("MANAGER", "ADMIN")
                .authenticated();       

    }   
}