本文共 3644 字,大约阅读时间需要 12 分钟。
首先需要写一个类
/** * 集成Shiro标签 */@Componentpublic class ShiroTagFreeMarkerConfigurer implements InitializingBean { @Autowired private Configuration configuration; @Autowired private FreeMarkerViewResolver resolver; @Override public void afterPropertiesSet() throws Exception { // 加上这句后,可以在页面上使用shiro标签 configuration.setSharedVariable("shiro", new ShiroTags()); // 加上这句后,可以在页面上用${context.contextPath}获取contextPath resolver.setRequestContextAttribute("context"); }}
然后在doGetAuthorizationInfo方法中获取我们想要验证的权限,将权限写入roleNames和PermissionNames中
@Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { logger.info("执行Shiro权限认证"); try { UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal(); if (user != null) { // 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission) SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); // 根据用户名id查询xxx权限 ListxxxList = xxxWSService.findxxxbyUserInfoId(user.getId()); Set roleNames = new HashSet (); Set permissionNames = new HashSet (); for (XXX xxx: xxxList) { permissionNames.add(Constants.SHIRO_AUTH_XXX + "_" + xxx.getxxxId().toString()); roleNames.add(Constants.SHIRO_AUTH_XXX + "_" + xxx.getxxxId().toString() + "_" + xxx.getXxxName().toString()); } // 将权限提供给info info.setStringPermissions(permissionNames); // 将角色名称提供给info info.setRoles(roleNames); info.addStringPermission(""); return info; } } catch (Exception e) { logger.error("执行Shiro权限认证异常!", e.getLocalizedMessage() ); e.printStackTrace(); return null; } // 返回null的话,就会导致任何用户访问被拦截的请求时,都会自动跳转到unauthorizedUrl指定的地址 return null; }
最后就可以在前端freemarker模板中使用shiro标签,有xxx角色的人员才可以看到"保存"按钮;
<@shiro.hasAnyRoles name="app_${xxx.id?c}_1,app_${xxx.id?c}_2">
转载地址:http://ditbi.baihongyu.com/