Search code examples
authenticationgrpcservice-accountsgoogle-cloud-rungrpc-java

Cloud Run - gRPC authentication through service account - Java


I've deployed to Google Cloud Run (fully managed) a gRPC server with the option "Required Authentication" set to true.

I'm trying to authenticate the calls from my gRPC client through a Google Service Account, however I'm always getting below exception.

Exception in thread "main" io.grpc.StatusRuntimeException: UNAUTHENTICATED: HTTP status code 401

Below is how I'm creating the gRPC channel and attaching the service account.

public GrpcClient(Channel channel) throws IOException {
    Credentials credentials = GoogleCredentials.getApplicationDefault();

    blockingStub = CalculatorServiceGrpc
            .newBlockingStub(channel)
            .withCallCredentials(MoreCallCredentials.from(credentials));
}

Obs.: env var GOOGLE_APPLICATION_CREDENTIALS is set with the path of the SA, and the SA has Cloud Run Invoker privilege

Is there anything that I'm missing?


Solution

  • After some more research I was able to authenticate the requests using IdTokenCredentials. See below the result.

    public GrpcClient(Channel channel) throws IOException {
        ServiceAccountCredentials saCreds = ServiceAccountCredentials
                .fromStream(new FileInputStream("path\to\sa"));
    
        IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder().setIdTokenProvider(saCreds)
                .setTargetAudience("https://{projectId}-{hash}-uc.a.run.app").build();
    
        blockingStub = CalculatorServiceGrpc
                .newBlockingStub(channel)
                .withCallCredentials(MoreCallCredentials.from(tokenCredential));
    }