用Spring Security快速实现 RABC模型案例

2024-05-28 10:44

本文主要是介绍用Spring Security快速实现 RABC模型案例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

RABC模型通常是指“基于角色的访问控制”(Role-Based Access Control,RBAC)模型。这是一种广泛使用的访问控制机制,用于限制用户或系统对计算机或网络资源的访问。在RBAC模型中,权限与角色相关联,用户通过分配角色来获得相应的权限,而不是直接将权限分配给用户。

下面 V 哥教你一步一步来实现 RABC 模型,你可以使用这个案例根据实际需求应用到你的项目中。

RBAC模型的主要组成部分包括:

  • 用户(Users):系统中的个体,可以是人、程序或设备。
  • 角色(Roles):定义在系统中的工作或责任的抽象。例如,“管理员”、“普通用户”、“访客”等。
  • 权限(Permissions):对系统资源的访问许可。例如,读、写、修改等操作。
  • 会话(Sessions):用户与系统交互的时期,用户可以在会话中激活其角色并获得相应的权限。
  • 角色分配(Role Assignments):将用户与角色相关联的过程。
  • 权限分配(Permission Assignments):将权限与角色相关联的过程。
  • 角色层次(Role Hierarchy):如果一组角色之间存在层次关系,可以形成角色层次,允许高级角色继承低级角色的权限。

RBAC模型的实施能够简化权限管理,使得权限的变更更为灵活,便于在大型组织中实施和维护。例如,如果一个用户的工作职责发生变化,只需要改变其角色,就可以自动调整其权限,而不需要逐个修改其权限设置。

在实施时,组织通常会根据自身的业务需求定制角色和权限,确保系统的安全性和用户的便利性。在中国,许多企业和政府部门都采用了基于角色的访问控制模型来提升信息系统的安全性和管理效率。

在Java Spring Security中实现RBAC模型通常涉及以下步骤:

  • 定义用户(User)和角色(Role)实体。
  • 配置Spring Security以使用自定义的UserDetailsService。
  • 创建角色和权限,并将它们分配给用户。
  • 配置Spring Security的WebSecurityConfigurerAdapter以使用角色进行访问控制。
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;@Entity
@Table(name = "users")
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String username;private String password;@ManyToMany(fetch = FetchType.EAGER)@JoinTable(name = "user_roles",joinColumns = @JoinColumn(name = "user_id"),inverseJoinColumns = @JoinColumn(name = "role_id"))private Set<Role> roles = new HashSet<>();// Getters and Setters
}@Entity
@Table(name = "roles")
public class Role {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;// Getters and Setters
}

接下来,创建一个UserDetailsService的实现,用于加载用户和他们的权限:

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;@Service
public class CustomUserDetailsService implements UserDetailsService {private final UserRepository userRepository;public CustomUserDetailsService(UserRepository userRepository) {this.userRepository = userRepository;}@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {User user = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),mapRolesToAuthorities(user.getRoles()));}private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles) {return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());}
}

然后,配置Spring Security的WebSecurityConfigurerAdapter:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {private final CustomUserDetailsService customUserDetailsService;public SecurityConfig(CustomUserDetailsService customUserDetailsService) {this.customUserDetailsService = customUserDetailsService;}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasAnyRole("USER", "ADMIN").antMatchers("/").permitAll().and().formLogin();}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}

在这个配置中,我们定义了不同URL路径的访问权限,例如/admin/**只允许具有ADMIN角色的用户访问,而/user/**则允许USER和ADMIN角色的用户访问。

最后,你需要创建一个Spring Data JPA的Repository来处理用户和角色的数据持久化:

public interface UserRepository extends JpaRepository<User, Long> {Optional<User> findByUsername(String username);
}

这个示例提供了一个基础的RBAC实现,实际应用中可能需要更复杂的角色和权限管理,以及与业务逻辑更紧密的集成。在实际部署时,还需要考虑加密用户密码、处理用户登录和注销、以及可能的安全漏洞。

首先,定义用户和角色实体:

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;@Entity
@Table(name = "users")
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String username;private String password;@ManyToMany(fetch = FetchType.EAGER)@JoinTable(name = "user_roles",joinColumns = @JoinColumn(name = "user_id"),inverseJoinColumns = @JoinColumn(name = "role_id"))private Set<Role> roles = new HashSet<>();// Getters and Setters
}@Entity
@Table(name = "roles")
public class Role {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;// Getters and Setters
}

接下来,创建一个UserDetailsService的实现,用于加载用户和他们的权限:

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;@Service
public class CustomUserDetailsService implements UserDetailsService {private final UserRepository userRepository;public CustomUserDetailsService(UserRepository userRepository) {this.userRepository = userRepository;}@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {User user = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),mapRolesToAuthorities(user.getRoles()));}private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles) {return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());}
}

然后,配置Spring Security的WebSecurityConfigurerAdapter:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {private final CustomUserDetailsService customUserDetailsService;public SecurityConfig(CustomUserDetailsService customUserDetailsService) {this.customUserDetailsService = customUserDetailsService;}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasAnyRole("USER", "ADMIN").antMatchers("/").permitAll().and().formLogin();}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}

在这个配置中,我们定义了不同URL路径的访问权限,例如/admin/**只允许具有ADMIN角色的用户访问,而/user/**则允许USER和ADMIN角色的用户访问。

最后,你需要创建一个Spring Data JPA的Repository来处理用户和角色的数据持久化:

public interface UserRepository extends JpaRepository<User, Long> {Optional<User> findByUsername(String username);
}

这个示例提供了一个基础的RBAC实现,实际应用中可能需要更复杂的角色和权限管理,以及与业务逻辑更紧密的集成。在实际部署时,还需要考虑加密用户密码、处理用户登录和注销、以及可能的安全漏洞。

最后

这是一个简单的 RBAC 模型案例,通过这个案例,你可以了解 RBAC 模型的实现步骤,应用在你的实际项目中,当然你需要考虑实际项目中的具体需求和逻辑来改造这个案例,你学会了吗。

这篇关于用Spring Security快速实现 RABC模型案例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1010339

相关文章

Java实现字节字符转bcd编码

《Java实现字节字符转bcd编码》BCD是一种将十进制数字编码为二进制的表示方式,常用于数字显示和存储,本文将介绍如何在Java中实现字节字符转BCD码的过程,需要的小伙伴可以了解下... 目录前言BCD码是什么Java实现字节转bcd编码方法补充总结前言BCD码(Binary-Coded Decima

SpringBoot全局域名替换的实现

《SpringBoot全局域名替换的实现》本文主要介绍了SpringBoot全局域名替换的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录 项目结构⚙️ 配置文件application.yml️ 配置类AppProperties.Ja

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

JavaScript中的高级调试方法全攻略指南

《JavaScript中的高级调试方法全攻略指南》什么是高级JavaScript调试技巧,它比console.log有何优势,如何使用断点调试定位问题,通过本文,我们将深入解答这些问题,带您从理论到实... 目录观点与案例结合观点1观点2观点3观点4观点5高级调试技巧详解实战案例断点调试:定位变量错误性能分

Python实现批量CSV转Excel的高性能处理方案

《Python实现批量CSV转Excel的高性能处理方案》在日常办公中,我们经常需要将CSV格式的数据转换为Excel文件,本文将介绍一个基于Python的高性能解决方案,感兴趣的小伙伴可以跟随小编一... 目录一、场景需求二、技术方案三、核心代码四、批量处理方案五、性能优化六、使用示例完整代码七、小结一、

Java实现将HTML文件与字符串转换为图片

《Java实现将HTML文件与字符串转换为图片》在Java开发中,我们经常会遇到将HTML内容转换为图片的需求,本文小编就来和大家详细讲讲如何使用FreeSpire.DocforJava库来实现这一功... 目录前言核心实现:html 转图片完整代码场景 1:转换本地 HTML 文件为图片场景 2:转换 H

Java使用jar命令配置服务器端口的完整指南

《Java使用jar命令配置服务器端口的完整指南》本文将详细介绍如何使用java-jar命令启动应用,并重点讲解如何配置服务器端口,同时提供一个实用的Web工具来简化这一过程,希望对大家有所帮助... 目录1. Java Jar文件简介1.1 什么是Jar文件1.2 创建可执行Jar文件2. 使用java

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

C#实现一键批量合并PDF文档

《C#实现一键批量合并PDF文档》这篇文章主要为大家详细介绍了如何使用C#实现一键批量合并PDF文档功能,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言效果展示功能实现1、添加文件2、文件分组(书签)3、定义页码范围4、自定义显示5、定义页面尺寸6、PDF批量合并7、其他方法

SpringBoot实现不同接口指定上传文件大小的具体步骤

《SpringBoot实现不同接口指定上传文件大小的具体步骤》:本文主要介绍在SpringBoot中通过自定义注解、AOP拦截和配置文件实现不同接口上传文件大小限制的方法,强调需设置全局阈值远大于... 目录一  springboot实现不同接口指定文件大小1.1 思路说明1.2 工程启动说明二 具体实施2