如何对REST API进行角色验证?
我有2个角色,分别为admin
和manager
。如何使用RBAC(基于角色的访问控制)限制REST API的访问?例如,/users
角色可以访问admin
POST,/users
角色可以访问manager
GET。
答案 0 :(得分:0)
您可以使用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();
}
}