22
22
import java .util .HashSet ;
23
23
import java .util .List ;
24
24
import java .util .Set ;
25
+ import java .util .stream .Stream ;
25
26
26
27
import org .springframework .security .core .GrantedAuthority ;
27
28
import org .springframework .util .Assert ;
@@ -39,6 +40,8 @@ public final class AuthorityUtils {
39
40
40
41
public static final List <GrantedAuthority > NO_AUTHORITIES = Collections .emptyList ();
41
42
43
+ private static String [] KNOWN_PREFIXES = { "ROLE_" , "SCOPE_" , "FACTOR_" };
44
+
42
45
private AuthorityUtils () {
43
46
}
44
47
@@ -93,4 +96,38 @@ public static List<GrantedAuthority> createAuthorityList(Collection<String> auth
93
96
return grantedAuthorities ;
94
97
}
95
98
99
+ /**
100
+ * Return a {@link Stream} containing only the authorities of the given type;
101
+ * {@code "ROLE"}, {@code "SCOPE"}, or {@code "FACTOR"}.
102
+ * @param type the authority type; {@code "ROLE"}, {@code "SCOPE"}, or
103
+ * {@code "FACTOR"}
104
+ * @param authorities the list of authorities
105
+ * @return a {@link Stream} containing the authorities of the given type
106
+ */
107
+ public static Stream <GrantedAuthority > authoritiesOfType (String type , Collection <GrantedAuthority > authorities ) {
108
+ return authorities .stream ().filter ((a ) -> a .getAuthority ().startsWith (type + "_" ));
109
+ }
110
+
111
+ /**
112
+ * Return the simple name of a {@link GrantedAuthority}, which is its name, less any
113
+ * common prefix; that is, {@code ROLE_}, {@code SCOPE_}, or {@code FACTOR_}.
114
+ * <p>
115
+ * For example, if the authority is {@code ROLE_USER}, then the simple name is
116
+ * {@code user}.
117
+ * <p>
118
+ * If the authority is {@code FACTOR_PASSWORD}, then the simple name is
119
+ * {@code password}.
120
+ * @param authority the granted authority
121
+ * @return the simple name of the authority
122
+ */
123
+ public static String getSimpleName (GrantedAuthority authority ) {
124
+ String name = authority .getAuthority ();
125
+ for (String prefix : KNOWN_PREFIXES ) {
126
+ if (name .startsWith (prefix )) {
127
+ return name .substring (prefix .length ());
128
+ }
129
+ }
130
+ return name ;
131
+ }
132
+
96
133
}
0 commit comments