|
18 | 18 |
|
19 | 19 | import static java.util.Collections.emptySet; |
20 | 20 | import static java.util.stream.Collectors.toList; |
| 21 | +import static java.util.stream.Collectors.toSet; |
21 | 22 |
|
22 | 23 | import java.security.Principal; |
| 24 | +import java.util.Collections; |
23 | 25 | import java.util.LinkedHashSet; |
24 | 26 | import java.util.Locale; |
25 | 27 | import java.util.Set; |
26 | 28 | import java.util.concurrent.Callable; |
27 | 29 | import java.util.function.Supplier; |
28 | 30 | import java.util.stream.Stream; |
29 | 31 |
|
| 32 | +import javax.json.JsonArray; |
| 33 | +import javax.json.JsonString; |
| 34 | +import javax.json.JsonValue; |
30 | 35 | import javax.security.auth.Subject; |
31 | 36 | import javax.servlet.http.Cookie; |
32 | 37 | import javax.servlet.http.HttpServletRequest; |
|
40 | 45 | public class JwtRequest extends HttpServletRequestWrapper implements TokenAccessor { |
41 | 46 | private final Supplier<JsonWebToken> tokenExtractor; |
42 | 47 | private final String headerName; |
| 48 | + private final String groupsName; |
43 | 49 | private volatile JsonWebToken token; // cache for perf reasons |
44 | 50 |
|
45 | | - public JwtRequest(final JwtParser service, final String header, final String cookie, |
| 51 | + public JwtRequest(final JwtParser service, final String header, final String cookie, final String groupsName, |
46 | 52 | final String prefix, final HttpServletRequest request) { |
47 | 53 | super(request); |
48 | 54 | this.headerName = header; |
| 55 | + this.groupsName = groupsName; |
49 | 56 |
|
50 | 57 | this.tokenExtractor = () -> { |
51 | 58 | if (token != null) { |
@@ -132,6 +139,20 @@ public Principal getUserPrincipal() { |
132 | 139 |
|
133 | 140 | @Override |
134 | 141 | public boolean isUserInRole(final String role) { |
| 142 | + if (tokenExtractor.get().containsClaim(groupsName)) { |
| 143 | + JsonValue jsonValue = tokenExtractor.get().getClaim(groupsName); |
| 144 | + Set<String> groups = Collections.EMPTY_SET; |
| 145 | + if (jsonValue.getValueType() == JsonValue.ValueType.ARRAY) { |
| 146 | + groups = JsonArray.class.cast(jsonValue).stream() |
| 147 | + .map(grp -> ((JsonString)grp).getString()) |
| 148 | + .collect(toSet()); |
| 149 | + } else if (jsonValue.getValueType() == JsonValue.ValueType.STRING){ |
| 150 | + groups = Stream.of(JsonString.class.cast(jsonValue).getString().split(",")) |
| 151 | + .collect(toSet()); |
| 152 | + } |
| 153 | + return groups.stream().anyMatch(v -> v.equals(role)); |
| 154 | + } |
| 155 | + |
135 | 156 | return tokenExtractor.get().getGroups().contains(role); |
136 | 157 | } |
137 | 158 |
|
|
0 commit comments