一、授权基本思路
在springsecurity中,会使用默认的filtersecurityinterceptor来进行权限校验。在 filtersecurityinterceptor中会从securitycontextholder获取其中的authentication,然后获取其中的 权限信息。当前用户是否拥有访问当前资源所需的权限。
所以我们在项目中只需要把当前登录用户的权限信息也存入authentication。然后设置我们的资源所需 要的权限即可
二、实现过程
(1)开启相关配置
@enableglobalmethodsecurity(prepostenabled = true)
public class securityconfig{
.....
}然后就可以使用对应的注解。@preauthorize在各接口
@restcontroller
public class hellocontroller {
@requestmapping("/hello")
@preauthorize("hasauthority('test')")
public string hello(){
return "hello";
}
}(2)自定义loginuser,封装权限信息
我们之前定义了userdetails的实现类loginuser,想要让其能封装权限信息就要对其进行修改。
@data
@noargsconstructor
public class loginuser implements userdetails{
private user user;
//查询到的权限列表
private list<string> list;
public loginuser(user user, list<string> list) {
this.list = list;
this.user = user;
}
//自定义一个权限列表的集合 中转操作
@jsonfield(serialize = false)
list<simplegrantedauthority> authorities;
//返回权限
@override
public collection<? extends grantedauthority> getauthorities() {
if (authorities != null) {
return authorities;
}
authorities = new arraylist<>();
for (string item : list) {
simplegrantedauthority authority = new simplegrantedauthority(item);
authorities.add(authority);
}
return authorities;
}
//获取密码
@override
public string getpassword() {
return user.getpassword();
}
//获取用户名
@override
public string getusername() {
return user.getusername();
}
//判断账号是否未过期
@override
public boolean isaccountnonexpired() {
return true;
}
//判断账号是否没有锁定
@override
public boolean isaccountnonlocked() {
return true;
}
//判断账号是否没有超时
@override
public boolean iscredentialsnonexpired() {
return true;
}
//判断账号是否可用
@override
public boolean isenabled() {
return true;
}
}(3)从数据库查询权限信息
rbac模型
我们可以在userdetailsserviceimpl中去调用该mapper的方法查询权限信息封装到loginuser对象 中即可。
@service
public class userdetailserviceimpl implements userdetailsservice {
@autowired
private usermapper usermapper;
@autowired
private menumapper menumapper;
@override
public userdetails loaduserbyusername(string username) throws usernamenotfoundexception {
//1.查询用户信息
querywrapper<user> querywrapper = new querywrapper<>();
querywrapper.eq("user_name", username);
user user = usermapper.selectone(querywrapper);
//如果没有查询到用户,就抛出异常
if (objects.isnull(user)) {
throw new runtimeexception("用户名或密码错误");
}
//2.查询用户对应的权限信息
// list<string> list = new arraylist<>();
// list.add("select");
// list.add("delete");
list<string> list = menumapper.selectpermsbyuserid(user.getid());
//3.返回userdetails对象
return new loginuser(user, list);
}
}到此这篇关于springsecurity授权实现的文章就介绍到这了,更多相关springsecurity授权内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论