Authentication capabilities for gRPC Java applications with Google Auth Library integration.
npx @tessl/cli install tessl/maven-io-grpc--grpc-auth@1.73.00
# gRPC Auth
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: io.grpc:grpc-auth
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**:
10
```xml
11
<dependency>
12
<groupId>io.grpc</groupId>
13
<artifactId>grpc-auth</artifactId>
14
<version>1.73.0</version>
15
</dependency>
16
```
17
18
## Core Imports
19
20
```java
21
import io.grpc.auth.MoreCallCredentials;
22
import io.grpc.CallCredentials;
23
import com.google.auth.Credentials;
24
import com.google.auth.oauth2.GoogleCredentials;
25
```
26
27
## Basic Usage
28
29
```java
30
import io.grpc.auth.MoreCallCredentials;
31
import io.grpc.CallCredentials;
32
import com.google.auth.oauth2.GoogleCredentials;
33
34
// Create credentials using Google Auth Library
35
Credentials credentials = GoogleCredentials.getApplicationDefault();
36
37
// Convert to gRPC CallCredentials
38
CallCredentials callCredentials = MoreCallCredentials.from(credentials);
39
40
// Attach to gRPC stub for authenticated calls
41
MyServiceGrpc.MyServiceBlockingStub stub = MyServiceGrpc.newBlockingStub(channel)
42
.withCallCredentials(callCredentials);
43
44
// Make authenticated gRPC calls
45
MyResponse response = stub.myMethod(MyRequest.newBuilder().build());
46
```
47
48
## Architecture
49
50
gRPC Auth is built around a simple but powerful architecture:
51
52
- **MoreCallCredentials**: Primary utility class providing factory methods for converting Google Auth Library credentials
53
- **GoogleAuthLibraryCallCredentials**: Internal implementation that handles the actual credential application
54
- **JWT Optimization**: Automatic conversion of ServiceAccount credentials to JWT when no scopes are present
55
- **Security Enforcement**: Ensures appropriate security levels for different credential types
56
- **Metadata Caching**: Optimizes performance by caching authentication metadata
57
58
## Capabilities
59
60
### CallCredentials Factory
61
62
Primary factory method for creating gRPC CallCredentials from Google Auth Library credentials.
63
64
```java { .api }
65
/**
66
* Utility class that converts other types of credentials to CallCredentials
67
*/
68
public final class MoreCallCredentials {
69
/**
70
* Converts a Google Auth Library Credentials to CallCredentials.
71
*
72
* Although this is a stable API, note that the returned instance's API is not stable.
73
* You are free to use the class name CallCredentials and pass the instance to other code,
74
* but the instance can't be called directly from code expecting stable behavior.
75
*
76
* @param creds Google Auth Library credentials to convert
77
* @return CallCredentials instance suitable for gRPC calls
78
*/
79
public static CallCredentials from(Credentials creds);
80
}
81
```
82
83
**Usage Examples:**
84
85
```java
86
import io.grpc.auth.MoreCallCredentials;
87
import com.google.auth.oauth2.GoogleCredentials;
88
import com.google.auth.oauth2.ServiceAccountCredentials;
89
90
// Using Application Default Credentials
91
Credentials appDefaultCreds = GoogleCredentials.getApplicationDefault();
92
CallCredentials callCreds = MoreCallCredentials.from(appDefaultCreds);
93
94
// Using Service Account Credentials from file
95
FileInputStream serviceAccountStream = new FileInputStream("path/to/service-account.json");
96
ServiceAccountCredentials serviceAccountCreds = ServiceAccountCredentials
97
.fromStream(serviceAccountStream);
98
CallCredentials callCreds = MoreCallCredentials.from(serviceAccountCreds);
99
100
// Using OAuth2 Credentials with specific scopes
101
GoogleCredentials scopedCreds = GoogleCredentials.getApplicationDefault()
102
.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
103
CallCredentials callCreds = MoreCallCredentials.from(scopedCreds);
104
```
105
106
### Legacy Client Interceptor (Deprecated)
107
108
Legacy authentication interceptor that was the original method for adding authentication to gRPC calls.
109
110
```java { .api }
111
/**
112
* Client interceptor that authenticates all calls by binding header data provided by a credential.
113
* Typically this will populate the Authorization header but other headers may also be filled out.
114
*
115
* @deprecated use MoreCallCredentials.from(Credentials) instead.
116
*/
117
@Deprecated
118
public final class ClientAuthInterceptor implements ClientInterceptor {
119
/**
120
* Creates a client interceptor that authenticates all calls
121
*
122
* @param credentials Google Auth Library credentials
123
* @param executor Executor for async operations (currently unused)
124
*/
125
public ClientAuthInterceptor(Credentials credentials, Executor executor);
126
127
/**
128
* Implements ClientInterceptor interface to add authentication headers
129
*
130
* @param method Method being called
131
* @param callOptions Call options
132
* @param next Next channel in the chain
133
* @return Authenticated ClientCall instance
134
*/
135
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
136
MethodDescriptor<ReqT, RespT> method,
137
CallOptions callOptions,
138
Channel next);
139
}
140
```
141
142
**Migration Example:**
143
144
```java
145
// Old approach (deprecated)
146
Credentials credentials = GoogleCredentials.getApplicationDefault();
147
ClientInterceptor interceptor = new ClientAuthInterceptor(credentials, executor);
148
Channel authenticatedChannel = ClientInterceptors.intercept(channel, interceptor);
149
MyServiceGrpc.MyServiceBlockingStub stub = MyServiceGrpc.newBlockingStub(authenticatedChannel);
150
151
// New approach (recommended)
152
Credentials credentials = GoogleCredentials.getApplicationDefault();
153
CallCredentials callCredentials = MoreCallCredentials.from(credentials);
154
MyServiceGrpc.MyServiceBlockingStub stub = MyServiceGrpc.newBlockingStub(channel)
155
.withCallCredentials(callCredentials);
156
```
157
158
## Types and Dependencies
159
160
```java { .api }
161
// Core gRPC types
162
import io.grpc.CallCredentials;
163
import io.grpc.Channel;
164
import io.grpc.ClientCall;
165
import io.grpc.ClientInterceptor;
166
import io.grpc.CallOptions;
167
import io.grpc.MethodDescriptor;
168
import io.grpc.Status;
169
import io.grpc.StatusException;
170
171
// Google Auth Library types
172
import com.google.auth.Credentials;
173
import com.google.auth.oauth2.GoogleCredentials;
174
import com.google.auth.oauth2.ServiceAccountCredentials;
175
import com.google.auth.oauth2.OAuth2Credentials;
176
177
// Standard Java types
178
import java.util.concurrent.Executor;
179
import java.util.List;
180
import java.util.Map;
181
import java.net.URI;
182
```
183
184
## Authentication Flow
185
186
The authentication process follows these steps:
187
188
1. **Credential Creation**: Use Google Auth Library to create appropriate credentials (OAuth2, ServiceAccount, etc.)
189
2. **CallCredentials Conversion**: Use `MoreCallCredentials.from()` to convert to gRPC-compatible format
190
3. **Stub Configuration**: Attach CallCredentials to gRPC stub using `withCallCredentials()`
191
4. **Automatic Application**: gRPC automatically applies authentication headers to each RPC call
192
5. **JWT Optimization**: ServiceAccount credentials without scopes are automatically converted to JWT tokens
193
6. **Security Validation**: Credentials requiring privacy enforce PRIVACY_AND_INTEGRITY security level
194
195
## Authentication Features
196
197
### Supported Credential Types
198
199
- **Google Application Default Credentials**: Automatically discovered credentials from environment
200
- **Service Account Credentials**: JSON key file or in-memory credentials for service-to-service auth
201
- **OAuth2 Credentials**: User credentials with access tokens and refresh tokens
202
- **JWT Credentials**: Self-signed JWT tokens for service accounts (automatically optimized)
203
- **App Engine Credentials**: Specialized credentials for Google App Engine environment
204
205
### Security Features
206
207
- **Automatic Security Level Enforcement**: Google credentials require PRIVACY_AND_INTEGRITY channels
208
- **JWT Token Optimization**: ServiceAccount credentials without scopes use JWT instead of OAuth2
209
- **Metadata Caching**: Avoids redundant authentication requests through intelligent caching
210
- **Thread Safety**: Safe for concurrent use across multiple threads
211
- **Error Propagation**: Authentication failures are properly reported as UNAUTHENTICATED status
212
213
### Performance Optimizations
214
215
- **Credential Metadata Caching**: Reuses authentication metadata when possible
216
- **JWT Preference**: Uses more efficient JWT tokens over OAuth2 when appropriate
217
- **Lazy Evaluation**: Authentication occurs only when RPC calls are made
218
- **Header Reuse**: Caches parsed authentication headers to avoid repeated parsing
219
220
## Error Handling
221
222
Authentication errors are reported through gRPC's standard error handling:
223
224
```java
225
try {
226
MyResponse response = stub.myMethod(request);
227
} catch (StatusRuntimeException e) {
228
if (e.getStatus().getCode() == Status.Code.UNAUTHENTICATED) {
229
// Handle authentication failure
230
System.err.println("Authentication failed: " + e.getStatus().getDescription());
231
}
232
}
233
```
234
235
Common error scenarios:
236
237
- **UNAUTHENTICATED**: Invalid credentials, expired tokens, or credential loading failures
238
- **UNAVAILABLE**: Temporary authentication service issues (retryable)
239
- **PERMISSION_DENIED**: Valid credentials but insufficient permissions for the operation
240
- **InvalidChannel**: Attempting to use privacy-requiring credentials on insecure channels
241
242
## Thread Safety and Executors
243
244
All authentication components are thread-safe and can be used concurrently:
245
246
- **CallCredentials**: Thread-safe and can be shared across multiple stubs
247
- **Metadata Caching**: Uses synchronization to ensure thread-safe cache access
248
- **App Engine Support**: Special executor handling for App Engine credentials when required
249
- **Async Operations**: Credential fetching is performed asynchronously without blocking RPC calls