shiro-realm.ini
[main]
#自定义Realm
myRealm=test.shiro.MyRealm
#将myRealm设置到securityManager,相当于Spring中的注入
securityManager.realms=$myRealm
MyRealm.java
/**
* 授权
* @param principals
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String account = (String) principals.getPrimaryPrincipal();
//所有权限实体
List<Permission> permissions = iPermissionsService.selectPermission(account);
//url集合
List<String> permissionUrls = new ArrayList<>();
for(Permission permission : permissions){
permissionUrls.add(permission.getUrl);
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermissions(permissionUrls);
return info;
}
测试代码
/**
* 通过自定义Realm查询数据库读取权限
*/
@Test
public void testMyRealm2(){
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro/shiro-realm.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("admin", "111111");
subject.login(token);
System.out.println("认证状态:"+subject.isAuthenticated());
System.out.println(subject.isPermitted("user:create"));
System.out.println(subject.isPermittedAll("user:create", "items:add"));
}
测试结果
认证状态:true
true
true