I have a list of authorities returned when user authenticates in Spring Boot app.
For example, I get list of granted authorities like:
user_1_authority,
user_2_authority,
group_1_authority,
group_2_authority,
test_1_authority,
test_2_authority,
driver_x_authority,
...
I would like to filter these authorities so that I get back only authorities starting with "user_" OR "group_".
I wonder how can I use Java streams to return a new list of filtered authorities to have something like:
List<String> authoritiesStartingWithList = Arrays.asList("user_", "group_");
public Collection<GrantedAuthorities> filterAuthorities(Authentication authentication, List<String> authoritiesStartingWithList) {
return authentication.getAuthorities().stream().contains(authoritiesStartingWithList);
}
this would return a list containing only:
user_1_authority,
user_2_authority,
group_1_authority,
group_2_authority,
Try the following solution:
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));
}
The filtering method is used to iterate through the list of prefixes to check if there are any matches, if no matches are found, authority is filtered out from the stream.