|
| 1 | +package io.avaje.oauth2.helidon.jwtfilter; |
| 2 | + |
| 3 | +import io.avaje.oauth2.core.data.AccessToken; |
| 4 | +import io.avaje.oauth2.core.jwt.JwtVerifier; |
| 5 | +import io.helidon.common.context.Context; |
| 6 | +import io.helidon.http.HeaderNames; |
| 7 | +import io.helidon.http.UnauthorizedException; |
| 8 | +import io.helidon.webserver.http.FilterChain; |
| 9 | +import io.helidon.webserver.http.RoutingRequest; |
| 10 | +import io.helidon.webserver.http.RoutingResponse; |
| 11 | + |
| 12 | +import java.security.Principal; |
| 13 | +import java.util.List; |
| 14 | + |
| 15 | +final class AuthFilter implements JwtAuthFilter { |
| 16 | + |
| 17 | + private static final String BEARER_ = "Bearer "; |
| 18 | + private static final int BEARER_LENGTH = BEARER_.length(); |
| 19 | + |
| 20 | + private final JwtVerifier verifier; |
| 21 | + private final String[] allowedPaths; |
| 22 | + |
| 23 | + AuthFilter(JwtVerifier verifier, List<String> allowedPaths) { |
| 24 | + this.verifier = verifier; |
| 25 | + this.allowedPaths = allowedPaths.toArray(new String[0]); |
| 26 | + } |
| 27 | + |
| 28 | + @Override |
| 29 | + public void filter(FilterChain filterChain, RoutingRequest routingRequest, RoutingResponse routingResponse) { |
| 30 | + String header = routingRequest.headers().first(HeaderNames.AUTHORIZATION).orElse(""); |
| 31 | + if (header.startsWith(BEARER_)) { |
| 32 | + String token = header.substring(BEARER_LENGTH); |
| 33 | + AccessToken accessToken = verifier.verifyAccessToken(token); |
| 34 | + Context context = routingRequest.context(); |
| 35 | + context.register("security.principal", new TokenPrincipal(accessToken.clientId())); |
| 36 | + context.register("security.roles", accessToken.scope()); |
| 37 | + filterChain.proceed(); |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + final String path = routingRequest.path().path(); |
| 42 | + for (String allowedPath : allowedPaths) { |
| 43 | + if (path.startsWith(allowedPath)) { |
| 44 | + filterChain.proceed(); |
| 45 | + return; |
| 46 | + } |
| 47 | + } |
| 48 | + throw new UnauthorizedException("Unauthorized"); |
| 49 | + } |
| 50 | + |
| 51 | + private static final class TokenPrincipal implements Principal { |
| 52 | + |
| 53 | + private final String name; |
| 54 | + |
| 55 | + TokenPrincipal(String name) { |
| 56 | + this.name = name; |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public String getName() { |
| 61 | + return name; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments