目录
一、RABC表的设计
二、查询权限并添加Security中
查询到权限后,接着在UserDetails中将自定义的权限集合转换为Security中的权限集合
//自定义认证服务
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UsersMapper usersMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
users s=usersMapper.findByUsername(username);
//查询用户的权限
if(s==null){
return null;
}
List<permission> permissionList=usersMapper.FindPermissionByUsername(username);
//将自定义的权限集合转换为Security的权限类型集合
List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
//开始遍历添加权限
for(permission permission:permissionList){
grantedAuthorities.add(new SimpleGrantedAuthority(permission.getUrl()));
}
//封装为UserDetailsService对象
UserDetails userDetailsService= User.withUsername(s.getUsername())
.password(s.getPassword())
.authorities(grantedAuthorities)
.build();
return userDetailsService;
}
}
这里的权限你可以写url路径来进行认证,也可以自己随便写点别的,反正作为标识即可。
三、通过注解进行授权
接着通过@PreAuthorize注解进行鉴权
//测试权限的方法
@PreAuthorize("hasAnyAuthority('/search')")
@RequestMapping("/search")
public String s1(){
return "查询权限";
}
@PreAuthorize("hasAnyAuthority('/update')")
@RequestMapping("/update")
public String u1(){
return "修改权限";
}
四、授权进行前端访问
在thymeleaf中前端鉴权时,别忘了写约束
<!DOCTYPE html>
<!-- 约束-->
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3 sec:authorize="hasAnyAuthority('/search')">查询</h3>
<h3 sec:authorize="hasAnyAuthority('/update')">修改</h3>
<h3 sec:authorize="hasAnyAuthority('/delete')">删除</h3>
<h3 sec:authorize="hasAnyAuthority('/insert')">添加</h3>
</body>
</html>