Example #1
0
 /**
  * 获取授权信息
  *
  * @param principals
  * @return
  */
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   if (!principals.isEmpty() && principals.fromRealm(getName()).size() > 0) {
     Object id = principals.fromRealm(getName()).iterator().next();
     if (id != null) {
       SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
       if (enableRoles && enablePerms) {
         Map<String, Collection<String>> rolesAndPerms = realmService.getUserRolesAndPerms(id);
         Collection<String> roles = rolesAndPerms.get(roles_in_map_key);
         Collection<String> perms = rolesAndPerms.get(perms_in_map_key);
         if (roles != null && !roles.isEmpty()) {
           info.addRoles(roles);
         }
         if (perms != null && !perms.isEmpty()) {
           info.addStringPermissions(perms);
         }
       } else if (enableRoles && !enablePerms) {
         Collection<String> perms = realmService.getPermissions(id);
         if (perms != null && !perms.isEmpty()) {
           info.addStringPermissions(perms);
         }
       } else if (enablePerms && !enableRoles) {
         Collection<String> roles = realmService.getRoles(id);
         if (roles != null && !roles.isEmpty()) {
           info.addRoles(roles);
         }
       }
       return info;
     } else {
       return null;
     }
   } else return null;
 }
Example #2
0
  /**
   * Retrieves the AuthorizationInfo for the given principals (the CAS previously authenticated user
   * : id + attributes).
   *
   * @param principals the primary identifying principals of the AuthorizationInfo that should be
   *     retrieved.
   * @return the AuthorizationInfo associated with this principals.
   */
  @Override
  @SuppressWarnings("unchecked")
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    // retrieve user information
    SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) principals;
    String userName = (String) principalCollection.getPrimaryPrincipal();
    User user = getUserRepository().getByName(userName);
    Set<String> roles = user.getRolesName();
    Set<String> permissions = user.getPermissions();

    List<Object> listPrincipals = principalCollection.asList();
    Map<String, String> attributes = (Map<String, String>) listPrincipals.get(1);
    // create simple authorization info
    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    // add default roles
    simpleAuthorizationInfo.addRoles(roles);
    // add default permissions
    simpleAuthorizationInfo.addStringPermissions(permissions);
    // get roles from attributes
    List<String> attributeNames = split(roleAttributeNames);
    for (String attributeName : attributeNames) {
      String value = attributes.get(attributeName);
      addRoles(simpleAuthorizationInfo, split(value));
    }
    // get permissions from attributes
    attributeNames = split(permissionAttributeNames);
    for (String attributeName : attributeNames) {
      String value = attributes.get(attributeName);
      addPermissions(simpleAuthorizationInfo, split(value));
    }
    return simpleAuthorizationInfo;
  }
  /**
   * 为当前登录的Subject授予角色和权限
   *
   * @see 经测试:本例中该方法的调用时机为需授权资源被访问时
   * @see 经测试:并且每次访问需授权资源时,只有第一次需要执行该方法,这表明本例中默认启用AuthorizationCache
   * @see 个人感觉若使用了Spring3.1开始提供的ConcurrentMapCache支持,则可灵活决定是否启用AuthorizationCache
   * @see 比如说这里从数据库获取权限信息时,先去访问Spring3.1提供的缓存,而不使用Shior提供的AuthorizationCache
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
    logger.info("------------开始 SecurityRealm doGetAuthorizationInfo----------");
    // String currentUsername = (String)super.getAvailablePrincipal(arg0);

    SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
    Subject currentUser = SecurityUtils.getSubject();
    Collection<String> con =
        (Collection) currentUser.getSession().getAttribute(IConstants.SHIRO_ROLE_INFO);
    for (String string : con) {
      // SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

      // System.out.println(string);
      simpleAuthorInfo.addStringPermission(string);
      // 需要访问需授权资源的时候调用该函数,且一个subject调用了该函数后,只要session还在有效期,再次访问需授权资源的时候
      // 就不需要再次执行该函数了。所以产生的问题就是如果权限改变了,但是原session还有效。需要用户重新手动的执行一次登录
    }

    return simpleAuthorInfo;
    //		/* if(null!=currentUsername && "001".equals(currentUsername)){
    //		      //添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色
    //		      simpleAuthorInfo.addRole("admin");
    //		      //添加权限
    //		      simpleAuthorInfo.addStringPermission("admin:manage111");
    //		      logger.info("已为用户["+currentUsername+"]赋予了[admin]角色和[admin:manage]权限");
    //		      return simpleAuthorInfo;
    //		 }*/
    //		// return null;
  }
Example #4
0
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   // 根据用户配置用户与权限
   if (principals == null) {
     throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
   }
   String name = (String) getAvailablePrincipal(principals);
   List<String> roles = new ArrayList<String>();
   List<String> per = new ArrayList<String>();
   // 简单默认一个用户与角色,实际项目应
   User user = userService.findByUserName(name);
   if (user.getUsername().equals(name)) {
     if (user.getRoleList().size() > 0) {
       for (int i = 0; i < user.getRoleList().size(); i++) {
         roles.add(user.getRoleList().get(i).getRole());
         for (int k = 0; k < user.getRoleList().get(i).getPermissionsList().size(); k++) {
           per.add(user.getRoleList().get(i).getPermissionsList().get(k).getPermission());
         }
       }
     }
   } else {
     throw new AuthorizationException();
   }
   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
   // 增加角色
   info.addRoles(roles);
   info.addStringPermissions(per);
   return info;
 }
Example #5
0
 /**
  * 为当前登录的Subject授予角色和权限
  *
  * @see 经测试:本例中该方法的调用时机为需授权资源被访问时
  * @see 经测试:并且每次访问需授权资源时都会执行该方法中的逻辑,这表明本例中默认并未启用AuthorizationCache
  * @see 个人感觉若使用了Spring3.1开始提供的ConcurrentMapCache支持,则可灵活决定是否启用AuthorizationCache
  * @see 比如说这里从数据库获取权限信息时,先去访问Spring3.1提供的缓存,而不使用Shior提供的AuthorizationCache
  */
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   // 获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()
   String currentUsername = (String) super.getAvailablePrincipal(principals);
   List<String> roles = new ArrayList<String>();
   List<String> permissions = new ArrayList<String>();
   // 从数据库中获取当前登录用户的详细信息
   User user = userService.getByAccount(currentUsername);
   if (null != user) {
     List<Role> roleList = userService.getRolesByUserId(user.getUserId());
     List<Permission> permissionList = userService.getPermissionsByUserId(user.getUserId());
     // 实体类User中包含有用户角色的实体类信息
     if (null != roleList && roleList.size() > 0) {
       // 获取当前登录用户的角色
       for (Role role : roleList) {
         roles.add(role.getName());
       }
       // 实体类Role中包含有角色权限的实体类信息
       for (Permission permission : permissionList) {
         permissions.add(permission.getDescription());
       }
     }
   } else {
     throw new AuthorizationException();
   }
   // 为当前用户设置角色和权限
   SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
   simpleAuthorInfo.addRoles(roles);
   simpleAuthorInfo.addStringPermissions(permissions);
   return simpleAuthorInfo;
 }
Example #6
0
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   String username = (String) principals.getPrimaryPrincipal();
   SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
   authorizationInfo.setRoles(userService.findRoles(username));
   authorizationInfo.setStringPermissions(userService.findPermissions(username));
   return authorizationInfo;
 }
Example #7
0
 /** 授权 */
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   logger.info("monitorRealm--授权");
   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
   info.addRole("role"); // 角色允许,
   info.addStringPermission("permission"); // 资源允许
   return info;
 }
Example #8
0
 /** 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. */
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
   User user = accountService.findUserByLoginName(shiroUser.loginName);
   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
   info.addRoles(user.getRoleList());
   return info;
 }
Example #9
0
 /** 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. */
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
   // 获取登录用户的信息
   User user = userService.findUserByLoginName(shiroUser.name);
   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
   // 添加用户所具有的权限信息
   info.addRoles(user.getRoleList());
   return info;
 }
Example #10
0
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals) {
   // only if authenticated with this realm too
   if (!principals.getRealmNames().contains(getName())) {
     return null;
   }
   // add the default role
   final SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
   authorizationInfo.addRole(kenaiRealmConfiguration.getConfiguration().getDefaultRole());
   return authorizationInfo;
 }
Example #11
0
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   // TODO Auto-generated method stub
   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
   if (principals.fromRealm("jianyu").iterator().hasNext()) {
     info.addRole("jianyu");
   } else if (principals.fromRealm("fayuan").iterator().hasNext()) {
     info.addRole("fayuan");
   }
   return info;
 }
  /** 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    logger.info("authorization: 授权回调函数 " + principals.getRealmNames());

    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

    simpleAuthorizationInfo.setRoles(Sets.newHashSet("student", "teacher"));
    simpleAuthorizationInfo.addStringPermissions(Lists.newArrayList("hello:index"));

    return simpleAuthorizationInfo;
  }
Example #13
0
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    CustomerLogin login =
        queryService.findCustomerLoginByLoginId(getAvailablePrincipal(principals));
    if (login == null) {
      return null;
    }

    SimpleAuthorizationInfo result = new SimpleAuthorizationInfo();
    result.addRole(CUSTOMERADMIN_ROLENAME);
    return result;
  }
Example #14
0
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    logger.info("doGetAuthorizationInfo(principals)...");

    /**
     * this function loads user authorization data from "userManager" data source (database) User,
     * Role are custom POJOs (beans) and are loaded from database. WildcardPermission implements
     * shiros Permission interface, so my permissions in database gets accepted by shiro security
     */
    Set<String> roles = new HashSet<String>();
    Set<Permission> permissions = new HashSet<Permission>();
    // Collection<User>	principalsList	= principals.byType(User.class);

    //		if (principalsList.isEmpty()) {
    //			throw new AuthorizationException("Empty principals list!");
    //		}
    //		//LOADING STUFF FOR PRINCIPAL
    //		for (User userPrincipal : principalsList) {
    //			try {
    //				this.userManager.beginTransaction();
    //
    //				User user = this.userManager.loadById(userPrincipal.getId());
    //
    //				Set<Role> userRoles	= user.getRoles();
    //				for (Role r : userRoles) {
    //					roles.add(r.getName());
    //					Set<WildcardPermission> userPermissions	= r.getPermissions();
    //					for (WildcardPermission permission : userPermissions) {
    //						if (!permissions.contains(permission)) {
    //							permissions.add(permission);
    //						}
    //					}
    //				}
    //				this.userManager.commitTransaction();
    //			} catch (InvalidDataException idEx) { //userManger exceptions
    //				throw new AuthorizationException(idEx);
    //			} catch (ResourceException rEx) {
    //				throw new AuthorizationException(rEx);
    //			}
    //		}

    // THIS IS THE MAIN CODE YOU NEED TO DO !!!!
    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(roles);
    authorizationInfo.setRoles(roles); // fill in roles
    authorizationInfo.setObjectPermissions(
        permissions); // add permisions (MUST IMPLEMENT SHIRO PERMISSION INTERFACE)

    return authorizationInfo;
  }
Example #15
0
 /** 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. */
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   Object principal = principals.getPrimaryPrincipal();
   SecurityUser<Long> user =
       (SecurityUser) principal; // userHessianService.findUserByPrincipal(principal);
   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
   if (user != null) {
     List<String> roles = userHessianService.getSecurityGroups(user.getId());
     List<String> auths = userHessianService.getSecurityPermissions(user.getId());
     if (null != roles && !roles.isEmpty()) info.addRoles(roles);
     if (null != auths && !auths.isEmpty()) info.addStringPermissions(auths);
   }
   return info;
 }
  // 载入角色和权限
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    String loginName = (String) principals.getPrimaryPrincipal();
    User user = adminUserDao.getByLoginName(loginName);

    Set<String> permissionSet = adminUserDao.getPermissions(user.getId());
    Set<String> roleSet = adminUserDao.getRoles(user.getId());

    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    authorizationInfo.setRoles(roleSet);
    authorizationInfo.setStringPermissions(permissionSet);

    return authorizationInfo;
  }
Example #17
0
 /** 授权-未授权的情况下调用 */
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
   User user = userService.findByUserName(shiroUser.loginName);
   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
   for (Role role : user.getRoleList()) {
     // 基于Role的权限信息
     info.addRole(role.getRoleName());
     // 基于Permission的权限信息
     info.addStringPermissions(role.getPermissions());
   }
   // log.info(info.getRoles().toString());
   return info;
 }
 /** 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用 */
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   Principal principal = (Principal) getAvailablePrincipal(principals);
   // 获取当前已登录的用户
   if (!Global.TRUE.equals(Global.getConfig("user.multiAccountLogin"))) {
     Collection<Session> sessions =
         getSystemService()
             .getSessionDao()
             .getActiveSessions(true, principal, UserUtils.getSession());
     if (sessions.size() > 0) {
       // 如果是登录进来的,则踢出已在线用户
       if (UserUtils.getSubject().isAuthenticated()) {
         for (Session session : sessions) {
           getSystemService().getSessionDao().delete(session);
         }
       }
       // 记住我进来的,并且当前用户已登录,则退出当前用户提示信息。
       else {
         UserUtils.getSubject().logout();
         throw new AuthenticationException("msg:账号已在其它地方登录,请重新登录。");
       }
     }
   }
   User user = getSystemService().getUserByLoginName(principal.getLoginName());
   if (user != null) {
     SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
     List<Menu> list = UserUtils.getMenuList();
     for (Menu menu : list) {
       if (StringUtils.isNotBlank(menu.getPermission())) {
         // 添加基于Permission的权限信息
         for (String permission : StringUtils.split(menu.getPermission(), ",")) {
           info.addStringPermission(permission);
         }
       }
     }
     // 添加用户权限
     info.addStringPermission("user");
     // 添加用户角色信息
     for (Role role : user.getRoleList()) {
       info.addRole(role.getEnname());
     }
     // 更新登录IP和时间
     getSystemService().updateUserLoginInfo(user);
     // 记录登录日志
     LogUtils.saveLog(Servlets.getRequest(), "系统登录");
     return info;
   } else {
     return null;
   }
 }
Example #19
0
 /** 授权 */
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   String username = (String) principals.getPrimaryPrincipal();
   CmsUser user = cmsUserMng.findByUsername(username);
   CmsSite site = CmsThreadVariable.getSite();
   SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
   if (user != null) {
     Set<String> viewPermissionSet = new HashSet<String>();
     Set<String> perms = user.getPerms(site.getId(), viewPermissionSet);
     if (!CollectionUtils.isEmpty(perms)) {
       // 权限加入AuthorizationInfo认证对象
       auth.setStringPermissions(perms);
     }
   }
   return auth;
 }
Example #20
0
  /** Builds the permission list for a give user. */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    SimpleAuthorizationInfo authz = new SimpleAuthorizationInfo();

    // Only give 'log' permission to 'user1'
    if (principals.getPrimaryPrincipal().equals("user1")) {
      authz.addObjectPermission(new DomainPermission("log"));
      authz.addStringPermission("encoder:*:config:specialKey");
    }

    if (principals.getPrimaryPrincipal().equals("user2")) {
      authz.addStringPermission("encoder:dave:config:*");
    }

    return authz;
  }
Example #21
0
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    // make sure the user is jcool, (its just for testing)

    if (principals.asList().get(0).toString().equals("jcool")) {
      SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

      info.addRole("test-role1");
      info.addRole("test-role2");

      info.addStringPermission("test:*");

      return info;
    }

    return null;
  }
Example #22
0
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   try {
     Role role = roleFacade().findByName("Public");
     SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
     info.addRole("Public");
     for (Permission p : role.getPermissions()) {
       JpaRealm.addPermissions(info, p);
     }
     return info;
   } catch (EJBException e) {
     return null;
   } catch (NamingException ex) {
     logger.error("Unable to find RoleFacade EJB", ex);
     return null;
   }
 }
Example #23
0
    @Override
    @SuppressWarnings("unchecked")
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
      logger.trace("resolve authorization info");
      // retrieve user information
      SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) principals;
      List<Object> listPrincipals = principalCollection.asList();
      Map<String, String> attributes = (Map<String, String>) listPrincipals.get(1);
      // create simple authorization info
      SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
      // add default roles
      addRoles(simpleAuthorizationInfo, split(getDefaultRoles()));
      // add default permissions
      addPermissions(simpleAuthorizationInfo, split(getDefaultPermissions()));
      // get roles from attributes
      List<String> attributeNames = split(getRoleAttributeNames());
      for (String attributeName : attributeNames) {
        final Object value = attributes.get(attributeName);
        if (value instanceof Collection<?>) {
          for (final Object valueEntry : (Collection<?>) value) {
            addRoles(simpleAuthorizationInfo, split((String) valueEntry));
          }
        } else {
          addRoles(simpleAuthorizationInfo, split((String) value));
        }
      }
      // get permissions from attributes
      attributeNames = split(getPermissionAttributeNames());
      for (String attributeName : attributeNames) {
        final Object value = attributes.get(attributeName);
        if (value instanceof Collection<?>) {
          for (final Object valueEntry : (Collection<?>) value) {
            addPermissions(simpleAuthorizationInfo, split((String) valueEntry));
          }
        } else {
          addPermissions(simpleAuthorizationInfo, split((String) value));
        }
      }

      if (simpleAuthorizationInfo.getRoles() != null
          && simpleAuthorizationInfo.getRoles().contains(configuration.getAdministratorRole())) {
        simpleAuthorizationInfo.addRole(Roles.ADMINISTRATOR);
      }

      return simpleAuthorizationInfo;
    }
Example #24
0
 /*
  *获取了当前登录用户的角色信息。
  *
  * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
  */
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   if (principals == null) {
     throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
   }
   /*User user = (User)principals.fromRealm(getName()).iterator().next();*/
   String name = (String) getAvailablePrincipal(principals);
   Set<String> roles = new HashSet<String>();
   User user = userService.findUserByNameAndPassword(name, "", 1);
   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
   List<UserRoleOrgRelation> relations = user.getUserRoleOrgRelations();
   for (UserRoleOrgRelation relation : relations) {
     roles.add(String.valueOf(relation.getRole().getId()));
   }
   info.addRoles(roles);
   return info;
 }
Example #25
0
  /**
   * Retrieves the AuthorizationInfo for the given principals from the underlying data store. When
   * returning an instance from this method, you might want to consider using an instance of
   * SimpleAuthorizationInfo, as it is suitable in most cases.
   *
   * @param principals the primary identifying principals of the AuthorizationInfo that should be
   *     retrieved.
   * @return the AuthorizationInfo associated with this principals.
   */
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    if (_logger.isDebugEnabled()) {
      _logger.debug("call doGetAuthorizationInfo..");
    }
    String username = (String) principals.getPrimaryPrincipal();
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

    Set<String> roles = new HashSet<String>();
    if ("camry".equals(username)) {
      roles.add("admin");
    }
    info.setRoles(roles); // userService.findRoles(username);

    Set<String> permissions = new HashSet<String>();
    info.setStringPermissions(permissions); // userService.findRoles(username);

    return info;
  }
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    // Long userId = (Long)
    // principals.fromRealm(getName()).iterator().next();
    // Useraccount user = userAccountService.getUserAccount(userId);
    Object u = principals.iterator().next();
    Useraccount user = null;
    if (u instanceof Useraccount) {
      // re-retrieve the useraccount instance as the one enclosed in
      // principal
      // does not carry roles in it
      logger.info("user is a user");
      int userid = ((Useraccount) u).getId();
      user = userAccountService.getUserAccount(userid);
    } else {
      logger.info("user is not user");
    }

    if (user != null) {
      SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
      // FIXME add roles
      // for (Role role : user.getRoles()) {
      // info.addRole(role.getName());
      // info.addStringPermissions(role.getPermissions());
      // }
      List<Userrole> roles = user.getRoles();
      logger.info("id:" + user.getId());
      logger.info("uname:" + user.getUsername());
      logger.info("email:" + user.getEmail());
      if (roles == null) {
        logger.info("roles is null");
      } else if (roles.size() == 0) {
        logger.info("has no roles");
      } else {
        for (Userrole role : roles) {
          logger.info("role:" + role.getRolename());
          info.addRole(role.getRolename());
          // info.addStringPermissions(role.getPermissions());
        }
      }
      return info;
    } else {
      return null;
    }
  }
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    LOG.debug("Retrieving authorization information for {}", principals);
    final SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    final User user = userService.load(principals.getPrimaryPrincipal().toString());

    final List<String> permissions;
    if (null == user) {
      permissions = Collections.emptyList();
    } else {
      permissions = user.getPermissions();

      if (permissions != null) {
        info.setStringPermissions(Sets.newHashSet(permissions));
      }
    }

    LOG.debug("User {} has permissions: {}", principals, permissions);
    return info;
  }
Example #28
0
 /** 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. */
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   System.out.println("=========================doGetAuthorizationInfo");
   ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
   ShiroUser user = shiroUserService.findUserByLoginName(shiroUser.getUsername());
   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
   List<ShiroRole> roles = user.getRoleList(); // 用户角色
   List<ShiroPermission> permissions = user.getPermissionList(); // 用户权限
   if (roles != null) {
     for (ShiroRole role : roles) {
       // 基于Role的权限信息
       info.addRole(role.getRoleName());
       // 基于角色Permission的权限信息
       List<ShiroPermission> rolePermissions = role.getPermissionList();
       if (rolePermissions != null) {
         for (ShiroPermission permission : rolePermissions) {
           info.addStringPermission(permission.getPermissionName());
         }
       }
     }
   }
   if (permissions != null) {
     for (ShiroPermission permission : permissions) {
       // 基于用户Permission的权限信息
       info.addStringPermission(permission.getPermissionName());
     }
   }
   // TODO:删除,测试用代码
   info.addRole("root");
   info.addStringPermission("user:edit");
   info.addStringPermission("user:list");
   return info;
 }
Example #29
0
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    if (principals == null) {
      throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }
    try {
      User user = (User) getAvailablePrincipal(principals);
      Connection conn = null;
      Set<String> roleNames = null;
      Set<String> permissions = null;
      try {
        conn = dataSource.getConnection();

        // Retrieve roles and permissions from database
        roleNames = getRoleNamesForUser(conn, user.getId());
        if (permissionsLookupEnabled) {
          permissions = getPermissions(conn, user.getId(), roleNames);
        }

      } catch (SQLException e) {
        final String message =
            "There was a SQL error while authorizing user [" + user.getId() + "]";
        if (logger.isErrorEnabled()) {
          logger.error(message, e);
        }

        // Rethrow any SQL errors as an authorization exception
        throw new AuthorizationException(message, e);
      } finally {
        JdbcUtils.closeConnection(conn);
      }

      SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
      info.setStringPermissions(permissions);
      return info;
    } catch (Exception ex) {
      logger.error("Unable to get authorization info");
    }
    return null;
  }
Example #30
0
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    Set<String> roles = new HashSet<String>();
    Set<Permission> permissions = new HashSet<Permission>();
    Collection<User> principalsList = principals.byType(User.class);

    for (User userPrincipal : principalsList) {
      try {
        User user = userDAO.getById(userPrincipal.getId());
        Set<Role> userRoles = user.getRoles();
        for (Role role : userRoles) {
          roles.add(role.getRole());
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
    info.setRoles(roles);
    info.setObjectPermissions(permissions);

    return info;
  }