/** * Get a set of roles the subject has, based on {@link Role Role}. * This is the set of roles as assumed by authentication provider. Authorization providers may use a different set of * roles (and context used authorization provider to check {@link SecurityContext#isUserInRole(String)}). * * @param subject Subject of a user/service * @return set of roles the user/service is in */ public static Set<String> getRoles(Subject subject) { return subject.grants(Role.class) .stream() .map(Role::getName) .collect(Collectors.toSet()); }
private void validate(Set<String> rolesAllowed, Errors.Collector collector, Optional<Subject> subject, SubjectType type) { if (rolesAllowed.isEmpty()) { // no required roles return; } Set<String> roleGrants = subject .map(sub -> sub.grants(Role.class)) .orElse(CollectionsHelper.listOf()) .stream() .map(Role::getName) .collect(Collectors.toSet()); boolean notFound = true; for (String role : rolesAllowed) { if (roleGrants.contains(role)) { notFound = false; break; } } if (notFound) { collector.fatal(this, type + " is not in required roles: " + rolesAllowed + ", only in: " + roleGrants); } }
private void validate(Set<String> rolesAllowed, Errors.Collector collector, Optional<Subject> subject, SubjectType type) { if (rolesAllowed.isEmpty()) { // no required roles return; } Set<String> roleGrants = subject .map(sub -> sub.grants(Role.class)) .orElse(CollectionsHelper.listOf()) .stream() .map(Role::getName) .collect(Collectors.toSet()); boolean notFound = true; for (String role : rolesAllowed) { if (roleGrants.contains(role)) { notFound = false; break; } } if (notFound) { collector.fatal(this, type + " is not in required roles: " + rolesAllowed + ", only in: " + roleGrants); } }