├── renovate.json ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── core ├── build.gradle └── src │ ├── main │ └── java │ │ └── com │ │ └── avast │ │ └── grpc │ │ └── jwt │ │ ├── client │ │ ├── SynchronousJwtTokenProvider.java │ │ ├── BlockingJwtTokenProvider.java │ │ ├── AsyncJwtTokenProvider.java │ │ └── JwtCallCredentials.java │ │ ├── Constants.java │ │ └── server │ │ ├── JwtTokenParser.java │ │ ├── DelayedServerCallListener.java │ │ └── JwtServerInterceptor.java │ └── test │ └── java │ └── com │ └── avast │ └── grpc │ └── jwt │ ├── client │ └── JwtCallCredentialsTest.java │ └── server │ └── JwtServerInterceptorTest.java ├── keycloak ├── src │ ├── test │ │ ├── resources │ │ │ └── reference.conf │ │ ├── proto │ │ │ └── TestServices.proto │ │ └── java │ │ │ └── com │ │ │ └── avast │ │ │ └── grpc │ │ │ └── jwt │ │ │ └── keycloak │ │ │ ├── TestServiceImpl.java │ │ │ └── KeycloakTest.java │ └── main │ │ ├── java │ │ └── com │ │ │ └── avast │ │ │ └── grpc │ │ │ └── jwt │ │ │ └── keycloak │ │ │ ├── server │ │ │ ├── KeycloakPublicKeyProvider.java │ │ │ ├── IssuersCheck.java │ │ │ ├── KeycloakJwtServerInterceptor.java │ │ │ ├── DefaultKeycloakPublicKeyProvider.java │ │ │ └── KeycloakJwtTokenParser.java │ │ │ ├── client │ │ │ └── KeycloakJwtCallCredentials.java │ │ │ └── KeycloakFactory.java │ │ └── resources │ │ └── reference.conf ├── docker-compose.yml ├── build.gradle └── test-realm.json ├── .github └── workflows │ ├── build.yml │ └── release.yml ├── LICENSE ├── gradlew.bat ├── README.md └── gradlew /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'grpc-java-jwt' 2 | 3 | include 'core' 4 | include 'keycloak' 5 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/avast/grpc-java-jwt/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | **/build/ 4 | **/out/ 5 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 6 | !gradle-wrapper.jar 7 | -------------------------------------------------------------------------------- /core/build.gradle: -------------------------------------------------------------------------------- 1 | tasks.jar.configure { 2 | archiveBaseName.set('grpc-java-jwt') 3 | } 4 | 5 | dependencies { 6 | api "io.grpc:grpc-core:$grpcVersion" 7 | api "org.slf4j:slf4j-api:2.0.17" 8 | } 9 | -------------------------------------------------------------------------------- /keycloak/src/test/resources/reference.conf: -------------------------------------------------------------------------------- 1 | testKeycloak { 2 | serverUrl = "http://"${KEYCLOAK_HOST}":"${KEYCLOAK_TCP_8080}"/auth" 3 | realm = "test" 4 | clientId = "test-client" 5 | clientSecret = "top-secret" 6 | } 7 | -------------------------------------------------------------------------------- /keycloak/src/main/java/com/avast/grpc/jwt/keycloak/server/KeycloakPublicKeyProvider.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.keycloak.server; 2 | 3 | import java.security.PublicKey; 4 | 5 | public interface KeycloakPublicKeyProvider { 6 | PublicKey get(String keyId); 7 | } 8 | -------------------------------------------------------------------------------- /core/src/main/java/com/avast/grpc/jwt/client/SynchronousJwtTokenProvider.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.client; 2 | 3 | @FunctionalInterface 4 | public interface SynchronousJwtTokenProvider { 5 | /* Gets encoded JWT token without blocking. */ 6 | String get(); 7 | } 8 | -------------------------------------------------------------------------------- /core/src/main/java/com/avast/grpc/jwt/client/BlockingJwtTokenProvider.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.client; 2 | 3 | @FunctionalInterface 4 | public interface BlockingJwtTokenProvider { 5 | /* Gets encoded JWT token, can block (e.g. perform blocking I/O). */ 6 | String get(); 7 | } 8 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-all.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /core/src/main/java/com/avast/grpc/jwt/client/AsyncJwtTokenProvider.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.client; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | 5 | @FunctionalInterface 6 | public interface AsyncJwtTokenProvider { 7 | /* Gets encoded JWT token. */ 8 | CompletableFuture get(); 9 | } 10 | -------------------------------------------------------------------------------- /core/src/main/java/com/avast/grpc/jwt/Constants.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt; 2 | 3 | import io.grpc.Metadata; 4 | 5 | public final class Constants { 6 | private Constants() {} 7 | 8 | public static io.grpc.Metadata.Key AuthorizationMetadataKey = 9 | Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER); 10 | } 11 | -------------------------------------------------------------------------------- /keycloak/src/test/proto/TestServices.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package com.avast.grpc.jwt.test; 4 | 5 | service TestService { 6 | rpc Add (AddParams) returns (AddResponse) { 7 | } 8 | } 9 | 10 | message AddParams { 11 | int32 a = 1; 12 | int32 b = 2; 13 | } 14 | 15 | message AddResponse { 16 | int32 sum = 1; 17 | } 18 | -------------------------------------------------------------------------------- /core/src/main/java/com/avast/grpc/jwt/server/JwtTokenParser.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.server; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | 5 | @FunctionalInterface 6 | public interface JwtTokenParser { 7 | 8 | /** Get valid JWT token, throws an exception otherwise. */ 9 | CompletableFuture parseToValid(String jwtToken); 10 | } 11 | -------------------------------------------------------------------------------- /keycloak/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | 3 | services: 4 | keycloak: 5 | image: keycloak/keycloak:26.4.7 6 | environment: 7 | - KEYCLOAK_ADMIN=admin 8 | - KEYCLOAK_ADMIN_PASSWORD=admin 9 | command: 10 | - "start-dev" 11 | - "--import-realm" 12 | - "--http-relative-path=/auth" 13 | volumes: 14 | - ./test-realm.json:/opt/keycloak/data/import/test-realm.json 15 | ports: 16 | - "8080" 17 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-24.04 8 | steps: 9 | - uses: actions/checkout@v6 10 | - name: Set up JDK 11 | uses: actions/setup-java@v5 12 | with: 13 | java-version: 17 14 | distribution: 'temurin' 15 | - name: Grant execute permission for gradlew 16 | run: chmod +x gradlew 17 | - name: Check with Gradle 18 | run: ./gradlew check --info 19 | -------------------------------------------------------------------------------- /keycloak/src/main/resources/reference.conf: -------------------------------------------------------------------------------- 1 | keycloakDefaults { 2 | serverUrl = "https://sso.example.com/auth" 3 | realm = "master" 4 | grantType = "client_credentials" // or password 5 | clientId = "" 6 | clientSecret = "" 7 | username = "" 8 | password = "" 9 | 10 | // for server 11 | expectedAudience = "" 12 | expectedIssuedFor = "" 13 | allowedIssuers = [] // list of additional allowed issuers, e.g. "https://sso-new.example.com/auth" 14 | minTimeBetweenJwksRequests = 10 seconds 15 | publicKeyCacheTtl = 1 day 16 | } 17 | -------------------------------------------------------------------------------- /keycloak/src/main/java/com/avast/grpc/jwt/keycloak/server/IssuersCheck.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.keycloak.server; 2 | 3 | import org.keycloak.TokenVerifier; 4 | import org.keycloak.common.VerificationException; 5 | import org.keycloak.representations.JsonWebToken; 6 | 7 | public class IssuersCheck implements TokenVerifier.Predicate { 8 | private final String[] issuers; 9 | 10 | public IssuersCheck(String[] issuers) { 11 | this.issuers = issuers; 12 | } 13 | 14 | @Override 15 | public boolean test(JsonWebToken t) throws VerificationException { 16 | for (String i : issuers) { 17 | if (i.equals(t.getIssuer())) { 18 | return true; 19 | } 20 | } 21 | throw new VerificationException( 22 | "Invalid token issuer. Was '" 23 | + t.getIssuer() 24 | + "' but expected one of: " 25 | + String.join(" ", issuers)); 26 | } 27 | } 28 | ; 29 | -------------------------------------------------------------------------------- /keycloak/src/main/java/com/avast/grpc/jwt/keycloak/client/KeycloakJwtCallCredentials.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.keycloak.client; 2 | 3 | import com.avast.grpc.jwt.client.JwtCallCredentials; 4 | import com.avast.grpc.jwt.keycloak.KeycloakFactory; 5 | import com.typesafe.config.Config; 6 | import org.keycloak.admin.client.Keycloak; 7 | 8 | public class KeycloakJwtCallCredentials extends JwtCallCredentials.Blocking 9 | implements AutoCloseable { 10 | private final Keycloak keycloak; 11 | 12 | public KeycloakJwtCallCredentials(Keycloak keycloak) { 13 | super(() -> keycloak.tokenManager().getAccessTokenString()); 14 | this.keycloak = keycloak; 15 | } 16 | 17 | @Override 18 | public void close() throws Exception { 19 | keycloak.close(); 20 | } 21 | 22 | public static KeycloakJwtCallCredentials fromConfig(Config config) { 23 | return new KeycloakJwtCallCredentials(KeycloakFactory.fromConfig(config)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /keycloak/src/test/java/com/avast/grpc/jwt/keycloak/TestServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.keycloak; 2 | 3 | import com.avast.grpc.jwt.test.TestServiceGrpc; 4 | import com.avast.grpc.jwt.test.TestServices; 5 | import io.grpc.Context; 6 | import io.grpc.stub.StreamObserver; 7 | import org.keycloak.representations.AccessToken; 8 | 9 | public class TestServiceImpl extends TestServiceGrpc.TestServiceImplBase { 10 | 11 | private final Context.Key accessTokenKey; 12 | AccessToken lastAccessToken; 13 | 14 | public TestServiceImpl(Context.Key accessTokenKey) { 15 | this.accessTokenKey = accessTokenKey; 16 | } 17 | 18 | @Override 19 | public void add( 20 | TestServices.AddParams request, StreamObserver responseObserver) { 21 | lastAccessToken = accessTokenKey.get(); 22 | responseObserver.onNext( 23 | TestServices.AddResponse.newBuilder().setSum(request.getA() + request.getB()).build()); 24 | responseObserver.onCompleted(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | release: 4 | types: [published] 5 | jobs: 6 | build: 7 | runs-on: ubuntu-24.04 8 | steps: 9 | - uses: actions/checkout@v6 10 | - name: Set up JDK 11 | uses: actions/setup-java@v5 12 | with: 13 | java-version: 17 14 | distribution: 'temurin' 15 | - name: Grant execute permission for gradlew 16 | run: chmod +x gradlew 17 | - name: Check with Gradle 18 | run: ./gradlew check --info -Pversion=${{ github.event.release.tag_name }} 19 | - name: Publish with Gradle to Maven Central 20 | run: ./gradlew publish jreleaserDeploy --info -Pversion=${{ github.event.release.tag_name }} 21 | env: 22 | SIGNING_KEY: ${{ secrets.SIGNING_KEY }} 23 | SIGNING_PUBLIC_KEY: ${{ secrets.SIGNING_PUBLIC_KEY }} 24 | JRELEASER_GPG_PASSPHRASE: ${{ secrets.SIGNING_PASSWORD }} 25 | JRELEASER_MAVENCENTRAL_USERNAME: ${{ secrets.JRELEASER_MAVENCENTRAL_USERNAME }} 26 | JRELEASER_MAVENCENTRAL_PASSWORD: ${{ secrets.JRELEASER_MAVENCENTRAL_PASSWORD }} 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Avast 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /keycloak/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.avast.gradle.docker-compose' 3 | id 'com.google.protobuf' 4 | id 'idea' 5 | } 6 | 7 | tasks.jar.configure { 8 | archiveBaseName.set('grpc-java-jwt-keycloak') 9 | } 10 | 11 | dockerCompose.isRequiredBy(test) 12 | 13 | protobuf { 14 | protoc { 15 | artifact = "com.google.protobuf:protoc:$protobufVersion" 16 | } 17 | plugins { 18 | grpc { 19 | artifact = "io.grpc:protoc-gen-grpc-java:$grpcVersion" 20 | } 21 | } 22 | generateProtoTasks { 23 | all()*.plugins { 24 | grpc {} 25 | } 26 | } 27 | } 28 | 29 | ext { 30 | keycloakClientVersion = '25.0.6' 31 | } 32 | 33 | dependencies { 34 | api project(':core') 35 | api "org.keycloak:keycloak-admin-client:$keycloakClientVersion" 36 | api "org.keycloak:keycloak-core:$keycloakClientVersion" 37 | api 'javax.annotation:javax.annotation-api:1.3.2' 38 | api 'org.bouncycastle:bcprov-jdk15on:1.70' 39 | api 'com.typesafe:config:1.4.5' 40 | 41 | testImplementation "com.google.protobuf:protobuf-java:$protobufVersion" 42 | testImplementation "io.grpc:grpc-inprocess:$grpcVersion" 43 | testImplementation "io.grpc:grpc-netty-shaded:$grpcVersion" 44 | testImplementation "io.grpc:grpc-protobuf:$grpcVersion" 45 | testImplementation "io.grpc:grpc-stub:$grpcVersion" 46 | } 47 | -------------------------------------------------------------------------------- /keycloak/src/main/java/com/avast/grpc/jwt/keycloak/KeycloakFactory.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.keycloak; 2 | 3 | import com.typesafe.config.Config; 4 | import com.typesafe.config.ConfigFactory; 5 | import org.keycloak.admin.client.Keycloak; 6 | import org.keycloak.admin.client.KeycloakBuilder; 7 | 8 | public final class KeycloakFactory { 9 | 10 | public static final String KEYCLOAK_DEFAULTS_CONFIG_NAME = "keycloakDefaults"; 11 | 12 | public static Keycloak fromConfig(Config config) { 13 | return fromConfig(config, Thread.currentThread().getContextClassLoader()); 14 | } 15 | 16 | public static Keycloak fromConfig(Config config, ClassLoader contextClassLoader) { 17 | Config fc = config.withFallback(getDefaultConfig(contextClassLoader)); 18 | return KeycloakBuilder.builder() 19 | .clientId(fc.getString("clientId")) 20 | .clientSecret(fc.getString("clientSecret")) 21 | .grantType(fc.getString("grantType")) 22 | .username(fc.getString("username")) 23 | .password(fc.getString("password")) 24 | .realm(fc.getString("realm")) 25 | .serverUrl(fc.getString("serverUrl")) 26 | .build(); 27 | } 28 | 29 | public static Config getDefaultConfig(final ClassLoader classLoader) { 30 | return ConfigFactory.defaultReference(classLoader).getConfig(KEYCLOAK_DEFAULTS_CONFIG_NAME); 31 | } 32 | 33 | private KeycloakFactory() {} 34 | } 35 | -------------------------------------------------------------------------------- /core/src/main/java/com/avast/grpc/jwt/server/DelayedServerCallListener.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.server; 2 | 3 | import io.grpc.ServerCall; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | // https://stackoverflow.com/a/53656689/181796 8 | class DelayedServerCallListener extends ServerCall.Listener { 9 | private ServerCall.Listener delegate; 10 | private List events = new ArrayList<>(); 11 | 12 | @Override 13 | public synchronized void onMessage(ReqT message) { 14 | if (delegate == null) { 15 | events.add(() -> delegate.onMessage(message)); 16 | } else { 17 | delegate.onMessage(message); 18 | } 19 | } 20 | 21 | @Override 22 | public synchronized void onHalfClose() { 23 | if (delegate == null) { 24 | events.add(() -> delegate.onHalfClose()); 25 | } else { 26 | delegate.onHalfClose(); 27 | } 28 | } 29 | 30 | @Override 31 | public synchronized void onCancel() { 32 | if (delegate == null) { 33 | events.add(() -> delegate.onCancel()); 34 | } else { 35 | delegate.onCancel(); 36 | } 37 | } 38 | 39 | @Override 40 | public synchronized void onComplete() { 41 | if (delegate == null) { 42 | events.add(() -> delegate.onComplete()); 43 | } else { 44 | delegate.onComplete(); 45 | } 46 | } 47 | 48 | @Override 49 | public synchronized void onReady() { 50 | if (delegate == null) { 51 | events.add(() -> delegate.onReady()); 52 | } else { 53 | delegate.onReady(); 54 | } 55 | } 56 | 57 | public synchronized void setDelegate(ServerCall.Listener delegate) { 58 | this.delegate = delegate; 59 | for (Runnable runnable : events) { 60 | runnable.run(); 61 | } 62 | events = null; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /keycloak/src/main/java/com/avast/grpc/jwt/keycloak/server/KeycloakJwtServerInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.keycloak.server; 2 | 3 | import static com.avast.grpc.jwt.keycloak.KeycloakFactory.getDefaultConfig; 4 | 5 | import com.avast.grpc.jwt.server.JwtServerInterceptor; 6 | import com.avast.grpc.jwt.server.JwtTokenParser; 7 | import com.typesafe.config.Config; 8 | import java.time.Clock; 9 | import org.keycloak.representations.AccessToken; 10 | 11 | public class KeycloakJwtServerInterceptor extends JwtServerInterceptor { 12 | public KeycloakJwtServerInterceptor(JwtTokenParser tokenParser) { 13 | super(tokenParser); 14 | } 15 | 16 | public static KeycloakJwtServerInterceptor fromConfig(Config config) { 17 | return fromConfig(config, Thread.currentThread().getContextClassLoader()); 18 | } 19 | 20 | public static KeycloakJwtServerInterceptor fromConfig( 21 | Config config, ClassLoader contextClassLoader) { 22 | Config fc = config.withFallback(getDefaultConfig(contextClassLoader)); 23 | KeycloakPublicKeyProvider publicKeyProvider = 24 | new DefaultKeycloakPublicKeyProvider( 25 | fc.getString("serverUrl"), 26 | fc.getString("realm"), 27 | fc.getDuration("minTimeBetweenJwksRequests"), 28 | fc.getDuration("publicKeyCacheTtl"), 29 | Clock.systemUTC()); 30 | KeycloakJwtTokenParser tokenParser = 31 | new KeycloakJwtTokenParser( 32 | fc.getString("serverUrl"), 33 | fc.getString("realm"), 34 | fc.getStringList("allowedIssuers"), 35 | publicKeyProvider); 36 | tokenParser = tokenParser.withExpectedAudience(fc.getString("expectedAudience")); 37 | tokenParser = tokenParser.withExpectedIssuedFor(fc.getString("expectedIssuedFor")); 38 | return new KeycloakJwtServerInterceptor(tokenParser); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /keycloak/test-realm.json: -------------------------------------------------------------------------------- 1 | { 2 | "realm": "test", 3 | "enabled": true, 4 | "sslRequired": "external", 5 | "privateKey": "MIICXAIBAAKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQABAoGAfmO8gVhyBxdqlxmIuglbz8bcjQbhXJLR2EoS8ngTXmN1bo2L90M0mUKSdc7qF10LgETBzqL8jYlQIbt+e6TH8fcEpKCjUlyq0Mf/vVbfZSNaVycY13nTzo27iPyWQHK5NLuJzn1xvxxrUeXI6A2WFpGEBLbHjwpx5WQG9A+2scECQQDvdn9NE75HPTVPxBqsEd2z10TKkl9CZxu10Qby3iQQmWLEJ9LNmy3acvKrE3gMiYNWb6xHPKiIqOR1as7L24aTAkEAtyvQOlCvr5kAjVqrEKXalj0Tzewjweuxc0pskvArTI2Oo070h65GpoIKLc9jf+UA69cRtquwP93aZKtW06U8dQJAF2Y44ks/mK5+eyDqik3koCI08qaC8HYq2wVl7G2QkJ6sbAaILtcvD92ToOvyGyeE0flvmDZxMYlvaZnaQ0lcSQJBAKZU6umJi3/xeEbkJqMfeLclD27XGEFoPeNrmdx0q10Azp4NfJAY+Z8KRyQCR2BEG+oNitBOZ+YXF9KCpH3cdmECQHEigJhYg+ykOvr1aiZUMFT72HU0jnmQe2FVekuG+LJUt2Tm7GtMjTFoGpf0JwrVuZN39fOYAlo+nTixgeW7X8Y=", 6 | "publicKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB", 7 | "users": [ 8 | { 9 | "username": "examples-admin-client", 10 | "enabled": true, 11 | "credentials": [ 12 | { 13 | "type": "password", 14 | "value": "password" 15 | } 16 | ], 17 | "clientRoles": { 18 | "realm-management": [ 19 | "realm-admin" 20 | ], 21 | "account": [ 22 | "manage-account" 23 | ] 24 | } 25 | } 26 | ], 27 | "clients": [ 28 | { 29 | "clientId": "test-client", 30 | "bearerOnly": false, 31 | "consentRequired": false, 32 | "standardFlowEnabled": false, 33 | "implicitFlowEnabled": false, 34 | "directAccessGrantsEnabled": false, 35 | "serviceAccountsEnabled": true, 36 | "publicClient": false, 37 | "enabled": true, 38 | "fullScopeAllowed": true, 39 | "secret": "top-secret" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /core/src/test/java/com/avast/grpc/jwt/client/JwtCallCredentialsTest.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.client; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.mockito.Mockito.mock; 5 | 6 | import com.avast.grpc.jwt.Constants; 7 | import io.grpc.CallCredentials; 8 | import io.grpc.Metadata; 9 | import io.grpc.Status; 10 | import java.util.concurrent.CompletableFuture; 11 | import java.util.concurrent.ExecutorService; 12 | import java.util.concurrent.Executors; 13 | import java.util.concurrent.atomic.AtomicReference; 14 | import org.junit.Test; 15 | 16 | public class JwtCallCredentialsTest { 17 | 18 | AtomicReference actualMetadata = new AtomicReference<>(); 19 | CallCredentials.MetadataApplier applier = 20 | new CallCredentials.MetadataApplier() { 21 | @Override 22 | public void apply(Metadata headers) { 23 | actualMetadata.set(headers); 24 | } 25 | 26 | @Override 27 | public void fail(Status status) {} 28 | }; 29 | ExecutorService executor = Executors.newSingleThreadExecutor(); 30 | 31 | @Test 32 | public void synchronous() { 33 | JwtCallCredentials target = JwtCallCredentials.synchronous(() -> "test token"); 34 | target.applyRequestMetadata( 35 | mock(CallCredentials.RequestInfo.class), Executors.newSingleThreadExecutor(), applier); 36 | assertEquals("Bearer test token", actualMetadata.get().get(Constants.AuthorizationMetadataKey)); 37 | } 38 | 39 | @Test 40 | public void blocking() throws InterruptedException { 41 | JwtCallCredentials target = JwtCallCredentials.blocking(() -> "test token"); 42 | target.applyRequestMetadata(mock(CallCredentials.RequestInfo.class), executor, applier); 43 | Thread.sleep(1000); 44 | assertEquals("Bearer test token", actualMetadata.get().get(Constants.AuthorizationMetadataKey)); 45 | } 46 | 47 | @Test 48 | public void asynchronous() throws InterruptedException { 49 | JwtCallCredentials target = 50 | JwtCallCredentials.asynchronous(() -> CompletableFuture.completedFuture("test token")); 51 | target.applyRequestMetadata(mock(CallCredentials.RequestInfo.class), executor, applier); 52 | Thread.sleep(1000); 53 | assertEquals("Bearer test token", actualMetadata.get().get(Constants.AuthorizationMetadataKey)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /keycloak/src/test/java/com/avast/grpc/jwt/keycloak/KeycloakTest.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.keycloak; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertFalse; 5 | 6 | import com.avast.grpc.jwt.keycloak.client.KeycloakJwtCallCredentials; 7 | import com.avast.grpc.jwt.keycloak.server.KeycloakJwtServerInterceptor; 8 | import com.avast.grpc.jwt.test.TestServiceGrpc; 9 | import com.avast.grpc.jwt.test.TestServices; 10 | import com.typesafe.config.Config; 11 | import com.typesafe.config.ConfigFactory; 12 | import io.grpc.*; 13 | import io.grpc.inprocess.InProcessChannelBuilder; 14 | import io.grpc.inprocess.InProcessServerBuilder; 15 | import java.io.IOException; 16 | import org.junit.Test; 17 | 18 | public class KeycloakTest { 19 | Config config = ConfigFactory.load().getConfig("testKeycloak"); 20 | String channelName = InProcessServerBuilder.generateName(); 21 | 22 | ManagedChannel clientChannel = 23 | InProcessChannelBuilder.forName(channelName).usePlaintext().build(); 24 | 25 | KeycloakJwtServerInterceptor serverInterceptor = KeycloakJwtServerInterceptor.fromConfig(config); 26 | TestServiceImpl service = new TestServiceImpl(serverInterceptor.AccessTokenContextKey); 27 | 28 | @Test 29 | public void endToEndTest() throws IOException { 30 | TestServiceGrpc.TestServiceBlockingStub client = 31 | TestServiceGrpc.newBlockingStub(clientChannel) 32 | .withCallCredentials(KeycloakJwtCallCredentials.fromConfig(config)); 33 | 34 | Server server = 35 | InProcessServerBuilder.forName(channelName) 36 | .addService(ServerInterceptors.intercept(service, serverInterceptor)) 37 | .build() 38 | .start(); 39 | try { 40 | TestServices.AddResponse sum = 41 | client.add(TestServices.AddParams.newBuilder().setA(1).setB(2).build()); 42 | assertEquals(sum.getSum(), 3); 43 | assertEquals(service.lastAccessToken.getType(), "Bearer"); 44 | } finally { 45 | server.shutdownNow(); 46 | } 47 | } 48 | 49 | @Test 50 | public void rejectsRequestWithoutHeader() throws IOException { 51 | TestServiceGrpc.TestServiceBlockingStub client = TestServiceGrpc.newBlockingStub(clientChannel); 52 | Server server = 53 | InProcessServerBuilder.forName(channelName) 54 | .addService(ServerInterceptors.intercept(service, serverInterceptor)) 55 | .build() 56 | .start(); 57 | try { 58 | TestServices.AddResponse sum = 59 | client.add(TestServices.AddParams.newBuilder().setA(1).setB(2).build()); 60 | } catch (StatusRuntimeException e) { 61 | assertFalse(e.getStatus().isOk()); 62 | assertEquals(Status.UNAUTHENTICATED.getCode(), e.getStatus().getCode()); 63 | } finally { 64 | server.shutdownNow(); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /core/src/test/java/com/avast/grpc/jwt/server/JwtServerInterceptorTest.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.server; 2 | 3 | import static org.junit.Assert.*; 4 | import static org.mockito.Mockito.*; 5 | 6 | import com.avast.grpc.jwt.Constants; 7 | import io.grpc.Metadata; 8 | import io.grpc.ServerCall; 9 | import io.grpc.ServerCallHandler; 10 | import java.util.concurrent.CompletableFuture; 11 | import java.util.concurrent.atomic.AtomicReference; 12 | import org.junit.Test; 13 | 14 | public class JwtServerInterceptorTest { 15 | 16 | JwtTokenParser jwtTokenParser = 17 | jwtToken -> { 18 | if (jwtToken.equals("Invalid Token")) { 19 | CompletableFuture res = new CompletableFuture<>(); 20 | res.completeExceptionally(new RuntimeException("invalid token")); 21 | return res; 22 | } 23 | return CompletableFuture.completedFuture(jwtToken); 24 | }; 25 | JwtServerInterceptor target = new JwtServerInterceptor<>(jwtTokenParser); 26 | ServerCall serverCall = (ServerCall) mock(ServerCall.class); 27 | ServerCallHandler next = 28 | (ServerCallHandler) mock(ServerCallHandler.class); 29 | 30 | @Test 31 | public void closesCallOnMisingHeader() { 32 | target.interceptCall(serverCall, new Metadata(), next); 33 | verify(serverCall).close(any(), any()); 34 | verify(next, never()).startCall(any(), any()); 35 | } 36 | 37 | @Test 38 | public void closesCallOnInvalidHeader() { 39 | Metadata metadata = new Metadata(); 40 | metadata.put(Constants.AuthorizationMetadataKey, "Bbb"); 41 | target.interceptCall(serverCall, metadata, next); 42 | verify(serverCall).close(any(), any()); 43 | verify(next, never()).startCall(any(), any()); 44 | } 45 | 46 | @Test 47 | public void closesCallOnInvalidToken() { 48 | Metadata metadata = new Metadata(); 49 | metadata.put(Constants.AuthorizationMetadataKey, "Bearer Invalid Token"); 50 | target.interceptCall(serverCall, metadata, next); 51 | verify(serverCall).close(any(), any()); 52 | verify(next, never()).startCall(any(), any()); 53 | } 54 | 55 | @Test 56 | public void callNextStageWithContextKeyOnValidHeader() { 57 | Metadata metadata = new Metadata(); 58 | metadata.put(Constants.AuthorizationMetadataKey, "Bearer test token"); 59 | final AtomicReference actualToken = new AtomicReference<>(""); 60 | when(next.startCall(any(), any())) 61 | .thenAnswer( 62 | i -> { 63 | actualToken.set(target.AccessTokenContextKey.get()); 64 | return null; 65 | }); 66 | target.interceptCall(serverCall, metadata, next); 67 | verify(serverCall, never()).close(any(), any()); 68 | verify(next).startCall(any(), any()); 69 | assertEquals("test token", actualToken.get()); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /keycloak/src/main/java/com/avast/grpc/jwt/keycloak/server/DefaultKeycloakPublicKeyProvider.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.keycloak.server; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import java.io.IOException; 5 | import java.net.URL; 6 | import java.security.PublicKey; 7 | import java.time.Clock; 8 | import java.time.Duration; 9 | import java.time.Instant; 10 | import java.util.Map; 11 | import java.util.concurrent.ConcurrentHashMap; 12 | import org.keycloak.constants.ServiceUrlConstants; 13 | import org.keycloak.jose.jwk.JSONWebKeySet; 14 | import org.keycloak.jose.jwk.JWK; 15 | import org.keycloak.util.JWKSUtils; 16 | 17 | public class DefaultKeycloakPublicKeyProvider implements KeycloakPublicKeyProvider { 18 | 19 | private final String serverUrl; 20 | private final String realm; 21 | private final Duration minTimeBetweenJwksRequests; 22 | private final Duration publicKeyCacheTtl; 23 | private final Clock clock; 24 | 25 | private Map currentKeys = new ConcurrentHashMap<>(); 26 | private volatile Instant lastRequestTime = Instant.MIN; 27 | 28 | public DefaultKeycloakPublicKeyProvider( 29 | String serverUrl, 30 | String realm, 31 | Duration minTimeBetweenJwksRequests, 32 | Duration publicKeyCacheTtl, 33 | Clock clock) { 34 | this.serverUrl = serverUrl; 35 | this.realm = realm; 36 | this.minTimeBetweenJwksRequests = minTimeBetweenJwksRequests; 37 | this.publicKeyCacheTtl = publicKeyCacheTtl; 38 | this.clock = clock; 39 | } 40 | 41 | @Override 42 | public PublicKey get(String keyId) { 43 | if (lastRequestTime.plus(publicKeyCacheTtl).isBefore(clock.instant())) { 44 | updateKeys(); 45 | } 46 | PublicKey fromCache = currentKeys.get(keyId); 47 | if (fromCache != null) { 48 | return fromCache; 49 | } 50 | updateKeys(); 51 | PublicKey res = currentKeys.get(keyId); 52 | if (res == null) { 53 | throw new RuntimeException("Key with following ID not found: " + keyId); 54 | } 55 | return res; 56 | } 57 | 58 | protected void updateKeys() { 59 | synchronized (this) { 60 | if (clock.instant().isAfter(lastRequestTime.plus(minTimeBetweenJwksRequests))) { 61 | Map newKeys = fetchNewKeys(); 62 | currentKeys.clear(); 63 | currentKeys.putAll(newKeys); 64 | lastRequestTime = clock.instant(); 65 | } 66 | } 67 | } 68 | 69 | protected Map fetchNewKeys() { 70 | try { 71 | ObjectMapper om = new ObjectMapper(); 72 | String jwksUrl = serverUrl + ServiceUrlConstants.JWKS_URL.replace("{realm-name}", realm); 73 | JSONWebKeySet jwks = om.readValue(new URL(jwksUrl).openStream(), JSONWebKeySet.class); 74 | return JWKSUtils.getKeysForUse(jwks, JWK.Use.SIG); 75 | } catch (IOException e) { 76 | throw new RuntimeException("Cannot fetch key from Keycloak server", e); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /core/src/main/java/com/avast/grpc/jwt/server/JwtServerInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.server; 2 | 3 | import com.avast.grpc.jwt.Constants; 4 | import io.grpc.*; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | public class JwtServerInterceptor implements ServerInterceptor { 9 | private static Logger LOGGER = LoggerFactory.getLogger(JwtServerInterceptor.class); 10 | 11 | public final io.grpc.Context.Key AccessTokenContextKey = Context.key("AccessToken"); 12 | 13 | private static final String AUTH_HEADER_PREFIX = "Bearer "; 14 | 15 | private final JwtTokenParser tokenParser; 16 | 17 | public JwtServerInterceptor(JwtTokenParser tokenParser) { 18 | this.tokenParser = tokenParser; 19 | } 20 | 21 | @Override 22 | public ServerCall.Listener interceptCall( 23 | ServerCall call, Metadata headers, ServerCallHandler next) { 24 | String authHeader = headers.get(Constants.AuthorizationMetadataKey); 25 | if (authHeader == null) { 26 | String msg = Constants.AuthorizationMetadataKey.name() + " header not found"; 27 | LOGGER.warn(msg); 28 | call.close(Status.UNAUTHENTICATED.withDescription(msg), new Metadata()); 29 | return new ServerCall.Listener() {}; 30 | } 31 | if (!authHeader.startsWith(AUTH_HEADER_PREFIX)) { 32 | String msg = 33 | Constants.AuthorizationMetadataKey.name() 34 | + " header does not start with " 35 | + AUTH_HEADER_PREFIX; 36 | LOGGER.warn(msg); 37 | call.close(Status.UNAUTHENTICATED.withDescription(msg), new Metadata()); 38 | return new ServerCall.Listener() {}; 39 | } 40 | DelayedServerCallListener delayedListener = new DelayedServerCallListener<>(); 41 | Context context = Context.current(); // we must call this on the right thread 42 | try { 43 | tokenParser 44 | .parseToValid(authHeader.substring(AUTH_HEADER_PREFIX.length())) 45 | .whenComplete( 46 | (token, e) -> 47 | context.run( 48 | () -> { 49 | if (e == null) { 50 | delayedListener.setDelegate( 51 | Contexts.interceptCall( 52 | Context.current().withValue(AccessTokenContextKey, token), 53 | call, 54 | headers, 55 | next)); 56 | } else { 57 | delayedListener.setDelegate(handleException(e, call)); 58 | } 59 | })); 60 | } catch (Exception e) { 61 | return handleException(e, call); 62 | } 63 | return delayedListener; 64 | } 65 | 66 | private ServerCall.Listener handleException( 67 | Throwable e, ServerCall call) { 68 | String msg = 69 | Constants.AuthorizationMetadataKey.name() + " header validation failed: " + e.getMessage(); 70 | LOGGER.warn(msg, e); 71 | call.close(Status.UNAUTHENTICATED.withDescription(msg).withCause(e), new Metadata()); 72 | return new ServerCall.Listener() {}; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | 74 | 75 | @rem Execute Gradle 76 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* 77 | 78 | :end 79 | @rem End local scope for the variables with windows NT shell 80 | if %ERRORLEVEL% equ 0 goto mainEnd 81 | 82 | :fail 83 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 84 | rem the _cmd.exe /c_ return code! 85 | set EXIT_CODE=%ERRORLEVEL% 86 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 87 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 88 | exit /b %EXIT_CODE% 89 | 90 | :mainEnd 91 | if "%OS%"=="Windows_NT" endlocal 92 | 93 | :omega 94 | -------------------------------------------------------------------------------- /keycloak/src/main/java/com/avast/grpc/jwt/keycloak/server/KeycloakJwtTokenParser.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.keycloak.server; 2 | 3 | import com.avast.grpc.jwt.server.JwtTokenParser; 4 | 5 | import java.util.Collections; 6 | import java.util.List; 7 | import java.util.concurrent.CompletableFuture; 8 | import java.util.concurrent.CompletionException; 9 | import java.util.stream.Collectors; 10 | 11 | import org.keycloak.TokenVerifier; 12 | import org.keycloak.common.VerificationException; 13 | import org.keycloak.constants.ServiceUrlConstants; 14 | import org.keycloak.representations.AccessToken; 15 | import org.keycloak.util.TokenUtil; 16 | 17 | public class KeycloakJwtTokenParser implements JwtTokenParser { 18 | 19 | protected final KeycloakPublicKeyProvider publicKeyProvider; 20 | protected final TokenVerifier.Predicate[] checks; 21 | protected String expectedAudience; 22 | protected String expectedIssuedFor; 23 | 24 | public KeycloakJwtTokenParser( 25 | String serverUrl, 26 | String realm, 27 | List allowedIssuers, 28 | KeycloakPublicKeyProvider publicKeyProvider) { 29 | this.publicKeyProvider = publicKeyProvider; 30 | 31 | String suffix = ServiceUrlConstants.REALM_INFO_PATH.replace("{realm-name}", realm); 32 | List issuers = 33 | allowedIssuers.stream().map(i -> i + suffix).collect(Collectors.toList()); 34 | issuers.add(0, serverUrl + suffix); 35 | this.checks = 36 | new TokenVerifier.Predicate[] { 37 | new IssuersCheck(issuers.toArray(new String[0])), 38 | TokenVerifier.SUBJECT_EXISTS_CHECK, 39 | new TokenVerifier.TokenTypeCheck(Collections.singletonList(TokenUtil.TOKEN_TYPE_BEARER)), 40 | TokenVerifier.IS_ACTIVE 41 | }; 42 | } 43 | 44 | @Override 45 | public CompletableFuture parseToValid(String jwtToken) { 46 | TokenVerifier verifier; 47 | try { 48 | verifier = createTokenVerifier(jwtToken); 49 | } catch (VerificationException e) { 50 | CompletableFuture r = new CompletableFuture<>(); 51 | r.completeExceptionally(e); 52 | return r; 53 | } 54 | return CompletableFuture.supplyAsync( 55 | () -> { 56 | try { 57 | return verifier.verify().getToken(); 58 | } catch (VerificationException e) { 59 | throw new CompletionException(e); 60 | } 61 | }); 62 | } 63 | 64 | protected TokenVerifier createTokenVerifier(String jwtToken) 65 | throws VerificationException { 66 | TokenVerifier verifier = 67 | TokenVerifier.create(jwtToken, AccessToken.class).withChecks(checks); 68 | if (expectedAudience != null && !expectedAudience.isEmpty()) { 69 | verifier = verifier.audience(expectedAudience); 70 | } 71 | if (expectedIssuedFor != null && !expectedIssuedFor.isEmpty()) { 72 | verifier = verifier.issuedFor(expectedIssuedFor); 73 | } 74 | verifier.publicKey(publicKeyProvider.get(verifier.getHeader().getKeyId())); 75 | return verifier; 76 | } 77 | 78 | public KeycloakJwtTokenParser withExpectedAudience(String expectedAudience) { 79 | this.expectedAudience = expectedAudience; 80 | return this; 81 | } 82 | 83 | public KeycloakJwtTokenParser withExpectedIssuedFor(String expectedIssuedFor) { 84 | this.expectedIssuedFor = expectedIssuedFor; 85 | return this; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /core/src/main/java/com/avast/grpc/jwt/client/JwtCallCredentials.java: -------------------------------------------------------------------------------- 1 | package com.avast.grpc.jwt.client; 2 | 3 | import com.avast.grpc.jwt.Constants; 4 | import io.grpc.CallCredentials; 5 | import io.grpc.Metadata; 6 | import io.grpc.Status; 7 | import java.util.concurrent.Executor; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | public abstract class JwtCallCredentials extends CallCredentials { 12 | private static Logger LOGGER = LoggerFactory.getLogger(JwtCallCredentials.class); 13 | 14 | public static JwtCallCredentials synchronous(SynchronousJwtTokenProvider tokenProvider) { 15 | return new Synchronous(tokenProvider); 16 | } 17 | 18 | public static JwtCallCredentials blocking(BlockingJwtTokenProvider tokenProvider) { 19 | return new Blocking(tokenProvider); 20 | } 21 | 22 | public static JwtCallCredentials asynchronous(AsyncJwtTokenProvider tokenProvider) { 23 | return new Asynchronous(tokenProvider); 24 | } 25 | 26 | @Override 27 | public void thisUsesUnstableApi() {} 28 | 29 | protected void applyToken(MetadataApplier applier, String jwtToken) { 30 | Metadata metadata = new Metadata(); 31 | metadata.put(Constants.AuthorizationMetadataKey, "Bearer " + jwtToken); 32 | applier.apply(metadata); 33 | } 34 | 35 | protected void applyFailure(MetadataApplier applier, Throwable e) { 36 | String msg = "An exception when obtaining JWT token"; 37 | LOGGER.error(msg, e); 38 | applier.fail(Status.UNAUTHENTICATED.withDescription(msg).withCause(e)); 39 | } 40 | 41 | public static class Synchronous extends JwtCallCredentials { 42 | 43 | private final SynchronousJwtTokenProvider jwtTokenProvider; 44 | 45 | public Synchronous(SynchronousJwtTokenProvider jwtTokenProvider) { 46 | this.jwtTokenProvider = jwtTokenProvider; 47 | } 48 | 49 | @Override 50 | public void applyRequestMetadata( 51 | RequestInfo requestInfo, Executor appExecutor, MetadataApplier applier) { 52 | try { 53 | applyToken(applier, jwtTokenProvider.get()); 54 | } catch (RuntimeException e) { 55 | applyFailure(applier, e); 56 | } 57 | } 58 | } 59 | 60 | public static class Blocking extends JwtCallCredentials { 61 | 62 | private final BlockingJwtTokenProvider jwtTokenProvider; 63 | 64 | public Blocking(BlockingJwtTokenProvider jwtTokenProvider) { 65 | this.jwtTokenProvider = jwtTokenProvider; 66 | } 67 | 68 | @Override 69 | public void applyRequestMetadata( 70 | RequestInfo requestInfo, Executor appExecutor, MetadataApplier applier) { 71 | appExecutor.execute( 72 | () -> { 73 | try { 74 | applyToken(applier, jwtTokenProvider.get()); 75 | } catch (RuntimeException e) { 76 | applyFailure(applier, e); 77 | } 78 | }); 79 | } 80 | } 81 | 82 | public static class Asynchronous extends JwtCallCredentials { 83 | 84 | private final AsyncJwtTokenProvider jwtTokenProvider; 85 | 86 | public Asynchronous(AsyncJwtTokenProvider jwtTokenProvider) { 87 | this.jwtTokenProvider = jwtTokenProvider; 88 | } 89 | 90 | @Override 91 | public void applyRequestMetadata( 92 | RequestInfo requestInfo, Executor appExecutor, MetadataApplier applier) { 93 | jwtTokenProvider 94 | .get() 95 | .whenComplete( 96 | (token, e) -> { 97 | if (token != null) applyToken(applier, token); 98 | else applyFailure(applier, e); 99 | }); 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gRPC Java JWT support [![Build](https://github.com/avast/grpc-java-jwt/actions/workflows/build.yml/badge.svg)](https://github.com/avast/grpc-java-jwt/actions/workflows/build.yml) [![Version](https://badgen.net/maven/v/maven-central/com.avast.grpc.jwt/grpc-java-jwt/)](https://repo1.maven.org/maven2/com/avast/grpc/jwt/) 2 | 3 | Library that helps with authenticated communication in gRPC-Java based applications. It uses [JSON Web Token](https://jwt.io/) transported in `Authorization` header (as `Bearer rawJWT`). 4 | 5 | Implementation of standard `CallCredentials` ensures that the header is sent, and `ServerInterceptor` ensures that the incoming header is valid and makes the parsed JWT available for the underlying code. 6 | 7 | ```maven 8 | 9 | com.avast.grpc.jwt 10 | grpc-java-jwt 11 | $latestVersion 12 | 13 | ``` 14 | ```gradle 15 | compile "com.avast.grpc.jwt:grpc-java-jwt:$latestVersion" 16 | ```` 17 | 18 | This base library contains a code that is not tied to any specific JWT implementation. So it requires instances of _JwtTokenProvider_ interface (for client) and [JwtTokenParser](core/src/main/java/com/avast/grpc/jwt/server/JwtTokenParser.java) (for server) to work. 19 | 20 | ## Keycloak support 21 | There are implementations of the core interfaces for [Keycloak](https://www.keycloak.org/). 22 | 23 | ```maven 24 | 25 | com.avast.grpc.jwt 26 | grpc-java-jwt-keycloak 27 | $latestVersion 28 | 29 | ``` 30 | ```gradle 31 | compile "com.avast.grpc.jwt:grpc-java-jwt-keycloak:$latestVersion" 32 | ```` 33 | 34 | Configuration defaults can be [found here](keycloak/src/main/resources/reference.conf). It uses [HOCON](https://github.com/lightbend/config/blob/master/HOCON.md) and [Lightbend Config](https://github.com/lightbend/config). 35 | 36 | ### Client usage 37 | This ensures that each call contains `Authorization` header with `Bearer ` prefixed Keycloak access token (as JWT). 38 | ```java 39 | import com.avast.grpc.jwt.keycloak.client.KeycloakJwtCallCredentials; 40 | 41 | KeycloakJwtCallCredentials callCredentials = KeycloakJwtCallCredentials.fromConfig(yourConfig); 42 | YourService.newStub(aChannel).withCallCredentials(callCredentials); 43 | ``` 44 | 45 | ### Server usage 46 | This ensures that only requests with valid `JWT` in `Authorization` header are processed. 47 | ```java 48 | import io.grpc.ServerServiceDefinition; 49 | import com.avast.grpc.jwt.keycloak.server.KeycloakJwtServerInterceptor; 50 | 51 | KeycloakJwtServerInterceptor serverInterceptor = KeycloakJwtServerInterceptor.fromConfig(yourConfig); 52 | ServerServiceDefinition interceptedService = ServerInterceptors.intercept(yourService, serverInterceptor); 53 | 54 | // read token in a gRPC method implementation 55 | import org.keycloak.representations.AccessToken; 56 | AccessToken accessToken = serverInterceptor.AccessTokenContextKey.get(); 57 | ``` 58 | 59 | There is also [this integration test](keycloak/src/test/java/com/avast/grpc/jwt/keycloak/KeycloakTest.java) that can serve as nice example. 60 | 61 | ## Implementation notes 62 | 63 | On the client side, there is implementation of `CallCredentials` that ensures the JWT token is correctly stored to the headers. Just call a static method on [JwtCallCredentials](core/src/main/java/com/avast/grpc/jwt/client/JwtCallCredentials.java) - it will require an instance of a _JwtTokenProvider_ (an interface that returns encoded JWT). 64 | 65 | On server side, there is `ServerInterceptor` implementation that parses the incoming JWT and verifies it. [JwtServerInterceptor](core/src/main/java/com/avast/grpc/jwt/server/JwtServerInterceptor.java) requires an instance of [JwtTokenParser](core/src/main/java/com/avast/grpc/jwt/server/JwtTokenParser.java) - it's an interface that parses and verifies the JWT. 66 | 67 | ## About gRPC internals 68 | gRCP uses terms `Metadata` and `Context keys`. `Metadata` is set of key-value pairs that are transported between client and server, et vice versa. So it's like HTTP headers. 69 | 70 | On other hand, `Context key` is set of values that are available during request processing. 71 | By default, a `Storage` implementation based on `ThreadLocal` is used. 72 | Thanks to this, you can just call `get()` method on a Context key and you immediately get the value because it read the value from `Context.current()`. 73 | 74 | So when implementing interceptors, you must be sure that you read Context values from the right thread. It's actually no issue for us because: 75 | 1. The right thread is automatically handled by gRPC-core when using`CallCredentials`. So you can call `applier.apply()` method on any thread. 76 | 2. Our `ServerInterceptor` implementation handles it correctly. 77 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | 118 | 119 | # Determine the Java command to use to start the JVM. 120 | if [ -n "$JAVA_HOME" ] ; then 121 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 122 | # IBM's JDK on AIX uses strange locations for the executables 123 | JAVACMD=$JAVA_HOME/jre/sh/java 124 | else 125 | JAVACMD=$JAVA_HOME/bin/java 126 | fi 127 | if [ ! -x "$JAVACMD" ] ; then 128 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 129 | 130 | Please set the JAVA_HOME variable in your environment to match the 131 | location of your Java installation." 132 | fi 133 | else 134 | JAVACMD=java 135 | if ! command -v java >/dev/null 2>&1 136 | then 137 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 138 | 139 | Please set the JAVA_HOME variable in your environment to match the 140 | location of your Java installation." 141 | fi 142 | fi 143 | 144 | # Increase the maximum file descriptors if we can. 145 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 146 | case $MAX_FD in #( 147 | max*) 148 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 149 | # shellcheck disable=SC2039,SC3045 150 | MAX_FD=$( ulimit -H -n ) || 151 | warn "Could not query maximum file descriptor limit" 152 | esac 153 | case $MAX_FD in #( 154 | '' | soft) :;; #( 155 | *) 156 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 157 | # shellcheck disable=SC2039,SC3045 158 | ulimit -n "$MAX_FD" || 159 | warn "Could not set maximum file descriptor limit to $MAX_FD" 160 | esac 161 | fi 162 | 163 | # Collect all arguments for the java command, stacking in reverse order: 164 | # * args from the command line 165 | # * the main class name 166 | # * -classpath 167 | # * -D...appname settings 168 | # * --module-path (only if needed) 169 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 170 | 171 | # For Cygwin or MSYS, switch paths to Windows format before running java 172 | if "$cygwin" || "$msys" ; then 173 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ 214 | "$@" 215 | 216 | # Stop when "xargs" is not available. 217 | if ! command -v xargs >/dev/null 2>&1 218 | then 219 | die "xargs is not available" 220 | fi 221 | 222 | # Use "xargs" to parse quoted args. 223 | # 224 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 225 | # 226 | # In Bash we could simply go: 227 | # 228 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 229 | # set -- "${ARGS[@]}" "$@" 230 | # 231 | # but POSIX shell has neither arrays nor command substitution, so instead we 232 | # post-process each arg (as a line of input to sed) to backslash-escape any 233 | # character that might be a shell metacharacter, then use eval to reverse 234 | # that process (while maintaining the separation between arguments), and wrap 235 | # the whole thing up as a single "set" statement. 236 | # 237 | # This will of course break if any of these variables contains a newline or 238 | # an unmatched quote. 239 | # 240 | 241 | eval "set -- $( 242 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 243 | xargs -n1 | 244 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 245 | tr '\n' ' ' 246 | )" '"$@"' 247 | 248 | exec "$JAVACMD" "$@" 249 | --------------------------------------------------------------------------------