Java Code Examples for org.apache.shiro.authz.SimpleAuthorizationInfo#setStringPermissions()

The following examples show how to use org.apache.shiro.authz.SimpleAuthorizationInfo#setStringPermissions() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LdapRealm.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
/**
* Get groups from LDAP.
*
* @param principals
*            the principals of the Subject whose AuthenticationInfo should
*            be queried from the LDAP server.
* @param ldapContextFactory
*            factory used to retrieve LDAP connections.
* @return an {@link AuthorizationInfo} instance containing information
*         retrieved from the LDAP server.
* @throws NamingException
*             if any LDAP errors occur during the search.
*/
@Override
public AuthorizationInfo queryForAuthorizationInfo(final PrincipalCollection principals,
    final LdapContextFactory ldapContextFactory) throws NamingException {
  if (!isAuthorizationEnabled()) {
    return null;
  }
  final Set<String> roleNames = getRoles(principals, ldapContextFactory);
  if (log.isDebugEnabled()) {
    log.debug("RolesNames Authorization: " + roleNames);
  }
  SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roleNames);
  Set<String> stringPermissions = permsFor(roleNames);
  simpleAuthorizationInfo.setStringPermissions(stringPermissions);
  return simpleAuthorizationInfo;
}
 
Example 2
Source File: DBRealm.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals,
                                                      LdapContextFactory ldapContextFactory) throws NamingException {
    System.out.println("————权限认证————");
    String username = JwtUtil.getUsername(principals.toString());
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    //获得该用户角色
    //String role = userMapper.getRole(username);
    //每个角色拥有默认的权限
    //String rolePermission = userMapper.getRolePermission(username);
    //每个用户可以设置新的权限
    //String permission = userMapper.getPermission(username);
    Set<String> roleSet = new HashSet<>();
    Set<String> permissionSet = new HashSet<>();
    //需要将 role, permission 封装到 Set 作为 info.setRoles(), info.setStringPermissions() 的参数
   // roleSet.add(role);
   // permissionSet.add(rolePermission);
    //permissionSet.add(permission);
    //设置该用户拥有的角色和权限
    info.setRoles(roleSet);
    info.setStringPermissions(permissionSet);
    return info;
}
 
Example 3
Source File: JwtRealm.java    From bootshiro with MIT License 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

    String payload = (String) principalCollection.getPrimaryPrincipal();
    // likely to be json, parse it:
    if (payload.startsWith(JWT) && payload.charAt(NUM_4) == LEFT
            && payload.charAt(payload.length() - 1) == RIGHT) {

        Map<String, Object> payloadMap = JsonWebTokenUtil.readValue(payload.substring(4));
        Set<String> roles = JsonWebTokenUtil.split((String)payloadMap.get("roles"));
        Set<String> permissions = JsonWebTokenUtil.split((String)payloadMap.get("perms"));
        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
        if(null!=roles&&!roles.isEmpty()) {
            info.setRoles(roles);
        }
        if(null!=permissions&&!permissions.isEmpty()) {
            info.setStringPermissions(permissions);
        }
        return info;
    }
    return null;
}
 
Example 4
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 获取用户角色和权限
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
	User user = (User) SecurityUtils.getSubject().getPrincipal();
	String userName = user.getUserName();

	System.out.println("用户" + userName + "获取权限-----ShiroRealm.doGetAuthorizationInfo");
	SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

	// 获取用户角色集
	List<Role> roleList = userRoleMapper.findByUserName(userName);
	Set<String> roleSet = new HashSet<String>();
	for (Role r : roleList) {
		roleSet.add(r.getName());
	}
	simpleAuthorizationInfo.setRoles(roleSet);

	// 获取用户权限集
	List<Permission> permissionList = userPermissionMapper.findByUserName(userName);
	Set<String> permissionSet = new HashSet<String>();
	for (Permission p : permissionList) {
		permissionSet.add(p.getName());
	}
	simpleAuthorizationInfo.setStringPermissions(permissionSet);
	return simpleAuthorizationInfo;
}
 
Example 5
Source File: MyCustomRealm.java    From tutorials with MIT License 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    Set<String> roleNames = new HashSet<>();
    Set<String> permissions = new HashSet<>();

    principals.forEach(p -> {
        try {
            Set<String> roles = getRoleNamesForUser(null, (String) p);
            roleNames.addAll(roles);
            permissions.addAll(getPermissions(null, null,roles));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
    info.setStringPermissions(permissions);
    return info;
}
 
Example 6
Source File: SimpleAuthorizingRealm.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	// null usernames are invalid
	if (principals == null) {
		throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
	}
	User user = (User) principals.getPrimaryPrincipal();
	if (user == null) {
		return null;
	}
	// 角色列表
	Set<String> roles =userService.getRoleCodeList(user.getId());
	// 功能列表
	Set<String> menus = userService.getPermsByUserId(user.getId());

	SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
	auth.setRoles(roles);
	auth.setStringPermissions(menus);
	return auth;
}
 
Example 7
Source File: ShiroRealm.java    From SpringAll with MIT License 6 votes vote down vote up
/**
 * 获取用户角色和权限
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
	User user = (User) SecurityUtils.getSubject().getPrincipal();
	String userName = user.getUserName();

	System.out.println("用户" + userName + "获取权限-----ShiroRealm.doGetAuthorizationInfo");
	SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

	// 获取用户角色集
	List<Role> roleList = userRoleMapper.findByUserName(userName);
	Set<String> roleSet = new HashSet<String>();
	for (Role r : roleList) {
		roleSet.add(r.getName());
	}
	simpleAuthorizationInfo.setRoles(roleSet);

	// 获取用户权限集
	List<Permission> permissionList = userPermissionMapper.findByUserName(userName);
	Set<String> permissionSet = new HashSet<String>();
	for (Permission p : permissionList) {
		permissionSet.add(p.getName());
	}
	simpleAuthorizationInfo.setStringPermissions(permissionSet);
	return simpleAuthorizationInfo;
}
 
Example 8
Source File: ShiroRealm.java    From taoshop with Apache License 2.0 5 votes vote down vote up
/**
 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用,负责在应用程序中决定用户的访问控制的方法(non-Javadoc)
 * @see AuthorizingRealm#doGetAuthorizationInfo(PrincipalCollection)
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
	String username = (String)pc.getPrimaryPrincipal();
	SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    authorizationInfo.setRoles(userService.getRoles(username));
    authorizationInfo.setStringPermissions(userService.getPermissions(username));
    return authorizationInfo;
}
 
Example 9
Source File: ShiroRealm.java    From OneBlog with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 权限认证,为当前登录的Subject授予角色和权限(角色的权限信息集合)
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    // 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

    Long userId = (Long) SecurityUtils.getSubject().getPrincipal();

    // 赋予角色
    List<Role> roleList = roleService.listRolesByUserId(userId);
    for (Role role : roleList) {
        info.addRole(role.getName());
    }

    // 赋予权限
    List<Resources> resourcesList = null;
    User user = userService.getByPrimaryKey(userId);
    if (null == user) {
        return info;
    }
    // ROOT用户默认拥有所有权限
    if (UserTypeEnum.ROOT.toString().equalsIgnoreCase(user.getUserType())) {
        resourcesList = resourcesService.listAll();
    } else {
        resourcesList = resourcesService.listByUserId(userId);
    }

    if (!CollectionUtils.isEmpty(resourcesList)) {
        Set<String> permissionSet = new HashSet<>();
        for (Resources resources : resourcesList) {
            String permission = null;
            if (!StringUtils.isEmpty(permission = resources.getPermission())) {
                permissionSet.addAll(Arrays.asList(permission.trim().split(",")));
            }
        }
        info.setStringPermissions(permissionSet);
    }
    return info;
}
 
Example 10
Source File: PasswordRealmMixin.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals )
{
    UnitOfWork uow = uowf.newUnitOfWork();
    try
    {

        String username = getAvailablePrincipal( principals ).toString();
        RoleAssignee roleAssignee = findRoleAssignee( uow, username );
        if( roleAssignee == null )
        {
            LOG.debug( "No authorization info for {}", username );
            return null;
        }
        LOG.debug( "Found role assignee for {}: {}", username, roleAssignee );
        Set<String> roleNames = roleAssignee.roleNames();
        Set<String> permissionStrings = roleAssignee.permissionStrings();
        LOG.debug( "Found role assignee has the following roles: {}", roleNames );
        LOG.debug( "Found role assignee has the following permissions: {}", permissionStrings );
        SimpleAuthorizationInfo atzInfo = new SimpleAuthorizationInfo( roleNames );
        atzInfo.setStringPermissions( permissionStrings );
        return atzInfo;
    }
    finally
    {
        uow.discard();
    }
}
 
Example 11
Source File: RealmInterceptor.java    From EasyEE with MIT License 5 votes vote down vote up
@Override
	public void afterDoGetAuthorizationInfo(SimpleAuthorizationInfo info) {
//		Set<String> roleNames = new LinkedHashSet<String>();
		Set<String> permissions = new LinkedHashSet<String>();
		
		Set<String> sets=info.getStringPermissions();
		
		for (String permissionString : sets) {
			if(permissionString!=null&&(!permissionString.trim().equals(""))){
				for (String o : permissionString.split("#|,")) {
					if (o.trim().length() > 0) {
						permissions.add(o.trim());
					}
				}
			}
		}
		info.setStringPermissions(permissions); 
		
		// System.out.println("permission:  "+permissions);
		
//		Set<String> sets2=info.getRoles();
		
//		for (String roleNameString : roleNames) {
//			if(roleNameString!=null&&(!roleNameString.trim().equals(""))){
//				for (String o : permissionString.split("#|,")) {
//					if (o.trim().length() > 0) {
//						permissions.add(o.trim());
//					}
//				}
//			}
//		}
	}
 
Example 12
Source File: ShiroConfiguration.java    From roncoo-jui-springboot with Apache License 2.0 5 votes vote down vote up
/**
 * 授权认证
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
	SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
	@SuppressWarnings("unchecked")
	List<SysMenuVO> menuVOList = (List<SysMenuVO>) SecurityUtils.getSubject().getSession().getAttribute(Constants.Session.MENU);
	Set<String> menuSet = new HashSet<>();
	// 处理菜单权限
	listMenu(menuSet, menuVOList);
	simpleAuthorizationInfo.setStringPermissions(menuSet);
	return simpleAuthorizationInfo;
}
 
Example 13
Source File: MyShiroRealmTest.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    String userName = (String) principals.getPrimaryPrincipal();

    // 模拟从数据库中查询角色
    Set<String> roles = getRolesByUserName(userName);
    // 模拟从数据库中查询权限
    Set<String> permissions = getPermissionsByUserName(userName);

    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    simpleAuthorizationInfo.setStringPermissions(permissions);
    simpleAuthorizationInfo.setRoles(roles);
    return simpleAuthorizationInfo;
}
 
Example 14
Source File: AdminAuthorizingRealm.java    From mall with MIT License 5 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }

    LitemallAdmin admin = (LitemallAdmin) getAvailablePrincipal(principals);
    Integer[] roleIds = admin.getRoleIds();
    Set<String> roles = roleService.queryByIds(roleIds);
    Set<String> permissions = permissionService.queryByRoleIds(roleIds);
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    info.setRoles(roles);
    info.setStringPermissions(permissions);
    return info;
}
 
Example 15
Source File: IrisRealm.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation of the interface expects the principals collection to return a String username keyed off of
 * this realm's {@link #getName() name}
 *
 * @see #getAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   //null usernames are invalid
   if (principals == null) {
      throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
   }

   String username = (String) getAvailablePrincipal(principals);

   Set<String> roleNames;
   Set<String> permissions = null;
   try {
      // Retrieve roles and permissions from database
      roleNames = getRoleNamesForUser(cassandraSession, username);
      if (permissionsLookupEnabled) {
         permissions = getPermissions(cassandraSession, 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 AuthorizationException(message, e);
   }

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

}
 
Example 16
Source File: UsernameRealm.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 授权
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

	String account = (String) principals.getPrimaryPrincipal();
	if(Objects.isNull(account)||!Strings.isNullOrEmpty(CommonUtils.jwtPayload(account))
							  ||!Strings.isNullOrEmpty(CommonUtils.hmacPayload(account))) 
		return null;
	SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
	Set<String> roles = this.accountProvider.loadRoles(account);
	Set<String> permissions = this.accountProvider.loadPermissions(account);
	if(!Collections.isEmpty(roles)) info.setRoles(roles);
	if(!Collections.isEmpty(permissions)) info.setStringPermissions(permissions);
       return info;  
}
 
Example 17
Source File: RealmInterceptor.java    From EasyEE with MIT License 5 votes vote down vote up
@Override
	public void afterDoGetAuthorizationInfo(SimpleAuthorizationInfo info) {
//		Set<String> roleNames = new LinkedHashSet<String>();
		Set<String> permissions = new LinkedHashSet<String>();
		
		Set<String> sets=info.getStringPermissions();
		
		for (String permissionString : sets) {
			if(permissionString!=null&&(!permissionString.trim().equals(""))){
				for (String o : permissionString.split("#|,")) {
					if (o.trim().length() > 0) {
						permissions.add(o.trim());
					}
				}
			}
		}
		info.setStringPermissions(permissions); 
		
//		System.out.println("permission:  "+permissions);
		
//		Set<String> sets2=info.getRoles();
		
//		for (String roleNameString : roleNames) {
//			if(roleNameString!=null&&(!roleNameString.trim().equals(""))){
//				for (String o : permissionString.split("#|,")) {
//					if (o.trim().length() > 0) {
//						permissions.add(o.trim());
//					}
//				}
//			}
//		}
	}
 
Example 18
Source File: UserNameRealm.java    From Shiro-Action with MIT License 5 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    log.info("从数据库获取权限信息");
    User user = (User) principals.getPrimaryPrincipal();

    String username = user.getUsername();

    Set<String> roles = userService.selectRoleNameByUserName(username);
    Set<String> perms = userService.selectPermsByUsername(username);

    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    authorizationInfo.setRoles(roles);
    authorizationInfo.setStringPermissions(perms);
    return authorizationInfo;
}
 
Example 19
Source File: MyShiroRealm.java    From permission with MIT License 5 votes vote down vote up
/**
 * 对用户进行角色授权
 *
 * @param principals 用户信息
 * @return 返回用户授权信息
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    String username = JWTUtil.getUsername(principals.toString());
    SysUser user = userService.findByName(username);
    Set<String> roles = roleService.findRoleByUserId(user.getId());
    Set<String> permissions = menuService.findPermsByUserId(user.getId());
    permissions = permissions.stream().filter(s -> s != null && !s.equals("")).collect(Collectors.toSet());
    authorizationInfo.setRoles(roles);
    authorizationInfo.setStringPermissions(permissions);
    return authorizationInfo;
}
 
Example 20
Source File: MyBatisRealm.java    From nano-framework with Apache License 2.0 4 votes vote down vote up
/**
 * This implementation of the interface expects the principals collection to return a String username keyed off of
 * this realm's {@link #getName() name}
 *
 * @see #getAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

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

    String username = (String) getAvailablePrincipal(principals);

    SqlSession sqlSession = null;
    Connection conn = null;
    Set<String> roleNames = null;
    Set<String> permissions = null;
    try {
    	if(sqlSessionManager == null)
    		sqlSessionManager = GlobalSqlSession.get(dataSourceName);
    	
        conn = (sqlSession = sqlSessionManager.openSession()).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 + ']';
        LOGGER.error(message, e);

        // Rethrow any SQL errors as an authorization exception
        throw new AuthorizationException(message, e);
    } finally {
        if(sqlSession != null) {
            sqlSession.close();
        }
    }

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

}