Spring Boot 如何过滤Java流并只返回以提供的子字符串列表开头的项

bxgwgixi  于 2023-06-22  发布在  Spring
关注(0)|答案(1)|浏览(124)

我有一个当用户在Sping Boot 应用程序中进行身份验证时返回的权限列表。
例如,我获得了授权列表,如:

user_1_authority, 
user_2_authority,  
group_1_authority,  
group_2_authority,  
test_1_authority, 
test_2_authority, 
driver_x_authority,
...

我想过滤这些权限,以便只返回以“user_”或“group_”开头的权限。
我想知道如何使用Java流来返回一个新的过滤权限列表,以获得如下内容:

List<String> authoritiesStartingWithList = Arrays.asList("user_", "group_");

  public Collection<GrantedAuthorities> filterAuthorities(Authentication authentication, List<String> authoritiesStartingWithList) {
    return authentication.getAuthorities().stream().contains(authoritiesStartingWithList);
  }

这将返回一个仅包含以下内容的列表:

user_1_authority, 
user_2_authority,  
group_1_authority,  
group_2_authority,
4nkexdtk

4nkexdtk1#

请尝试以下解决方案:

List<String> authoritiesStartingWithList = Arrays.asList("user_", "group_");

public Collection<GrantedAuthority> filterAuthorities(Authentication authentication, List<String> authoritiesStartingWithList) {
  return authentication.getAuthorities().stream().filter(this::startsWithOneOfPredefinedValues).collect(Collectors.toList());
}

private boolean startsWithOneOfPredefinedValues(GrantedAuthority grantedAuthority) {
  return authoritiesStartingWithList.stream().anyMatch(i->grantedAuthority.getAuthority().startsWith(i));
}

过滤方法用于遍历前缀列表以检查是否存在任何匹配,如果没有找到匹配,则从流中过滤出权限。

相关问题