Spring Security之RBAC模型
RBAC权限模型
RBAC(Role-based access control)是一种以角色为基础的访问控制(Role-based access control,RBAC),它是一种较新且广为使用的权限控制机制,这种机制不是直接给用户赋予权限,而是将权限赋予角色。
RBAC 权限模型将用户按角色进行归类,通过用户的角色来确定用户对某项资源是否具备操作权限。RBAC 简化了用户与权限的管理,它将用户与角色关联、角色与权限关联、权限与资源关联,这种模式使得用户的授权管理变得非常简单和易于维护。
数据库设计如下:
要求:
Spring Boot + Spring data jpa + lombok + web + Spring Security + mysql
pom依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
代码实现:
SecurityConfig 配置类:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SysSecurityService sysSecurityService;
@Resource
private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
@Resource
private MyAuthenticationFailHandler myAuthenticationFailHandler;
@Autowired
private DataSource dataSource;
//http配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/admin/**")
.formLogin().loginPage("/admin/login")
.successHandler(myAuthenticationSuccessHandler)
.failureHandler(myAuthenticationFailHandler)
.and().logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/admin/login");
//认证权限
http.authorizeRequests()
.antMatchers("/admin/login").permitAll()
//rbac 访问admin/rbac时,使用自定义hasPermission验证是否允许访问
//.antMatchers("/admin/list","/admin/add","/admin/del")
.anyRequest()
.access("@rbacService.hasPermission(request , authentication)");
//记住我
http.rememberMe()