shiro-realm.ini
[main]#自定义RealmmyRealm=test.shiro.MyRealm#将myRealm设置到securityManager,相当于Spring中的注入securityManager.realms=$myRealm
MyRealm.java
/** * 授权 * @param principals * @return */@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String account = (String) principals.getPrimaryPrincipal(); //所有权限实体 Listpermissions = iPermissionsService.selectPermission(account); //url集合 List permissionUrls = new ArrayList<>(); for(Permission permission : permissions){ permissionUrls.add(permission.getUrl); } SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.addStringPermissions(permissionUrls); return info;}
测试代码
/** * 通过自定义Realm查询数据库读取权限 */@Testpublic void testMyRealm2(){ Factoryfactory = 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"));}
测试结果
认证状态:truetruetrue