Shiro 授权:
参考链接:http://jinnianshilongnian.iteye.com/blog/2020017
授权,也称访问控制,即在应用中控制用户可以访问哪些资源(访问页面/页面操作/编辑数据等)
roles:角色,代表操作集合,可以理解为权限的集合(隐式角色)
perms:权限(显示角色)
三种设置权限方式:
1 编程式:
Subject subject = SecurityUtils.getSubject(); if(subject.hasRole(“admin”)) { //有权限 } else { //无权限 }
2 注解式:
@RequestMapping("/list") @ResponseBody @RequiresPermissions({"sys:menu:list"}) public DataGridResult getPage(@RequestParam Map<String, Object> params) { Query query = new Query(params); return sysMenuService.getPageList(query); }
3 标签式:
<shiro:hasPermission name="sys:user:create"> <a href="form?add" class="btn btn-success " type="button"> <i class="fa fa-plus"></i> <span class="bold">新增</span> </a> </shiro:hasPermission>
两种授权方式:
1.1 基于角色授权:
[users] draco = 615, role1, role3 harry = 130, role2
1.2 基于权限授权:
[users]
draco = 615, role1, role3
harry = 130, role2
[roles]
role1 = sys:user,sys:menu
role2 = sys:user:create,sys:user:update,sys:user:list
role3 = sys:config:list
2 编程式授权
//分配权限 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //为用户分配角色: List<String> roles = Arrays.asList("admin", "user"); info.addRoles(roles); //为用户分配资源: List<String> perms = Arrays.asList("sys:role:list", "sys:role:info", "sys:user:save"); info.addStringPermissions(perms);
验证权限:
boolean authenticated = currentUser.isAuthenticated(); log.debug("是否登陆成功:"+ authenticated); //授权 if(authenticated){ //授权:角色 //单个角色的判断 boolean isHasRole = currentUser.hasRole("role1"); System.out.println(isHasRole); //多个角色判断:逐个判断 boolean[] isHasRoles = currentUser.hasRoles(Arrays.asList("role1", "role2")); for(int i = 0; i< isHasRoles.length; i++){ System.out.print(isHasRoles[i]+"\t"); } //多个角色判断:总体判断 System.out.println(); boolean isHasAllRoles = currentUser.hasAllRoles(Arrays.asList("role1", "role2")); System.out.println(isHasAllRoles); //check方法:抛出异常 try { currentUser.checkRole("role3"); } catch (AuthorizationException e) { System.out.println("你没有被分配这个角色"); e.printStackTrace(); } //授权:权限 //单个授权的判断 boolean isPermitted = currentUser.isPermitted("sys:user"); System.out.println(isPermitted); //多个权限判断 boolean isPermittedAll = currentUser.isPermittedAll("sys:user", "sys:menu"); System.out.println(isPermittedAll); //check方法 try { currentUser.checkPermission("sys:config:list"); } catch (AuthorizationException e) { System.out.println("你没有被分配这个权限"); e.printStackTrace(); } }
授权流程:
1 调用subject.isPermitted()进行验证,自动委托给SecurityManager
2 SecurityManger将身份验证委托给Authorizer
3 Authorizer负责真正的授权者,是Shiro API中授权核心的入口点
4 Authorizer在进行授权之前,会调用相应的Realm获取Subject相应的角色/权限用于匹配传入的角色/权限
5 Authorizer会判断Realm的角色/权限是否和传入的匹配,如果有多个Realm,会委托给ModularRealmAuthorizer进行循环判断,如果匹配如isPermitted*/hasRole*会返回true,否则返回false表示授权失败