0
# Authentication
1
2
PyGithub provides comprehensive authentication support for all GitHub API access patterns including personal access tokens, GitHub Apps, OAuth, and legacy authentication methods.
3
4
## Capabilities
5
6
### Personal Access Token Authentication
7
8
The most common authentication method using GitHub personal access tokens. Supports both classic and fine-grained personal access tokens.
9
10
```python { .api }
11
class Auth:
12
class Token:
13
def __init__(self, token: str):
14
"""
15
Create token-based authentication.
16
17
Args:
18
token (str): GitHub personal access token
19
"""
20
```
21
22
Usage example:
23
24
```python
25
from github import Github, Auth
26
27
# Using personal access token
28
auth = Auth.Token("your_personal_access_token")
29
g = Github(auth=auth)
30
31
# Now you can make authenticated requests
32
user = g.get_user() # Gets the authenticated user
33
print(f"Authenticated as: {user.login}")
34
```
35
36
### GitHub App Authentication
37
38
Authentication for GitHub Apps using private key or JWT tokens. Supports both app-level authentication and installation-specific authentication.
39
40
```python { .api }
41
class Auth:
42
class AppAuth:
43
def __init__(self, app_id: str, private_key: str):
44
"""
45
GitHub App authentication using private key.
46
47
Args:
48
app_id (str): GitHub App ID
49
private_key (str): Private key content or path to key file
50
"""
51
52
class AppAuthToken:
53
def __init__(self, token: str):
54
"""
55
GitHub App authentication using a single constant JWT token.
56
57
Args:
58
token (str): Pre-generated JWT token
59
"""
60
61
class AppInstallationAuth:
62
def __init__(
63
self,
64
app_auth: AppAuth,
65
installation_id: int,
66
token_permissions: dict[str, str] | None = None
67
):
68
"""
69
GitHub App installation authentication.
70
71
Args:
72
app_auth (AppAuth): GitHub App authentication object
73
installation_id (int): Installation ID
74
token_permissions (dict, optional): Requested permissions for the token
75
"""
76
77
class AppUserAuth:
78
def __init__(
79
self,
80
client_id: str,
81
client_secret: str,
82
token: str,
83
token_type: str = None,
84
expires_at: datetime = None,
85
refresh_token: str = None,
86
refresh_expires_at: datetime = None
87
):
88
"""
89
GitHub App user-to-server authentication for acting on behalf of a user.
90
91
Args:
92
client_id (str): OAuth app client ID
93
client_secret (str): OAuth app client secret
94
token (str): User access token
95
token_type (str, optional): Token type (usually "bearer")
96
expires_at (datetime, optional): Token expiration time
97
refresh_token (str, optional): Refresh token for renewing access
98
refresh_expires_at (datetime, optional): Refresh token expiration
99
"""
100
101
class NetrcAuth:
102
def __init__(self):
103
"""
104
Authentication using .netrc file credentials.
105
Automatically reads credentials from .netrc file for the GitHub hostname.
106
"""
107
```
108
109
Usage example:
110
111
```python
112
from github import Github, Auth
113
114
# App-level authentication (for app management operations)
115
app_auth = Auth.AppAuth("123456", private_key_content)
116
g = Github(auth=app_auth)
117
118
# Installation-specific authentication (for repository operations)
119
installation_auth = Auth.AppInstallationAuth(
120
installation_id=12345678,
121
app_id="123456",
122
private_key=private_key_content
123
)
124
g = Github(auth=installation_auth)
125
126
# Access repositories the app is installed on
127
for repo in g.get_installation(12345678).get_repos():
128
print(f"App has access to: {repo.full_name}")
129
```
130
131
### Additional Authentication Methods
132
133
Additional authentication methods for specialized use cases.
134
135
```python { .api }
136
# Pre-generated JWT token authentication
137
auth_token = Auth.AppAuthToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...")
138
g = Github(auth=auth_token)
139
140
# .netrc file authentication
141
netrc_auth = Auth.NetrcAuth()
142
g = Github(auth=netrc_auth)
143
```
144
145
### Legacy Authentication Methods
146
147
Legacy authentication methods maintained for backward compatibility.
148
149
```python { .api }
150
class Auth:
151
class Login:
152
def __init__(self, username: str, password: str):
153
"""
154
Username/password authentication (deprecated).
155
156
Args:
157
username (str): GitHub username
158
password (str): GitHub password or personal access token
159
"""
160
161
class NetrcAuth:
162
def __init__(self):
163
"""
164
Authentication using .netrc file credentials.
165
"""
166
```
167
168
### GitHub Integration Client
169
170
Specialized client for GitHub App integration management operations.
171
172
```python { .api }
173
class GithubIntegration:
174
def __init__(
175
self,
176
integration_id: str,
177
private_key: str,
178
base_url: str = "https://api.github.com"
179
):
180
"""
181
GitHub App integration client.
182
183
Args:
184
integration_id (str): GitHub App ID
185
private_key (str): Private key content or path
186
base_url (str): GitHub API base URL
187
"""
188
189
def get_installation(self, owner: str, repo: str = None):
190
"""
191
Get installation for owner/repo or organization.
192
193
Args:
194
owner (str): Repository owner or organization name
195
repo (str, optional): Repository name
196
197
Returns:
198
Installation: Installation object
199
"""
200
201
def get_installations(self):
202
"""
203
Get all installations for this GitHub App.
204
205
Returns:
206
PaginatedList[Installation]: List of installations
207
"""
208
209
def get_access_token(self, installation_id: int, permissions: dict = None):
210
"""
211
Get installation access token.
212
213
Args:
214
installation_id (int): Installation ID
215
permissions (dict, optional): Requested permissions
216
217
Returns:
218
InstallationAuthorization: Access token object
219
"""
220
221
def create_jwt(self, expiration: int = None):
222
"""
223
Create JWT token for app authentication.
224
225
Args:
226
expiration (int, optional): Token expiration in seconds
227
228
Returns:
229
str: JWT token
230
"""
231
```
232
233
Usage example for GitHub App integrations:
234
235
```python
236
from github import GithubIntegration
237
238
# Create integration client
239
integration = GithubIntegration("123456", private_key_content)
240
241
# Get installation for a specific repository
242
installation = integration.get_installation("owner", "repo")
243
print(f"Installation ID: {installation.id}")
244
245
# Get access token for the installation
246
auth = integration.get_access_token(installation.id)
247
token = auth.token
248
249
# Use the token to create authenticated Github client
250
from github import Github, Auth
251
g = Github(auth=Auth.Token(token))
252
```
253
254
### Legacy App Authentication
255
256
Legacy GitHub App authentication class maintained for backward compatibility.
257
258
```python { .api }
259
class AppAuthentication:
260
def __init__(
261
self,
262
app_id: str,
263
private_key: str,
264
installation_id: int = None
265
):
266
"""
267
Legacy GitHub App authentication (deprecated).
268
269
Args:
270
app_id (str): GitHub App ID
271
private_key (str): Private key content
272
installation_id (int, optional): Installation ID
273
"""
274
```
275
276
## Authentication Patterns
277
278
### Repository Access Pattern
279
280
```python
281
from github import Github, Auth
282
283
# Personal access token for individual user
284
auth = Auth.Token("your_token")
285
g = Github(auth=auth)
286
287
# Access user's repositories
288
user = g.get_user()
289
for repo in user.get_repos():
290
print(f"User repo: {repo.full_name}")
291
292
# Access public repositories
293
repo = g.get_repo("octocat/Hello-World")
294
print(f"Public repo: {repo.description}")
295
```
296
297
### Organization Access Pattern
298
299
```python
300
from github import Github, Auth
301
302
# App installation for organization access
303
auth = Auth.AppInstallationAuth(
304
installation_id=12345678,
305
app_id="123456",
306
private_key=private_key_content
307
)
308
g = Github(auth=auth)
309
310
# Access organization repositories
311
org = g.get_organization("myorg")
312
for repo in org.get_repos():
313
print(f"Org repo: {repo.full_name}")
314
```
315
316
### Error Handling
317
318
```python
319
from github import Github, Auth, BadCredentialsException, TwoFactorException
320
321
try:
322
auth = Auth.Token("invalid_token")
323
g = Github(auth=auth)
324
user = g.get_user()
325
except BadCredentialsException:
326
print("Invalid credentials provided")
327
except TwoFactorException:
328
print("Two-factor authentication required")
329
```