文章目录
Rbac动态权限控制
1、RBAC(基于角色的权限控制)模型的核心是在用户和权限之间引入了角色的概念。取消了用户和权限的直接关联,改为通过用户关联角色、角色关联权限的方法来间接地赋予用户权限(如下图),从而达到用户和权限解耦的目的。
2、Maven依赖
<!-- 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>
3、配置文件
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/mayikt_rbac
username: root
password: root
# druid 连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
4、Mapper接口
导入Mapper接口
5、动态根据账户名称查询权限
使用UserDetailsService实现动态查询数据库验证账号
@Component
@Slf4j
public class MemberDetailsService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
// 1.根据用户名称查询到user用户
UserEntity userDetails = userMapper.findByUsername(userName);
if (userDetails == null) {
return null;
}
// 2.查询该用户对应的权限
List<PermissionEntity> permissionList = userMapper.findPermissionByUsername(userName);
ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
permissionList.forEach((a) -> {
grantedAuthorities.add(new SimpleGrantedAuthority(a.getPermTag()));
});
log.info(">>permissionList:{}<<",permissionList);
// 设置权限
userDetails.setAuthorities(grantedAuthorities);
return userDetails;
}
}
6、WebSecurity相关配置
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MemberDetailsService memberDetailsService;
@Autowired
private PermissionMapper permissionMapper;
/**
* 新增授权账户
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/**
* 新增一个账户mayikt 密码也是为mayikt 可以允许访问所有的请求
*/
// auth.inMemoryAuthentication().withUser("mayikt").password("mayikt").authorities("mayikt");
/**
* 1.新增mayikt_admin mayikt_admin 权限可以访问所有请求
*/
// auth.inMemoryAuthentication().withUser("mayikt_admin").password("mayikt_admin").authorities("addMember"
// , "delMember", "updateMember", "showMember");
// auth.inMemoryAuthentication().withUser("mayikt_add").password("mayikt_add").authorities("addMember");
// auth.inMemoryAuthentication().withUser("mayikt_del").password("mayikt_del").authorities("delMember");
// auth.inMemoryAuthentication().withUser("mayikt_update").password("mayikt_update").authorities("updateMember");
// auth.inMemoryAuthentication().withUser("mayikt_show").password("mayikt_show").authorities("showMember");
auth.userDetailsService(memberDetailsService).passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence rawPassword) {
return MD5Util.encode((String) rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
String rawPass = MD5Util.encode((String) rawPassword);
boolean result = rawPass.equals(encodedPassword);
return result;
}
});
}
/**
* 新增 HttpSecurity配置
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// /**
// * 拦截 http 安全认证模式 设置为httpBasic模式
// */
// http.authorizeRequests().antMatchers("/**").fullyAuthenticated()
// .and().httpBasic();
/**
* 拦截 http 安全认证模式 设置为formLogin模式
*/
// http.authorizeRequests().antMatchers("/**").fullyAuthenticated()
// .and().formLogin();
// http.authorizeRequests().antMatchers("/addMember").hasAnyAuthority("addMember")
// .antMatchers("/delMember").hasAnyAuthority("delMember")
// .antMatchers("/updateMember").hasAnyAuthority("updateMember")
// .antMatchers("/showMember").hasAnyAuthority("showMember")
antMatchers("/**").fullyAuthenticated()
.and().formLogin();
// //并且关闭csrf 设置跳转到自定义login页面 放开权限
// .antMatchers("/login").permitAll()
// // 设置自定义登录页面
// .antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").and().csrf().disable();
List<PermissionEntity> allPermission = permissionMapper.findAllPermission();
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry
authorizeRequests = http.authorizeRequests();
allPermission.forEach((p) -> {
authorizeRequests.antMatchers(p.getUrl()).hasAnyAuthority(p.getPermTag());
});
authorizeRequests.antMatchers("/login").permitAll()
// 设置自定义登录页面
.antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").and().csrf().disable();
}
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
7、MD5工具类
public class MD5Util {
private static final String SALT = "mayikt";
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("mayikt"));
}
}
注:码云地址 https://gitee.com/sdaewrwerew/mayikt-spring-security.git