Shiro入门学习之shi.ini实现授权(三)
一、Shiro授权
前提:需要认证通过才会有授权一说
1、授权过程
2、相关方法说明
①subject.hasRole("role1"):判断是否有该角色
②subject.hasRoles(List):分别判断该角色是否具有该List的每个内容
③subject.hasAllRoles(Collection):返回boolean,要求参数中所有角色都需要具有
④subject.isPermitted(""):判断是否有该权限
二、shiro.ini实现授权
1、新建module,添加如下pom依赖
<properties> <shiro.version>1.4.1</shiro.version> <loggingg.version>1.2</loggingg.version> </properties> <dependencies> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>${loggingg.version}</version> </dependency> </dependencies>
2、shiro.ini添加配置
3、test类
public class TestAuthorization { public static void main(String[] args) { //1.模拟前台传递的用户名和密码 String username = "zhangsan"; String password = "123456"; //2.创建安全管理器的工厂 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); //3.通过安全管理器工厂获取安全管理器 SecurityManager securityManager = factory.getInstance(); //4.将安全管理器绑定到当前运行环境 SecurityUtils.setSecurityManager(securityManager); //5.从当前环境中获取Subject主体 Subject subject1 = SecurityUtils.getSubject(); //6.调用主体的登录方法 try { subject1.login(new UsernamePasswordToken(username,password)); System.out.println("登录成功!"); } catch (IncorrectCredentialsException e) { System.out.println("密码不正确"); }catch (UnknownAccountException e) { System.out.println("用户名不存在"); } //角色判断 boolean role2 = subject1.hasRole("role2"); System.out.println("是否有role2的角色:"+role2); //分别判断集合中元素,返回boolean数组 boolean[] booleans = subject1.hasRoles(Arrays.asList("role1", "role2", "role3")); for (boolean aBoolean : booleans) { System.out.println(aBoolean); } //判断当前用户是否有集合中所有角色 boolean b = subject1.hasAllRoles(Arrays.asList("role1", "role2", "role3")); System.out.println(b); //判断权限 boolean permitted = subject1.isPermitted("user:query"); System.out.println("判断当前用户是否有user:query的权限:"+permitted); boolean[] permitted1 = subject1.isPermitted("user:query", "user:add", "user:delete"); for (boolean b1 : permitted1) { System.out.println(b1); } boolean permittedAll = subject1.isPermittedAll("user:query", "user:add", "user:delete"); System.out.println(permittedAll); } }
这样就实现shiro.ini授权,接下来通过shiro.ini实现自定义realm:Shiro入门学习之自定义Realm(四)