Java Code Examples for org.apache.shiro.subject.PrincipalCollection

The following are top voted examples for showing how to use org.apache.shiro.subject.PrincipalCollection. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: SSMShiro   File: ShiroDemoRealm.java   View source code 8 votes vote down vote up
/**
 * 完成授权
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
		PrincipalCollection principals) {
	//得到认证成功之后凭证的身份信息
	String username=((User) principals.getPrimaryPrincipal()).getUsername();
	//查询数据库得到所有的权限列表
	List<String> permissionList=new ArrayList<String>();
	UserCustom userCustom = customMapper.findUserCustomByUsername(username);
	Set<RoleCustom> roles=userCustom.getRoleSet();
	for(RoleCustom role:roles){
		Set<Permission> permissionSet = role.getPermissionSet();
		for (Permission permission:permissionSet) {
			permissionList.add(permission.getPname());
		}
	}
	SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
	authorizationInfo.addStringPermissions(permissionList);
	return authorizationInfo;
}
 
Example 2
Project: ShiroDemo   File: ShiroDemoRealm.java   View source code 8 votes vote down vote up
/**
 * 完成授权
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
		PrincipalCollection principals) {
	//得到认证成功之后凭证的身份信息
	String username=(String) principals.getPrimaryPrincipal();
	//查询数据库得到所有的权限列表
	List<String> permissionList=new ArrayList<String>();
	UserCustomMapper mapper=getUserCustomMapper();
	UserCustom userCustom = mapper.findUserCustomByUsername(username);
	Set<RoleCustom> roles=userCustom.getRoleSet();
	for(RoleCustom role:roles){
		Set<Permission> permissionSet = role.getPermissionSet();
		for (Permission permission:permissionSet) {
			permissionList.add(permission.getPname());
		}
	}
	SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
	authorizationInfo.addStringPermissions(permissionList);
	return authorizationInfo;
}
 
Example 3
Project: admin-shiro   File: AdminShiroRealm.java   View source code 7 votes vote down vote up
/**
 * 此方法调用  hasRole,hasPermission的时候才会进行回调.
 *
 * 权限信息.(授权):
 * 1、如果用户正常退出,缓存自动清空;
 * 2、如果用户非正常退出,缓存自动清空;
 * 3、如果我们修改了用户的权限,而用户不退出系统,修改的权限无法立即生效。
 * (需要手动编程进行实现;放在service进行调用)
 * 在权限修改后调用realm中的方法,realm已经由spring管理,所以从spring中获取realm实例,
 * 调用clearCached方法;
 * :Authorization 是授权访问控制,用于对用户进行的操作授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等。
 * @param principals
 * @return
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) throws AuthenticationException{
   /*
    * 当没有使用缓存的时候,不断刷新页面的话,这个代码会不断执行,
    * 当其实没有必要每次都重新设置权限信息,所以我们需要放到缓存中进行管理;
    * 当放到缓存中时,这样的话,doGetAuthorizationInfo就只会执行一次了,
    * 缓存过期之后会再次执行。
    */
    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    AdminDO userInfo  = (AdminDO)principals.getPrimaryPrincipal();
    Set<String> set = new HashSet<String>();
    set.add(userInfo.getRole().getRoleId());
    authorizationInfo.setRoles(set);

    Set<String> menus = roleMenuService.getMenuCodesByRoleId(userInfo.getRole().getRoleId());
    authorizationInfo.addStringPermissions(menus);

    return authorizationInfo;
}
 
Example 4
Project: jeeWe   File: UserRealm.java   View source code 7 votes vote down vote up
@SuppressWarnings("rawtypes")
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	String username = (String) principals.getPrimaryPrincipal();
	SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
	// 根据用户名查询当前用户拥有的角色
	List<Map> roles = userService.findRolesByUserName(username);
	Set<String> roleNames = new HashSet<String>();
	for (Map role : roles) {
		roleNames.add(role.get("name").toString());
	}
	// 将角色名称提供给info
	authorizationInfo.setRoles(roleNames);
	// 根据用户名查询当前用户权限
	List<Map> permissions = userService.findPermissionsByUserName(username);
	Set<String> permissionNames = new HashSet<String>();
	for (Map permission : permissions) {
		permissionNames.add(permission.get("name").toString());
	}
	// 将权限名称提供给info
	authorizationInfo.setStringPermissions(permissionNames);

	return authorizationInfo;
}
 
Example 5
Project: SpringBootLayIM   File: AuthRealm.java   View source code 6 votes vote down vote up
/**
 * 暂时先不做权限,只做有没有登录
 * */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    /*
    *  User user=(User) principal.fromRealm(this.getClass().getName()).iterator().next();//获取session中的用户
    List<String> permissions=new ArrayList<>();
    Set<Role> roles = user.getRoles();
    if(roles.size()>0) {
        for(Role role : roles) {
            Set<Module> modules = role.getModules();
            if(modules.size()>0) {
                for(Module module : modules) {
                    permissions.add(module.getMname());
                }
            }
        }
    }
    SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
    info.addStringPermissions(permissions);//将权限放入shiro中.
    return info;
    * */
    return null;
}
 
Example 6
Project: kettle_support_kettle8.0   File: Authorizing2Realm.java   View source code 6 votes vote down vote up
/**
 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
		PrincipalCollection principalCollection) {
	if (principalCollection == null) {
		throw new AuthorizationException("Principal is not null!");
	}
	Shiro shiro = (Shiro) principalCollection.getPrimaryPrincipal();
	User entity = new User();
	entity.setId(shiro.getId());
	entity = (User) service.iUserService.select(entity);
	if (null == entity) {
		throw new UnknownAccountException("No account found for user ["
				+ shiro.getId() + "]");
	}
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	return info;
}
 
Example 7
Project: stateless-shiro   File: BearerAuthenticationInfo.java   View source code 6 votes vote down vote up
@Override
public PrincipalCollection getPrincipals() {
    RealmSecurityManager manager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
    SimplePrincipalCollection ret = new SimplePrincipalCollection();
    for (Realm realm : manager.getRealms()) {
        /*
        if (realm instanceof ProfileRealm) {
            String email = token.getEmail();
            if (((ProfileRealm) realm).accountExists(email)) {
                ret.add(email, realm.getName());
            }
        }
        */
    }
    ret.add(token.getEmail(), bearerTokenAuthenticatingRealm.getName());
    return ret;
}
 
Example 8
Project: automat   File: Realm.java   View source code 6 votes vote down vote up
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	Long userId = (Long) WebUtil.getCurrentUser();
	Parameter parameter = new Parameter("sysAuthorizeService", "queryPermissionByUserId").setId(userId);
	logger.info("{} execute queryPermissionByUserId start...", parameter.getNo());
	List<?> list = provider.execute(parameter).getList();
	logger.info("{} execute queryPermissionByUserId end.", parameter.getNo());
	for (Object permission : list) {
		if (StringUtils.isNotBlank((String) permission)) {
			// 添加基于Permission的权限信息
			info.addStringPermission((String) permission);
		}
	}
	// 添加用户权限
	info.addStringPermission("user");
	return info;
}
 
Example 9
Project: automat   File: Realm.java   View source code 6 votes vote down vote up
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	Long userId = (Long) WebUtil.getCurrentUser();
	Parameter parameter = new Parameter("sysAuthorizeService", "queryPermissionByUserId").setId(userId);
	logger.info("{} execute queryPermissionByUserId start...", parameter.getNo());
	List<?> list = provider.execute(parameter).getList();
	logger.info("{} execute queryPermissionByUserId end.", parameter.getNo());
	for (Object permission : list) {
		if (StringUtils.isNotBlank((String) permission)) {
			// 添加基于Permission的权限信息
			info.addStringPermission((String) permission);
		}
	}
	// 添加用户权限
	info.addStringPermission("user");
	return info;
}
 
Example 10
Project: automat   File: Realm.java   View source code 6 votes vote down vote up
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	Long userId = (Long) WebUtil.getCurrentUser();
	Parameter parameter = new Parameter("sysAuthorizeService", "queryPermissionByUserId").setId(userId);
	logger.info("{} execute queryPermissionByUserId start...", parameter.getNo());
	List<?> list = provider.execute(parameter).getList();
	logger.info("{} execute queryPermissionByUserId end.", parameter.getNo());
	for (Object permission : list) {
		if (StringUtils.isNotBlank((String) permission)) {
			// 添加基于Permission的权限信息
			info.addStringPermission((String) permission);
		}
	}
	// 添加用户权限
	info.addStringPermission("user");
	return info;
}
 
Example 11
Project: spring_mybatis_shiro   File: UserAuthorizingRealm.java   View source code 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	// 配置用户权限
	Principal principal = (Principal) principals.fromRealm(getName()).iterator().next();
	if (principal != null) {
		// 推荐将权限标识加入缓存,然后从缓存获取权限标识集合,并添加给SimpleAuthorizationInfo,避免频繁访问数据库获取资源
		// 如:List<String> permissions = redisService.findUserPermissions(userId);
		// 权限标识与applicationContext-shiro.xml配置的filterChainDefinitionsperms中类似["admin:userModule"]
		// 以下示例
		List<String> permissions = new ArrayList<String>();
		permissions.add("admin:userModule");// 赋予这个标识才有权限访问/user/findPage.html
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.addStringPermissions(permissions);
		return authorizationInfo;

	}
	return null;
}
 
Example 12
Project: mumu   File: UserRealm.java   View source code 6 votes vote down vote up
/**
 * 获取当前用户的角色集合,权限集合
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
	//获取保存在session中的用户信息
	SysUser user = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SysUser.SYS_USER);
	if (user == null) {
		throw new IllegalArgumentException();
	}
	//获取当前用户拥有的所有角色
	List<SysRole> roles = roleService.getSysRoleByUserId(user.getUserId().toString(), PublicEnum.NORMAL.value());
	for (SysRole sysRole : roles) {
		authorizationInfo.addRole(sysRole.getRoleCode());
	}
	//获取当前用户拥有的所有权限
	List<SysPermission> permissions = permissionService.getSysPermissionByUserId(user.getUserId(), PublicEnum.NORMAL.value());
	for (SysPermission sysPermission : permissions) {
		authorizationInfo.addStringPermission(sysPermission.getPermission());
	}
	System.out.println("用户权限:"+ JSON.toJSONString(authorizationInfo));
	return authorizationInfo;
}
 
Example 13
Project: oauth2-shiro-redis   File: RedisRealm.java   View source code 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    final String username = getUsername(principals);

    List<Roles> roles = usersRepository.findRolesByUsername(username);
    LOG.debug("Load Roles[{}] by username: {}", roles, username);

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

    for (Roles role : roles) {
        info.addRole(role.roleName());
        for (RolesPermissions permissions : role.permissions()) {
            info.addStringPermission(permissions.permission());
        }
    }

    return info;
}
 
Example 14
Project: SpringBootShiro   File: AuthRealm.java   View source code 6 votes vote down vote up
/**
 * 完成授权
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
        PrincipalCollection principals) {
    //得到认证成功之后凭证的身份信息
    String username=((User) principals.getPrimaryPrincipal()).getUsername();
    //查询数据库得到所有的权限列表
    List<String> permissionList=new ArrayList<String>();
    List<String> roleList=new ArrayList<>();
    UserCustom userCustom = customMapper.findUserCustomByUsername(username);
    Set<RoleCustom> roles=userCustom.getRoleSet();
    for(RoleCustom role:roles){
        roleList.add(role.getRname());
        Set<Permission> permissionSet = role.getPermissionSet();
        for (Permission permission:permissionSet) {
            permissionList.add(permission.getPname());
        }
    }
    SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
    authorizationInfo.addStringPermissions(permissionList);
    authorizationInfo.addRoles(roleList);
    return authorizationInfo;
}
 
Example 15
Project: Spring-Shiro-Spark   File: ShiroRealm.java   View source code 6 votes vote down vote up
@Override
//@org.springframework.transaction.annotation.Transactional
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    //获取当前用户
    //UserDto user = convertToDto(userDao.findUserByUsername((String)principalCollection.getPrimaryPrincipal()));
    //User currentUser = userDao.findUserByUsername((String)principalCollection.getPrimaryPrincipal());
    UserDto user = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("user");

    //把principals放session中,key=userId value=principals
    SecurityUtils.getSubject().getSession().setAttribute(String.valueOf(user.getId()),SecurityUtils.getSubject().getPrincipals());

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    //赋予角色
    for(RoleDto role:user.getRoles()){
        info.addRole(role.getName());
    }
    //赋予权限
    for(PermissionDto permission:user.getPermissions()){
        //System.out.println(permission.getName());
        info.addStringPermission(permission.getName());
    }
    return info;
}
 
Example 16
Project: stateless-shiro   File: BearerTokenAuthenticatingRealm.java   View source code 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
	Preconditions.checkNotNull(principalCollection, "You can't have a null collection of principals. No really, how did you do that");
	String userEmail = (String) getAvailablePrincipal(principalCollection);
	if (userEmail == null) {
		throw new NullPointerException("Can't find a principal in the collection");
	}
	LOGGER.debug("Finding authorization info for " + userEmail + " in DB");

	final User user = userRepository.findByEmailAndActive(userEmail, true);

	LOGGER.debug("Found " + userEmail + " in DB");

	final int totalRoles = user.getRoles().size();
	final Set<String> roleNames = new LinkedHashSet<>(totalRoles);
	final Set<String> permissionNames = new LinkedHashSet<>();
	if (totalRoles > 0) {
		for (Role role : user.getRoles()) {
			roleNames.add(role.getName());
			for (Permission permission : role.getPermissions()) {
				permissionNames.add(permission.getName());
			}
		}
	}

	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	info.addRoles(roleNames);
	info.addStringPermissions(permissionNames);
	return info;
}
 
Example 17
Project: gitplex-mit   File: GitPlexAuthorizingRealm.java   View source code 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	return new AuthorizationInfo() {
		
		private static final long serialVersionUID = 1L;

		@Override
		public Collection<String> getStringPermissions() {
			return new HashSet<>();
		}
		
		@Override
		public Collection<String> getRoles() {
			return new HashSet<>();
		}
		
		@Override
		public Collection<Permission> getObjectPermissions() {
			return getObjectPermissionsInSession((Long) principals.getPrimaryPrincipal());
		}
	};
}
 
Example 18
Project: JAVA-   File: Realm.java   View source code 6 votes vote down vote up
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	Long userId = (Long) WebUtil.getCurrentUser();
	Parameter parameter = new Parameter("sysAuthorizeService", "queryPermissionByUserId").setId(userId);
	logger.info("{} execute queryPermissionByUserId start...", parameter.getNo());
	List<?> list = provider.execute(parameter).getList();
	logger.info("{} execute queryPermissionByUserId end.", parameter.getNo());
	for (Object permission : list) {
		if (StringUtils.isNotBlank((String) permission)) {
			// 添加基于Permission的权限信息
			info.addStringPermission((String) permission);
		}
	}
	// 添加用户权限
	info.addStringPermission("user");
	return info;
}
 
Example 19
Project: JAVA-   File: Realm.java   View source code 6 votes vote down vote up
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	Long userId = (Long) WebUtil.getCurrentUser();
	Parameter parameter = new Parameter("sysAuthorizeService", "queryPermissionByUserId").setId(userId);
	logger.info("{} execute queryPermissionByUserId start...", parameter.getNo());
	List<?> list = provider.execute(parameter).getList();
	logger.info("{} execute queryPermissionByUserId end.", parameter.getNo());
	for (Object permission : list) {
		if (StringUtils.isNotBlank((String) permission)) {
			// 添加基于Permission的权限信息
			info.addStringPermission((String) permission);
		}
	}
	// 添加用户权限
	info.addStringPermission("user");
	return info;
}
 
Example 20
Project: weibo   File: SampleRealm.java   View source code 6 votes vote down vote up
/** 
   * 授权 
   */  
  @Override  
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  	
  	//Long userId = TokenManager.getUserId();
  	User token = (User)SecurityUtils.getSubject().getPrincipal();
  	
SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
//根据用户ID查询角色(role),放入到Authorization里。
Set<String> roleName = roleService.findRoleNameByUserId(String.valueOf(token.getUuid()));
info.setRoles(roleName);
//根据用户ID查询权限(permission),放入到Authorization里。
Set<String> permissions = permissionService.findPermissionByUserId(String.valueOf(token.getUuid()));
info.setStringPermissions(permissions);
      return info;  
  }
 
Example 21
Project: springboot-shiro-cas-mybatis   File: IndexController.java   View source code 5 votes vote down vote up
@RequiresPermissions(value = { "user:edit" })
    @GetMapping("/user/{id}")
    public Object user(@PathVariable(value = "id") String id,HttpServletRequest request) {
    	   Subject subject = SecurityUtils.getSubject();
    	   //gonson解析
    	   PrincipalCollection att = subject.getPrincipals();
    	   LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>> {}",att);
//    	   JSONArray ja = JSON.parseArray(subject.getPrincipals().toString());
//    	   LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>> {}",ja);
    	   

        return SecurityUtils.getSubject().getPrincipals();
    }
 
Example 22
Project: framework   File: CacheSessionDAO.java   View source code 5 votes vote down vote up
/**
 * 获取活动会话
 *
 * @param includeLeave  是否包括离线(最后访问时间大于3分钟为离线会话)
 * @param principal     根据登录者对象获取活动会话
 * @param filterSession 不为空,则过滤掉(不包含)这个会话。
 * @return
 */
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
	// 如果包括离线,并无登录者条件。
	if (includeLeave && principal == null) {
		return getActiveSessions();
	}
	Set<Session> sessions = Sets.newHashSet();
	for (Session session : getActiveSessions()) {
		boolean isActiveSession = false;
		// 不包括离线并符合最后访问时间小于等于3分钟条件。
		if (includeLeave || DateUtils.pastMinutes(session.getLastAccessTime()) <= 3) {
			isActiveSession = true;
		}
		// 符合登陆者条件。
		if (principal != null) {
			PrincipalCollection pc = (PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
			if (principal.toString().equals(pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY)) {
				isActiveSession = true;
			}
		}
		// 过滤掉的SESSION
		if (filterSession != null && filterSession.getId().equals(session.getId())) {
			isActiveSession = false;
		}
		if (isActiveSession) {
			sessions.add(session);
		}
	}
	return sessions;
}
 
Example 23
Project: eagle-oj-api   File: Realm.java   View source code 5 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    UserSession session = SessionHelper.get();
    if (session==null) {
        return null;
    }

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    info.addRole(String.valueOf(session.getRole()));
    info.addStringPermissions(session.getPermission());
    return info;
}
 
Example 24
Project: JavaQuarkBBS   File: MyShiroRealm.java   View source code 5 votes vote down vote up
/**
 * 授权
 * @param principalCollection
 * @return
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    Integer id = (Integer) principalCollection.getPrimaryPrincipal();
    List<Permission> permissionList = permissionService.loadUserPermission(id);
    // 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

    permissionList.forEach(p->info.addStringPermission(p.getPerurl()));
    return info;
}
 
Example 25
Project: LazyAdmin   File: UserRealm.java   View source code 5 votes vote down vote up
/**
 * 对用户权限进行判定
 *
 * @param principals
 * @return
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    String username = (String) principals.getPrimaryPrincipal();
    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    authorizationInfo.setRoles(adminService.findRoles(username));
    authorizationInfo.setStringPermissions(adminService.findPermissions(username));
    return authorizationInfo;
}
 
Example 26
Project: xproject   File: AdminUserRealm.java   View source code 5 votes vote down vote up
/**
 * 用户授权-用户有哪些角色、权限
 */
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	logger.info(">>> 【用户授权】principals = {}", principals);
	String userName = (String)principals.getPrimaryPrincipal();
	AdminUser user = getPrincipalService().getPrincipalObject(userName);
	CustomAuthorizationInfo<AdminResource> authorizationInfo = new CustomAuthorizationInfo<AdminResource>();
       authorizationInfo.setRoles(getPrincipalService().getRoles(user));
       authorizationInfo.setStringPermissions(getPrincipalService().getPermissions(user));
       authorizationInfo.setResources(getPrincipalService().getResources(user));
       return authorizationInfo;
}
 
Example 27
Project: xproject   File: ShiroCacheServiceImpl.java   View source code 5 votes vote down vote up
public void clearCachedAuthorizationInfo(String principal) {
	try {
		AdminUserRealm userRealm = ShiroUtils.getRealm(AdminUserRealm.class);
		if(userRealm != null){
			PrincipalCollection principals = new SimplePrincipalCollection(principal, userRealm.getName());
			userRealm.clearCachedAuthorizationInfo(principals);
			logger.warn(">>> 清除用户[{}]的授权信息缓存", principal);
		}
	} catch (Exception e) {
		logger.error(String.format(">>> 清除用户授权缓存发生异常: %s", e.getMessage()), e);
	}
}
 
Example 28
Project: PowerApi   File: UserRealm.java   View source code 5 votes vote down vote up
/**
 * 对用户权限进行判定
 *
 * @param principals
 * @return
 */
@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 29
Project: BLOG-Microservice   File: MyShiroRealm.java   View source code 5 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    //为用户授予权限 staff-list
    //info.addStringPermission("staff-list");
    //获取当前登录对象
    //User user = (User) SecurityUtils.getSubject().getPrincipal();//User user2 = (User) principals.getPrimaryPrincipal();

    User user = (User) principalCollection.fromRealm(this.getName()).iterator().next();//根据传入的值选择realm

    if ("admin".equals(user.getUsername())) {

        Iterable<Authority> iterable = authorityService.findAll();
        iterable.forEach(auriter->{
            info.addStringPermission(auriter.getCode());
            System.err.println("admin有权限:"+auriter.getCode());
        });

    }else {

        Set<Authority> authoritySet = new HashSet<>(0);
        //根据用户id查询他的权限
        User userEntity = userService.findUserByUsername(user.getUsername());
        Set<Role> roles = userEntity.getRoles();
        //遍历用户的权限 取出权限
        roles.forEach(role -> {
            authoritySet.addAll(role.getAuthorities());
        });
        authoritySet.forEach(authority -> {
            info.addStringPermission(authority.getCode());
            System.err.println("有权限:"+authority.getCode());
        });

    }

    return info;

}
 
Example 30
Project: -Spring-SpringMVC-Mybatis-   File: UpmsRealm.java   View source code 5 votes vote down vote up
/**
 * 授权:验证权限时调用
 * @param principalCollection
 * @return
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    String username = (String) principalCollection.getPrimaryPrincipal();
    UpmsUser upmsUser = upmsApiService.selectUpmsUserByUsername(username);

    // 当前用户所有角色
    List<UpmsRole> upmsRoles = upmsApiService.selectUpmsRoleByUpmsUserId(upmsUser.getUserId());
    Set<String> roles = new HashSet<>();
    for (UpmsRole upmsRole : upmsRoles) {
        if (StringUtils.isNotBlank(upmsRole.getName())) {
            roles.add(upmsRole.getName());
        }
    }

    // 当前用户所有权限
    List<UpmsPermission> upmsPermissions = upmsApiService.selectUpmsPermissionByUpmsUserId(upmsUser.getUserId());
    Set<String> permissions = new HashSet<>();
    for (UpmsPermission upmsPermission : upmsPermissions) {
        if (StringUtils.isNotBlank(upmsPermission.getPermissionValue())) {
            permissions.add(upmsPermission.getPermissionValue());
        }
    }

    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    simpleAuthorizationInfo.setStringPermissions(permissions);
    simpleAuthorizationInfo.setRoles(roles);
    return simpleAuthorizationInfo;
}
 
Example 31
Project: oauth2-shiro   File: OAuth2JdbcRealm.java   View source code 5 votes vote down vote up
@Override
public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    //null usernames are invalid
    if (principals == null) {
        throw new OAuth2AuthenticationException("PrincipalCollection method argument cannot be null.");
    }

    String username = (String) 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, username);
        if (permissionsLookupEnabled) {
            permissions = getPermissions(conn, username, roleNames);
        }

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

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

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
    info.setStringPermissions(permissions);
    return info;

}
 
Example 32
Project: renren-msg   File: UserRealm.java   View source code 5 votes vote down vote up
/**
    * 授权(验证权限时调用)
    */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	SysUserEntity user = (SysUserEntity)principals.getPrimaryPrincipal();
	Long userId = user.getUserId();
	
	List<String> permsList = null;
	
	//系统管理员,拥有最高权限
	if(userId == 1){
		List<SysMenuEntity> menuList = sysMenuDao.queryList(new HashMap<String, Object>());
		permsList = new ArrayList<>(menuList.size());
		for(SysMenuEntity menu : menuList){
			permsList.add(menu.getPerms());
		}
	}else{
		permsList = sysUserDao.queryAllPerms(userId);
	}

	//用户权限列表
	Set<String> permsSet = new HashSet<String>();
	for(String perms : permsList){
		if(StringUtils.isBlank(perms)){
			continue;
		}
		permsSet.addAll(Arrays.asList(perms.trim().split(",")));
	}
	
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	info.setStringPermissions(permsSet);
	return info;
}
 
Example 33
Project: shuzheng   File: UpmsRealm.java   View source code 5 votes vote down vote up
/**
 * 授权:验证权限时调用
 * @param principalCollection
 * @return
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    String username = (String) principalCollection.getPrimaryPrincipal();
    UpmsUser upmsUser = upmsApiService.selectUpmsUserByUsername(username);

    // 当前用户所有角色
    List<UpmsRole> upmsRoles = upmsApiService.selectUpmsRoleByUpmsUserId(upmsUser.getUserId());
    Set<String> roles = new HashSet<>();
    for (UpmsRole upmsRole : upmsRoles) {
        if (StringUtils.isNotBlank(upmsRole.getName())) {
            roles.add(upmsRole.getName());
        }
    }

    // 当前用户所有权限
    List<UpmsPermission> upmsPermissions = upmsApiService.selectUpmsPermissionByUpmsUserId(upmsUser.getUserId());
    Set<String> permissions = new HashSet<>();
    for (UpmsPermission upmsPermission : upmsPermissions) {
        if (StringUtils.isNotBlank(upmsPermission.getPermissionValue())) {
            permissions.add(upmsPermission.getPermissionValue());
        }
    }

    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    simpleAuthorizationInfo.setStringPermissions(permissions);
    simpleAuthorizationInfo.setRoles(roles);
    return simpleAuthorizationInfo;
}
 
Example 34
Project: ZHFS-WEB   File: MyRealm.java   View source code 5 votes vote down vote up
/**
 * 用户授予权限
 * 
 * @param principalCollection
 * @return
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	String accountNumber = (String) principalCollection.getPrimaryPrincipal();
	User user = userService.getUserByAccountNumber(accountNumber);
	if (user != null) {// 给用户添加角色限制
		info.addRole(user.getRole().toString());
	} else {
		SecurityUtils.getSubject().logout();
	}
	return info;
}
 
Example 35
Project: DWSurvey   File: ShiroDbRealm.java   View source code 5 votes vote down vote up
/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.fromRealm(getName()).iterator().next();
//		User user = accountManager.findUserByLoginName(username);
		User user = accountManager.findUserByLoginNameOrEmail(username);
		if (user != null && "1".equals(user.getId())) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			info.addRole("admin");
			return info;
		} else {
			return null;
		}
	}
 
Example 36
Project: stateless-shiro   File: DatabaseRealm.java   View source code 5 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	Preconditions.checkNotNull(principals, "You can't have a null collection of principals. No really, how did you do that");
	String userEmail = (String) getAvailablePrincipal(principals);
	if (userEmail == null) {
		throw new NullPointerException("Can't find a principal in the collection");
	}
       LOGGER.debug("Finding authorization info for " + userEmail + " in DB");

	final User user = userRepository.findByEmailAndActive(userEmail, true);

       LOGGER.debug("Found " + userEmail + " in DB");

	final int totalRoles = user.getRoles().size();
	final Set<String> roleNames = new LinkedHashSet<>(totalRoles);
	final Set<String> permissionNames = new LinkedHashSet<>();
	if (totalRoles > 0) {
		for (Role role : user.getRoles()) {
			roleNames.add(role.getName());
			for (Permission permission : role.getPermissions()) {
				permissionNames.add(permission.getName());
			}
		}
	}

	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	info.addRoles(roleNames);
	info.addStringPermissions(permissionNames);
	return info;
}
 
Example 37
Project: home   File: SimpleRealm.java   View source code 5 votes vote down vote up
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    String username = (String) principalCollection.getPrimaryPrincipal();
    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    Set<String> roles = new HashSet<String>();
    roles.add("leader");
    Set<String> permissions = new HashSet<String>();
    permissions.add("user:view");
    simpleAuthorizationInfo.setRoles(roles);
    simpleAuthorizationInfo.setStringPermissions(permissions);
    return simpleAuthorizationInfo;
}
 
Example 38
Project: docs-manage   File: StatelessRealm.java   View source code 5 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    String username = (String) principalCollection.getPrimaryPrincipal();
    User user = userRepository.findByUsername(username);
    List<Role> roleList = user.getRoles();
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    Set<String> roleSet = roleList.stream().map(Role::getRoleName).collect(Collectors.toSet());
    info.addRoles(roleSet);
    return info;
}
 
Example 39
Project: oauth2-shiro-redis   File: OAuth2JdbcRealm.java   View source code 5 votes vote down vote up
@Override
public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    //null usernames are invalid
    if (principals == null) {
        throw new OAuth2AuthenticationException("PrincipalCollection method argument cannot be null.");
    }

    String username = (String) 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, username);
        if (permissionsLookupEnabled) {
            permissions = getPermissions(conn, username, roleNames);
        }

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

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

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
    info.setStringPermissions(permissions);
    return info;

}
 
Example 40
Project: oauth2-shiro-redis   File: RedisRealm.java   View source code 5 votes vote down vote up
protected String getUsername(PrincipalCollection principals) {
    //null usernames are invalid
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }

    return (String) getAvailablePrincipal(principals);
}