微服务技术系列教程(39)- SpringBoot -RBAC权限模型

1. 引言

代码和相关的sql脚本已提交至Github,有兴趣的同学可以下载看看:https://github.com/ylw-github/SpringBoot-Security-Demo

SQL脚本执行完成后,会生成5张表,相当于把上一篇博客《微服务技术系列教程(38)- SpringBoot -整合SpringSecurity》的权限配置内容全部配置到数据库了,从数据库中读取:
在这里插入图片描述

2. RBAC权限模型

RBAC权限模型 : 基于角色的权限访问控制(Role-Based Access Control)作为传统访问控制(自主访问,强制访问)的有前景的代替受到广泛的关注。

在RBAC中,权限与角色相关联,用户通过成为适当角色的成员而得到这些角色的权限。这就极大地简化了权限的管理。在一个组织中,角色是为了完成各种工作而创造,用户则依据它的责任和资格来被指派相应的角色,用户可以很容易地从一个角色被指派到另一个角色。

角色可依新的需求和系统的合并而赋予新的权限,而权限也可根据需要而从某角色中回收。角色与角色的关系可以建立起来以囊括更广泛的客观情况。

本文基于上一篇《微服务技术系列教程(38)- SpringBoot -整合SpringSecurity》的基础上来进行代码整合。

3. 代码整合

1.添加Maven依赖:

<!-->spring-boot 整合security -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- springboot 整合mybatis框架 -->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.3.2</version>
</dependency>
<!-- alibaba的druid数据库连接池 -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid-spring-boot-starter</artifactId>
	<version>1.1.9</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>

2.application.yml配置:

# 配置freemarker
spring:
  freemarker:
    # 设置模板后缀名
    suffix: .ftl
    # 设置文档类型
    content-type: text/html
    # 设置页面编码格式
    charset: UTF-8
    # 设置页面缓存
    cache: false
    # 设置ftl文件路径
    template-loader-path:
      - classpath:/templates
  # 设置静态文件路径,js,css等
  mvc:
    static-path-pattern: /static/**
  ####整合数据库层
  datasource:
    name: test
    url: jdbc:mysql://127.0.0.1:3306/rbac_db
    username: root
    password: 123456
    # druid 连接池
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver

3.添加mapper:

public interface UserMapper {
	// 查询用户信息
	@Select(" select * from sys_user where username = #{userName}")
	User findByUsername(@Param("userName") String userName);

	// 查询用户的权限
	@Select(" select permission.* from sys_user user" + " inner join sys_user_role user_role"
			+ " on user.id = user_role.user_id inner join "
			+ "sys_role_permission role_permission on user_role.role_id = role_permission.role_id "
			+ " inner join sys_permission permission on role_permission.perm_id = permission.id where user.username = #{userName};")
	List<Permission> findPermissionByUsername(@Param("userName") String userName);
}

4.动态查询账号

// 设置动态用户信息
@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 1.根据用户名称查询数据用户信息
        User user = userMapper.findByUsername(username);
        // 2.底层会根据数据库查询用户信息,判断密码是否正确
        // 3. 给用户设置权限
        List<Permission> listPermission = userMapper.findPermissionByUsername(username);
        System.out.println("username:" + username + ",对应权限:" + listPermission.toString());
        if (listPermission != null && listPermission.size() > 0) {
            // 定义用户权限
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            for (Permission permission : listPermission) {
                authorities.add(new SimpleGrantedAuthority(permission.getPermTag()));
            }
            user.setAuthorities(authorities);
        }
        return user;
    }

}

5.Security权限控制:

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	private MyAuthenticationFailureHandler failureHandler;
	@Autowired
	private MyAuthenticationSuccessHandler successHandler;
	@Autowired
	private MyUserDetailsService myUserDetailsService;
	@Autowired
	private PermissionMapper permissionMapper;

	// 配置认证用户信息和权限
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// // 添加admin账号
		// auth.inMemoryAuthentication().withUser("admin").password("123456").
		// authorities("showOrder","addOrder","updateOrder","deleteOrder");
		// // 添加userAdd账号
		// auth.inMemoryAuthentication().withUser("userAdd").password("123456").authorities("showOrder","addOrder");
		// 如果想实现动态账号与数据库关联 在该地方改为查询数据库
		auth.userDetailsService(myUserDetailsService).passwordEncoder(new PasswordEncoder() {

			// 加密的密码与数据库密码进行比对CharSequence rawPassword 表单字段 encodedPassword
			// 数据库加密字段
			public boolean matches(CharSequence rawPassword, String encodedPassword) {
				System.out.println("rawPassword:" + rawPassword + ",encodedPassword:" + encodedPassword);
				// 返回true 表示认证成功 返回fasle 认证失败
				return MD5Util.encode((String) rawPassword).equals(encodedPassword);
			}

			// 对表单密码进行加密
			public String encode(CharSequence rawPassword) {
				System.out.println("rawPassword:" + rawPassword);
				return MD5Util.encode((String) rawPassword);
			}
		});
	}

	// 配置拦截请求资源
	protected void configure(HttpSecurity http) throws Exception {
		ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests = http
				.authorizeRequests();
		// 1.读取数据库权限列表
		List<Permission> listPermission = permissionMapper.findAllPermission();
		for (Permission permission : listPermission) {
			// 设置权限
			authorizeRequests.antMatchers(permission.getUrl()).hasAnyAuthority(permission.getPermTag());
		}
		authorizeRequests.antMatchers("/login").permitAll().antMatchers("/**").fullyAuthenticated().and().formLogin()
				.loginPage("/login").successHandler(successHandler).and().csrf().disable();

	}

	@Bean
	public static NoOpPasswordEncoder passwordEncoder() {
		return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
	}

}

5.密码使用MD5加密

public class MD5Util {

	// 加盐
	private static final String SALT = "ylw";

	public static String encode(String password) {
		password = password + SALT;
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		char[] charArray = password.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}

			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	public static void main(String[] args) {
		System.out.println(MD5Util.encode("123456"));

	}
}

4. 测试

有两个账号已经保存到数据库:

  • 账号:admin 密码:123456
  • 账号:userAdd 密码:123456

测试结果与上一篇博客《微服务技术系列教程(38)- SpringBoot -整合SpringSecurity》结果一样,区别在于可以动态配置权限。

比如:userAdd 不能删除或者修改订单,现在要求userAdd可以修改订单,那么,修改数据库的sys_role_permission
在这里插入图片描述
userAdd新增一条修改权限:

INSERT INTO `sys_role_permission` VALUES ('2', '3');

在这里插入图片描述
再使用userAdd账号重新登录,发现userAdd有修改功能了。
在这里插入图片描述
代码和相关的sql脚本已提交至Github,有兴趣的同学可以下载看看:https://github.com/ylw-github/SpringBoot-Security-Demo

本文完!

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RBAC权限管理系统是基于角色的用户权限控制系统。在springboot中,我们可以使用Spring Security框架来实现RBAC权限管理。Spring Security是一个功能强大的、灵活的框架,可以帮助我们在应用程序中实现身份验证、授权和其他安全功能。 要在springboot中使用RBAC权限管理系统,可以按照以下步骤进行操作: 1. 导入Spring Security依赖:在pom.xml文件中添加Spring Security相关的依赖项。 2. 配置Spring Security:在应用程序的配置文件中,设置Spring Security的基本参数,例如认证方式、登录页面等。 3. 创建用户和角色实体:使用实体类表示用户和角色,并建立它们之间的关系。 4. 实现用户认证和授权:通过自定义的用户认证和授权逻辑,实现用户登录验证和权限控制。可以使用注解或配置文件的方式进行权限配置。 5. 创建页面和接口:根据系统需求,创建相应的页面和接口,并为每个角色分配不同的权限。 6. 完善系统功能:根据实际需求,完善RBAC权限管理系统的其他功能,例如日志记录、异常处理等。 需要注意的是,以上步骤仅为概括性的指导,实际操作可能会因具体需求而有所不同。可以根据具体的项目情况进行适当的调整和扩展。 总结起来,springboot中的RBAC权限管理是通过使用Spring Security框架来实现的,需要进行依赖导入、配置、实体创建、认证和授权逻辑实现、页面和接口创建等步骤。通过这些步骤,可以构建一个完善的RBAC权限管理系统。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值