or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

adc.mdasync.mdcrypt.mdexternal-accounts.mdindex.mdjwt.mdoauth2-users.mdservice-accounts.mdtransport.md

jwt.mddocs/

0

# JWT Credentials

1

2

JSON Web Token-based authentication for service-to-service communication without OAuth2 flows. JWT credentials provide efficient authentication by creating self-signed tokens that can be verified without server-side validation.

3

4

## Capabilities

5

6

### JWT Credentials

7

8

Self-signed JWT authentication for direct API access without OAuth2 token exchange.

9

10

```python { .api }

11

class Credentials(

12

google.auth.credentials.Signing,

13

google.auth.credentials.CredentialsWithQuotaProject

14

):

15

"""JWT-based credentials for service authentication."""

16

17

def __init__(

18

self,

19

signer,

20

issuer,

21

subject,

22

audience,

23

additional_claims=None,

24

**kwargs

25

):

26

"""

27

Initialize JWT credentials.

28

29

Args:

30

signer (google.auth.crypt.Signer): The signer used to sign JWTs

31

issuer (str): The issuer claim (typically service account email)

32

subject (str): The subject claim (typically service account email)

33

audience (str): The audience claim (typically the API endpoint)

34

additional_claims (Mapping[str, str]): Additional JWT claims

35

"""

36

37

@classmethod

38

def from_service_account_file(

39

cls,

40

filename,

41

audience,

42

**kwargs

43

):

44

"""

45

Create JWT credentials from service account file.

46

47

Args:

48

filename (str): Path to service account JSON file

49

audience (str): The intended audience for the JWT

50

**kwargs: Additional arguments to pass to the constructor

51

52

Returns:

53

Credentials: The constructed JWT credentials

54

"""

55

56

@classmethod

57

def from_service_account_info(

58

cls,

59

info,

60

audience,

61

**kwargs

62

):

63

"""

64

Create JWT credentials from service account info.

65

66

Args:

67

info (Mapping[str, str]): Service account info in JSON format

68

audience (str): The intended audience for the JWT

69

**kwargs: Additional arguments to pass to the constructor

70

71

Returns:

72

Credentials: The constructed JWT credentials

73

"""

74

75

def with_claims(self, issuer=None, subject=None, audience=None, **additional_claims):

76

"""

77

Create a copy with modified claims.

78

79

Args:

80

issuer (str): The issuer claim

81

subject (str): The subject claim

82

audience (str): The audience claim

83

**additional_claims: Additional claims to include

84

85

Returns:

86

Credentials: A new JWT credentials instance

87

"""

88

```

89

90

Usage example:

91

92

```python

93

from google.auth import jwt

94

95

# Create JWT credentials for specific audience

96

credentials = jwt.Credentials.from_service_account_file(

97

'/path/to/service-account.json',

98

audience='https://example.googleapis.com/'

99

)

100

101

# With additional claims

102

credentials = jwt.Credentials.from_service_account_info(

103

service_account_info,

104

audience='https://example.googleapis.com/',

105

additional_claims={'custom_claim': 'value', 'scope': 'read'}

106

)

107

108

# Modify claims

109

credentials = credentials.with_claims(

110

audience='https://different.googleapis.com/',

111

role='admin'

112

)

113

```

114

115

### On-Demand JWT Credentials

116

117

JWT credentials that generate tokens on-demand rather than pre-generating them, useful for dynamic claim generation.

118

119

```python { .api }

120

class OnDemandCredentials(google.auth.credentials.Credentials):

121

"""On-demand JWT credentials that generate tokens when needed."""

122

123

def __init__(

124

self,

125

signer,

126

issuer,

127

subject,

128

audience,

129

additional_claims=None,

130

**kwargs

131

):

132

"""

133

Initialize on-demand JWT credentials.

134

135

Args:

136

signer (google.auth.crypt.Signer): The signer used to sign JWTs

137

issuer (str): The issuer claim

138

subject (str): The subject claim

139

audience (str): The audience claim

140

additional_claims (Mapping[str, str]): Additional JWT claims

141

"""

142

143

@classmethod

144

def from_service_account_file(

145

cls,

146

filename,

147

audience,

148

**kwargs

149

):

150

"""

151

Create on-demand JWT credentials from service account file.

152

153

Args:

154

filename (str): Path to service account JSON file

155

audience (str): The intended audience for the JWT

156

**kwargs: Additional arguments

157

158

Returns:

159

OnDemandCredentials: The constructed credentials

160

"""

161

```

162

163

### JWT Token Operations

164

165

Low-level JWT encoding and decoding utilities for custom JWT implementations.

166

167

```python { .api }

168

def encode(signer, payload, header=None, key_id=None):

169

"""

170

Encode a JWT token.

171

172

Args:

173

signer (google.auth.crypt.Signer): The signer used to sign the JWT

174

payload (Mapping[str, Any]): The JWT payload claims

175

header (Mapping[str, str]): Additional JWT header fields

176

key_id (str): Key ID to add to JWT header (overrides signer key_id)

177

178

Returns:

179

bytes: The encoded JWT token

180

181

Raises:

182

ValueError: If the signer or payload is invalid

183

"""

184

185

def decode(token, certs=None, verify=True, audience=None, clock_skew_in_seconds=0):

186

"""

187

Decode and verify a JWT token.

188

189

Args:

190

token (str): The encoded JWT

191

certs (Union[str, bytes, Mapping[str, Union[str, bytes]]]): Certificate used to validate JWT signature

192

verify (bool): Whether to perform signature and claim validation

193

audience (Union[str, list]): The audience claim that this JWT should contain

194

clock_skew_in_seconds (int): The number of seconds of clock skew to tolerate

195

196

Returns:

197

Mapping[str, str]: Decoded JWT payload

198

199

Raises:

200

ValueError: If the token is invalid or verification fails

201

"""

202

203

def decode_header(token):

204

"""

205

Decode JWT header without verification.

206

207

Args:

208

token (Union[str, bytes]): The JWT token

209

210

Returns:

211

Mapping[str, str]: The JWT header

212

"""

213

```

214

215

Usage example:

216

217

```python

218

from google.auth import jwt

219

import json

220

221

# Load service account key

222

with open('/path/to/service-account.json') as f:

223

key_data = json.load(f)

224

225

private_key = key_data['private_key']

226

service_account_email = key_data['client_email']

227

228

# Create signer from private key

229

from google.auth import crypt

230

signer = crypt.RSASigner.from_string(private_key, key_id='key-1')

231

232

# Create JWT payload

233

import time

234

now = int(time.time())

235

payload = {

236

'iss': service_account_email,

237

'sub': service_account_email,

238

'aud': 'https://example.googleapis.com/',

239

'iat': now,

240

'exp': now + 3600, # 1 hour expiry

241

'custom_claim': 'value'

242

}

243

244

# Encode JWT

245

token = jwt.encode(signer, payload)

246

print(f"JWT: {token.decode('utf-8')}")

247

248

# Decode JWT (for verification)

249

public_key = get_public_key() # Get corresponding public key

250

decoded_payload = jwt.decode(

251

token,

252

public_key,

253

audience='https://example.googleapis.com/'

254

)

255

print(f"Decoded: {decoded_payload}")

256

```

257

258

### JWT Async Support

259

260

Async versions of JWT credentials for non-blocking token generation.

261

262

```python { .api }

263

class Credentials(google.auth.credentials.Credentials):

264

"""Async JWT credentials."""

265

266

async def refresh(self, request):

267

"""

268

Async refresh of JWT token.

269

270

Args:

271

request (google.auth.transport.Request): Async HTTP transport

272

"""

273

```

274

275

## JWT Claims

276

277

Standard and custom JWT claims supported by Google Auth:

278

279

```python { .api }

280

JWTClaims = TypedDict('JWTClaims', {

281

'iss': str, # Issuer (service account email)

282

'sub': str, # Subject (service account email)

283

'aud': str, # Audience (API endpoint)

284

'iat': int, # Issued at time (Unix timestamp)

285

'exp': int, # Expiration time (Unix timestamp)

286

'scope': str, # Space-delimited scopes (optional)

287

'target_audience': str, # Target audience for ID tokens (optional)

288

}, total=False)

289

```

290

291

## Error Handling

292

293

```python { .api }

294

class MalformedError(google.auth.exceptions.GoogleAuthError):

295

"""Raised when JWT data is malformed."""

296

297

class RefreshError(google.auth.exceptions.GoogleAuthError):

298

"""Raised when JWT refresh fails."""

299

```

300

301

Common JWT error scenarios:

302

- Invalid or malformed JWT structure

303

- JWT signature verification failures

304

- Expired JWT tokens

305

- Invalid audience or issuer claims

306

- Missing required claims (iss, sub, aud, exp)

307

- Unsupported JWT algorithms

308

- Invalid private key format for signing