MonitorRealm;

本文介绍了一个基于Apache Shiro框架实现的权限认证示例。通过继承AuthorizingRealm类,完成用户登录验证及权限分配功能。文章展示了如何从数据库获取用户信息进行身份验证,并通过角色和权限集来为用户授权。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package org.seven.MonitorRealm;


import java.util.HashSet;
import java.util.List;
import java.util.Set;


import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.seven.bean.ShiroUser;
import org.seven.service.UserServiceImp;
import org.seven.util.BlankUtil;
import org.springframework.beans.factory.annotation.Autowired;




public class MonitorRealm extends AuthorizingRealm {
@Autowired
private UserServiceImp service;

/*
* 验证当前用户的用户

*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// TODO Auto-generated method stub
try {
String username = (String)token.getPrincipal();
ShiroUser user = service.login(username);
if(user!=null){
AuthenticationInfo authinfo=new  SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),"xx");
// 身份认证
return authinfo;
}else{
return null;
}

} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/*
* 为当前登录用户授权
*/

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// TODO Auto-generated method stub
String username = (String) principals.getPrimaryPrincipal();
// 权限认证
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//放置角色名
Set<String> roleSet=new HashSet<String>();
//放置权限
Set<String> permissionSet=new HashSet<String>();

List<ShiroUser> roles = service.getRoles(username);
List<ShiroUser> permission = service.getPermission(username);
for (ShiroUser shiroUser : permission) {
String pname = shiroUser.getPname();
System.out.println(pname+"pname");
permissionSet.add(pname);

}

for (ShiroUser shiroUser : roles) {
String role_name = shiroUser.getRole_name();
System.out.println(role_name+"role_name");
roleSet.add(shiroUser.getRole_name());
}



System.out.println(roleSet+"roleSet");
System.out.println(permissionSet+"permissionSet");
authorizationInfo.setRoles(roleSet);  
    authorizationInfo.setStringPermissions(permissionSet);  




// 设置当前用户的角色
// 设置权限

return authorizationInfo;

}



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值