or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/maven-io-grpc--grpc-auth

Authentication capabilities for gRPC Java applications with Google Auth Library integration.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/io.grpc/grpc-auth@1.73.x

To install, run

npx @tessl/cli install tessl/maven-io-grpc--grpc-auth@1.73.0

index.mddocs/

gRPC Auth

gRPC Auth provides authentication capabilities for gRPC Java applications by integrating with Google Auth Library for Java. It implements the CallCredentials interface to enable OAuth2, JWT, and other authentication mechanisms for secure gRPC communications.

Package Information

  • Package Name: io.grpc:grpc-auth
  • Package Type: Maven
  • Language: Java
  • Installation:
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-auth</artifactId>
      <version>1.73.0</version>
    </dependency>

Core Imports

import io.grpc.auth.MoreCallCredentials;
import io.grpc.CallCredentials;
import com.google.auth.Credentials;
import com.google.auth.oauth2.GoogleCredentials;

Basic Usage

import io.grpc.auth.MoreCallCredentials;
import io.grpc.CallCredentials;
import com.google.auth.oauth2.GoogleCredentials;

// Create credentials using Google Auth Library
Credentials credentials = GoogleCredentials.getApplicationDefault();

// Convert to gRPC CallCredentials
CallCredentials callCredentials = MoreCallCredentials.from(credentials);

// Attach to gRPC stub for authenticated calls
MyServiceGrpc.MyServiceBlockingStub stub = MyServiceGrpc.newBlockingStub(channel)
    .withCallCredentials(callCredentials);

// Make authenticated gRPC calls
MyResponse response = stub.myMethod(MyRequest.newBuilder().build());

Architecture

gRPC Auth is built around a simple but powerful architecture:

  • MoreCallCredentials: Primary utility class providing factory methods for converting Google Auth Library credentials
  • GoogleAuthLibraryCallCredentials: Internal implementation that handles the actual credential application
  • JWT Optimization: Automatic conversion of ServiceAccount credentials to JWT when no scopes are present
  • Security Enforcement: Ensures appropriate security levels for different credential types
  • Metadata Caching: Optimizes performance by caching authentication metadata

Capabilities

CallCredentials Factory

Primary factory method for creating gRPC CallCredentials from Google Auth Library credentials.

/**
 * Utility class that converts other types of credentials to CallCredentials
 */
public final class MoreCallCredentials {
    /**
     * Converts a Google Auth Library Credentials to CallCredentials.
     * 
     * Although this is a stable API, note that the returned instance's API is not stable.
     * You are free to use the class name CallCredentials and pass the instance to other code,
     * but the instance can't be called directly from code expecting stable behavior.
     *
     * @param creds Google Auth Library credentials to convert
     * @return CallCredentials instance suitable for gRPC calls
     */
    public static CallCredentials from(Credentials creds);
}

Usage Examples:

import io.grpc.auth.MoreCallCredentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;

// Using Application Default Credentials
Credentials appDefaultCreds = GoogleCredentials.getApplicationDefault();
CallCredentials callCreds = MoreCallCredentials.from(appDefaultCreds);

// Using Service Account Credentials from file
FileInputStream serviceAccountStream = new FileInputStream("path/to/service-account.json");
ServiceAccountCredentials serviceAccountCreds = ServiceAccountCredentials
    .fromStream(serviceAccountStream);
CallCredentials callCreds = MoreCallCredentials.from(serviceAccountCreds);

// Using OAuth2 Credentials with specific scopes
GoogleCredentials scopedCreds = GoogleCredentials.getApplicationDefault()
    .createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
CallCredentials callCreds = MoreCallCredentials.from(scopedCreds);

Legacy Client Interceptor (Deprecated)

Legacy authentication interceptor that was the original method for adding authentication to gRPC calls.

/**
 * Client interceptor that authenticates all calls by binding header data provided by a credential.
 * Typically this will populate the Authorization header but other headers may also be filled out.
 *
 * @deprecated use MoreCallCredentials.from(Credentials) instead.
 */
@Deprecated
public final class ClientAuthInterceptor implements ClientInterceptor {
    /**
     * Creates a client interceptor that authenticates all calls
     *
     * @param credentials Google Auth Library credentials
     * @param executor Executor for async operations (currently unused)
     */
    public ClientAuthInterceptor(Credentials credentials, Executor executor);

    /**
     * Implements ClientInterceptor interface to add authentication headers
     *
     * @param method Method being called
     * @param callOptions Call options
     * @param next Next channel in the chain
     * @return Authenticated ClientCall instance
     */
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        MethodDescriptor<ReqT, RespT> method,
        CallOptions callOptions,
        Channel next);
}

Migration Example:

// Old approach (deprecated)
Credentials credentials = GoogleCredentials.getApplicationDefault();
ClientInterceptor interceptor = new ClientAuthInterceptor(credentials, executor);
Channel authenticatedChannel = ClientInterceptors.intercept(channel, interceptor);
MyServiceGrpc.MyServiceBlockingStub stub = MyServiceGrpc.newBlockingStub(authenticatedChannel);

// New approach (recommended)
Credentials credentials = GoogleCredentials.getApplicationDefault();
CallCredentials callCredentials = MoreCallCredentials.from(credentials);
MyServiceGrpc.MyServiceBlockingStub stub = MyServiceGrpc.newBlockingStub(channel)
    .withCallCredentials(callCredentials);

Types and Dependencies

// Core gRPC types
import io.grpc.CallCredentials;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.CallOptions;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import io.grpc.StatusException;

// Google Auth Library types
import com.google.auth.Credentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.auth.oauth2.OAuth2Credentials;

// Standard Java types
import java.util.concurrent.Executor;
import java.util.List;
import java.util.Map;
import java.net.URI;

Authentication Flow

The authentication process follows these steps:

  1. Credential Creation: Use Google Auth Library to create appropriate credentials (OAuth2, ServiceAccount, etc.)
  2. CallCredentials Conversion: Use MoreCallCredentials.from() to convert to gRPC-compatible format
  3. Stub Configuration: Attach CallCredentials to gRPC stub using withCallCredentials()
  4. Automatic Application: gRPC automatically applies authentication headers to each RPC call
  5. JWT Optimization: ServiceAccount credentials without scopes are automatically converted to JWT tokens
  6. Security Validation: Credentials requiring privacy enforce PRIVACY_AND_INTEGRITY security level

Authentication Features

Supported Credential Types

  • Google Application Default Credentials: Automatically discovered credentials from environment
  • Service Account Credentials: JSON key file or in-memory credentials for service-to-service auth
  • OAuth2 Credentials: User credentials with access tokens and refresh tokens
  • JWT Credentials: Self-signed JWT tokens for service accounts (automatically optimized)
  • App Engine Credentials: Specialized credentials for Google App Engine environment

Security Features

  • Automatic Security Level Enforcement: Google credentials require PRIVACY_AND_INTEGRITY channels
  • JWT Token Optimization: ServiceAccount credentials without scopes use JWT instead of OAuth2
  • Metadata Caching: Avoids redundant authentication requests through intelligent caching
  • Thread Safety: Safe for concurrent use across multiple threads
  • Error Propagation: Authentication failures are properly reported as UNAUTHENTICATED status

Performance Optimizations

  • Credential Metadata Caching: Reuses authentication metadata when possible
  • JWT Preference: Uses more efficient JWT tokens over OAuth2 when appropriate
  • Lazy Evaluation: Authentication occurs only when RPC calls are made
  • Header Reuse: Caches parsed authentication headers to avoid repeated parsing

Error Handling

Authentication errors are reported through gRPC's standard error handling:

try {
    MyResponse response = stub.myMethod(request);
} catch (StatusRuntimeException e) {
    if (e.getStatus().getCode() == Status.Code.UNAUTHENTICATED) {
        // Handle authentication failure
        System.err.println("Authentication failed: " + e.getStatus().getDescription());
    }
}

Common error scenarios:

  • UNAUTHENTICATED: Invalid credentials, expired tokens, or credential loading failures
  • UNAVAILABLE: Temporary authentication service issues (retryable)
  • PERMISSION_DENIED: Valid credentials but insufficient permissions for the operation
  • InvalidChannel: Attempting to use privacy-requiring credentials on insecure channels

Thread Safety and Executors

All authentication components are thread-safe and can be used concurrently:

  • CallCredentials: Thread-safe and can be shared across multiple stubs
  • Metadata Caching: Uses synchronization to ensure thread-safe cache access
  • App Engine Support: Special executor handling for App Engine credentials when required
  • Async Operations: Credential fetching is performed asynchronously without blocking RPC calls