0
# Service Account Credentials
1
2
Server-to-server authentication using service account keys and JWT tokens. Service accounts are Google accounts associated with your application or compute instance, enabling applications to authenticate and make API calls on their own behalf.
3
4
## Capabilities
5
6
### OAuth2 Service Account Credentials
7
8
Standard OAuth2 flow using service account keys, supporting token refresh and scope-based access control.
9
10
```python { .api }
11
class Credentials(
12
google.auth.credentials.Scoped,
13
google.auth.credentials.CredentialsWithQuotaProject
14
):
15
"""Service account credentials for OAuth2 authentication."""
16
17
def __init__(
18
self,
19
signer,
20
service_account_email,
21
token_uri,
22
scopes=None,
23
default_scopes=None,
24
subject=None,
25
project_id=None,
26
quota_project_id=None,
27
additional_claims=None,
28
always_use_jwt_access=False,
29
universe_domain=google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN,
30
trust_boundary=None,
31
**kwargs
32
):
33
"""
34
Initialize service account credentials.
35
36
Args:
37
signer (google.auth.crypt.Signer): The signer used to sign JWTs
38
service_account_email (str): The service account email address
39
token_uri (str): The OAuth 2.0 authorization server's token endpoint URI
40
scopes (Sequence[str]): User-defined scopes to request
41
default_scopes (Sequence[str]): Default scopes passed by client libraries
42
subject (str): For domain-wide delegation, the email address of the user to impersonate
43
project_id (str): The project ID associated with the service account
44
quota_project_id (str): The project for quota and billing
45
additional_claims (Mapping[str, str]): Any additional claims for the JWT assertion
46
always_use_jwt_access (bool): Whether to always use JWT access tokens
47
universe_domain (str): The STS audience which contains the resource name
48
trust_boundary (str): String representation of trust boundary meta
49
"""
50
51
@classmethod
52
def from_service_account_file(
53
cls,
54
filename,
55
**kwargs
56
):
57
"""
58
Create credentials from a service account JSON file.
59
60
Args:
61
filename (str): Path to the service account JSON file
62
**kwargs: Additional arguments to pass to the constructor
63
64
Returns:
65
Credentials: The constructed credentials
66
"""
67
68
@classmethod
69
def from_service_account_info(
70
cls,
71
info,
72
**kwargs
73
):
74
"""
75
Create credentials from service account info dictionary.
76
77
Args:
78
info (Mapping[str, str]): The service account info in JSON format
79
**kwargs: Additional arguments to pass to the constructor
80
81
Returns:
82
Credentials: The constructed credentials
83
"""
84
85
def with_scopes(self, scopes):
86
"""
87
Create a copy of these credentials with specified scopes.
88
89
Args:
90
scopes (Sequence[str]): The list of scopes to attach
91
92
Returns:
93
Credentials: A new credentials instance
94
"""
95
96
def with_quota_project(self, quota_project_id):
97
"""
98
Create a copy with a specified quota project ID.
99
100
Args:
101
quota_project_id (str): The project for quota and billing
102
103
Returns:
104
Credentials: A new credentials instance
105
"""
106
```
107
108
Usage example:
109
110
```python
111
from google.oauth2 import service_account
112
113
# From JSON file
114
credentials = service_account.Credentials.from_service_account_file(
115
'/path/to/service-account.json',
116
scopes=['https://www.googleapis.com/auth/cloud-platform']
117
)
118
119
# From info dictionary
120
import json
121
with open('/path/to/service-account.json') as f:
122
info = json.load(f)
123
124
credentials = service_account.Credentials.from_service_account_info(
125
info,
126
scopes=['https://www.googleapis.com/auth/bigquery']
127
)
128
129
# Add quota project
130
credentials = credentials.with_quota_project('my-billing-project')
131
```
132
133
### JWT Service Account Credentials
134
135
Self-signed JWT authentication without OAuth2 flows, more efficient for service-to-service communication.
136
137
```python { .api }
138
class Credentials(
139
google.auth.credentials.Signing,
140
google.auth.credentials.CredentialsWithQuotaProject
141
):
142
"""JWT-based service account credentials."""
143
144
def __init__(
145
self,
146
signer,
147
issuer,
148
subject,
149
audience,
150
additional_claims=None,
151
**kwargs
152
):
153
"""
154
Initialize JWT credentials.
155
156
Args:
157
signer (google.auth.crypt.Signer): The signer used to sign JWTs
158
issuer (str): The issuer claim (typically service account email)
159
subject (str): The subject claim (typically service account email)
160
audience (str): The audience claim (typically the API endpoint)
161
additional_claims (Mapping[str, str]): Additional JWT claims
162
"""
163
164
@classmethod
165
def from_service_account_file(
166
cls,
167
filename,
168
audience,
169
**kwargs
170
):
171
"""
172
Create JWT credentials from service account file.
173
174
Args:
175
filename (str): Path to service account JSON file
176
audience (str): The STS audience which is usually the fully specified
177
resource name of the workload identity pool
178
**kwargs: Additional arguments to pass to the constructor
179
180
Returns:
181
Credentials: The constructed JWT credentials
182
"""
183
184
@classmethod
185
def from_service_account_info(
186
cls,
187
info,
188
audience,
189
**kwargs
190
):
191
"""
192
Create JWT credentials from service account info.
193
194
Args:
195
info (Mapping[str, str]): The service account info in JSON format
196
audience (str): The intended audience for the JWT
197
**kwargs: Additional arguments to pass to the constructor
198
199
Returns:
200
Credentials: The constructed JWT credentials
201
"""
202
```
203
204
Usage example:
205
206
```python
207
from google.auth import jwt
208
209
# Create JWT credentials for specific audience
210
credentials = jwt.Credentials.from_service_account_file(
211
'/path/to/service-account.json',
212
audience='https://example.googleapis.com/'
213
)
214
215
# With additional claims
216
credentials = jwt.Credentials.from_service_account_info(
217
service_account_info,
218
audience='https://example.googleapis.com/',
219
additional_claims={'custom_claim': 'value'}
220
)
221
```
222
223
### GDCH Service Account Credentials
224
225
Google Distributed Cloud Hosted (GDCH) service account credentials for private cloud environments.
226
227
```python { .api }
228
class ServiceAccountCredentials(google.auth.credentials.Credentials):
229
"""GDCH service account credentials."""
230
231
def __init__(
232
self,
233
signer,
234
issuer,
235
subject,
236
audience,
237
ca_cert_path,
238
token_endpoint,
239
**kwargs
240
):
241
"""
242
Initialize GDCH service account credentials.
243
244
Args:
245
signer (google.auth.crypt.Signer): The signer used to sign JWTs
246
issuer (str): The issuer claim
247
subject (str): The subject claim
248
audience (str): The STS audience
249
ca_cert_path (str): Path to CA certificate for TLS verification
250
token_endpoint (str): The STS token endpoint
251
"""
252
253
@classmethod
254
def from_service_account_file(
255
cls,
256
filename,
257
audience,
258
ca_cert_path,
259
token_endpoint,
260
**kwargs
261
):
262
"""
263
Create GDCH credentials from service account file.
264
265
Args:
266
filename (str): Path to service account JSON file
267
audience (str): The STS audience
268
ca_cert_path (str): Path to CA certificate file
269
token_endpoint (str): The STS token endpoint
270
**kwargs: Additional arguments
271
272
Returns:
273
ServiceAccountCredentials: The constructed GDCH credentials
274
"""
275
```
276
277
## Service Account Key Format
278
279
Service account JSON keys contain the following fields:
280
281
```python { .api }
282
ServiceAccountInfo = TypedDict('ServiceAccountInfo', {
283
'type': str, # Always "service_account"
284
'project_id': str, # The Google Cloud project ID
285
'private_key_id': str, # Key ID for the private key
286
'private_key': str, # RSA private key in PEM format
287
'client_email': str, # Service account email address
288
'client_id': str, # Numeric client ID
289
'auth_uri': str, # OAuth2 authorization endpoint
290
'token_uri': str, # OAuth2 token endpoint
291
'auth_provider_x509_cert_url': str, # Provider cert URL
292
'client_x509_cert_url': str, # Client cert URL
293
'universe_domain': str # Universe domain (optional)
294
})
295
```
296
297
## Error Handling
298
299
```python { .api }
300
class RefreshError(google.auth.exceptions.GoogleAuthError):
301
"""Raised when credentials cannot be refreshed."""
302
303
class MalformedError(google.auth.exceptions.GoogleAuthError):
304
"""Raised when credential data is malformed."""
305
```
306
307
Common error scenarios:
308
- Invalid or malformed service account key file
309
- Network issues during token refresh
310
- Invalid scopes for the service account
311
- Expired or revoked service account keys
312
- Insufficient permissions for requested operations