0
# Authentication & Session Management
1
2
Comprehensive authentication functionality supporting multiple GitHub authentication methods including personal access tokens, OAuth applications, GitHub Apps, and enterprise instances with two-factor authentication support.
3
4
## Capabilities
5
6
### Basic Authentication Methods
7
8
Create authenticated GitHub sessions using various credential types for different use cases and security requirements.
9
10
```python { .api }
11
def login(username=None, password=None, token=None, two_factor_callback=None):
12
"""
13
Construct and return an authenticated GitHub session.
14
15
Parameters:
16
- username (str, optional): GitHub username for basic auth
17
- password (str, optional): Password for basic auth
18
- token (str, optional): Personal access token or OAuth token
19
- two_factor_callback (callable, optional): Function to provide 2FA code
20
21
Returns:
22
GitHub instance or None if no credentials provided
23
"""
24
25
def enterprise_login(username=None, password=None, token=None, url=None, two_factor_callback=None):
26
"""
27
Construct and return an authenticated GitHub Enterprise session.
28
29
Parameters:
30
- username (str, optional): Username for basic auth
31
- password (str, optional): Password for basic auth
32
- token (str, optional): Personal access token or OAuth token
33
- url (str, required): URL of GitHub Enterprise instance
34
- two_factor_callback (callable, optional): Function to provide 2FA code
35
36
Returns:
37
GitHubEnterprise instance or None if no credentials provided
38
"""
39
```
40
41
### Usage Examples
42
43
```python
44
# Token-based authentication (recommended)
45
import github3
46
gh = github3.login(token='ghp_your_personal_access_token')
47
48
# Username and token
49
gh = github3.login('username', token='ghp_your_token')
50
51
# Enterprise instance
52
gh = github3.enterprise_login(
53
url='https://github.your-company.com',
54
token='your_enterprise_token'
55
)
56
57
# Two-factor authentication
58
def two_factor_callback():
59
return input('Enter 2FA code: ')
60
61
gh = github3.login('username', 'password', two_factor_callback=two_factor_callback)
62
```
63
64
### Session Management via GitHub Class
65
66
Direct session management and authentication using the GitHub class constructor and login methods.
67
68
```python { .api }
69
class GitHub:
70
def __init__(self, username="", password="", token="", session=None, api_version=""):
71
"""
72
Create a new GitHub instance.
73
74
Parameters:
75
- username (str): Username for authentication
76
- password (str): Password for authentication
77
- token (str): Token for authentication
78
- session (Session, optional): Custom requests session
79
- api_version (str, optional): API version header value
80
"""
81
82
def login(self, username=None, password=None, token=None, two_factor_callback=None):
83
"""
84
Log the user into GitHub for protected API calls.
85
86
Parameters:
87
- username (str, optional): Login name
88
- password (str, optional): Password for the login
89
- token (str, optional): OAuth token
90
- two_factor_callback (callable, optional): Function for 2FA code
91
"""
92
93
def set_client_id(self, id, secret):
94
"""
95
Set OAuth application credentials.
96
97
Parameters:
98
- id (str): 20-character hexadecimal client_id from GitHub
99
- secret (str): 40-character hexadecimal client_secret from GitHub
100
"""
101
102
def set_user_agent(self, user_agent):
103
"""
104
Set custom user agent string.
105
106
Parameters:
107
- user_agent (str): Custom user agent identifier
108
"""
109
```
110
111
### Usage Examples
112
113
```python
114
# Initialize with token
115
gh = github3.GitHub(token='your_token')
116
117
# Initialize and login separately
118
gh = github3.GitHub()
119
gh.login(token='your_token')
120
121
# Set OAuth app credentials for app-specific operations
122
gh.set_client_id('your_client_id', 'your_client_secret')
123
124
# Custom user agent
125
gh.set_user_agent('MyApp/1.0.0')
126
```
127
128
### GitHub Apps Authentication
129
130
Advanced authentication for GitHub Apps enabling programmatic access as applications rather than users.
131
132
```python { .api }
133
def login_as_app(self, private_key_pem, app_id, expire_in=600):
134
"""
135
Login as a GitHub Application using JWT.
136
137
Parameters:
138
- private_key_pem (bytes): Private key for the GitHub App
139
- app_id (int): Integer identifier for the GitHub App
140
- expire_in (int): Token validity period in seconds (max 600)
141
"""
142
143
def login_as_app_installation(self, private_key_pem, app_id, installation_id, expire_in=30):
144
"""
145
Login using GitHub App installation credentials.
146
147
Parameters:
148
- private_key_pem (bytes): Private key for the GitHub App
149
- app_id (int): Integer identifier for the GitHub App
150
- installation_id (int): Installation ID for the app
151
- expire_in (int): JWT expiration in seconds (default 30)
152
"""
153
```
154
155
### Usage Examples
156
157
```python
158
# Read private key from file
159
with open('github-app-private-key.pem', 'rb') as f:
160
private_key = f.read()
161
162
# Authenticate as GitHub App
163
gh = github3.GitHub()
164
gh.login_as_app(private_key, app_id=12345)
165
166
# Authenticate as specific installation
167
gh.login_as_app_installation(private_key, app_id=12345, installation_id=67890)
168
```
169
170
### OAuth Authorization Management
171
172
Complete OAuth authorization lifecycle for building applications that integrate with GitHub on behalf of users.
173
174
```python { .api }
175
def authorize(self, username, password, scopes=None, note="", note_url="", client_id="", client_secret=""):
176
"""
177
Obtain an authorization token for OAuth applications.
178
179
Parameters:
180
- username (str, required): GitHub username
181
- password (str, required): GitHub password
182
- scopes (list, optional): Permission scopes for the token
183
- note (str, optional): Note about the authorization
184
- note_url (str, optional): URL for the application
185
- client_id (str, optional): OAuth client key
186
- client_secret (str, optional): OAuth client secret
187
188
Returns:
189
Authorization object with token details
190
"""
191
192
def authorization(self, id_num):
193
"""
194
Get information about a specific authorization.
195
196
Parameters:
197
- id_num (int): Unique ID of the authorization
198
199
Returns:
200
Authorization object or None
201
"""
202
203
def authorizations(self, number=-1, etag=None):
204
"""
205
Iterate over authorizations for the authenticated user.
206
207
Parameters:
208
- number (int): Number of authorizations to return (-1 for all)
209
- etag (str, optional): ETag from previous request
210
211
Returns:
212
Generator of Authorization objects
213
"""
214
215
def check_authorization(self, access_token):
216
"""
217
Check if an authorization token is valid.
218
219
Parameters:
220
- access_token (str): Token to validate
221
222
Returns:
223
bool: True if valid, False otherwise
224
"""
225
226
def revoke_authorization(self, access_token):
227
"""
228
Revoke a specific authorization token.
229
230
Parameters:
231
- access_token (str): Token to revoke
232
233
Returns:
234
bool: True if successful, False otherwise
235
"""
236
237
def revoke_authorizations(self):
238
"""
239
Revoke all authorization tokens for the OAuth application.
240
241
Returns:
242
bool: True if successful, False otherwise
243
"""
244
```
245
246
### Usage Examples
247
248
```python
249
# Create authorization with specific scopes
250
auth = gh.authorize(
251
'username',
252
'password',
253
scopes=['repo', 'user'],
254
note='MyApp Authorization',
255
note_url='https://myapp.com'
256
)
257
print(f"Token: {auth.token}")
258
259
# Check authorization validity
260
is_valid = gh.check_authorization('token_to_check')
261
262
# List all authorizations
263
for auth in gh.authorizations():
264
print(f"ID: {auth.id}, Note: {auth.note}")
265
266
# Revoke specific authorization
267
gh.revoke_authorization('token_to_revoke')
268
```
269
270
### Enterprise Authentication
271
272
Special authentication handling for GitHub Enterprise instances with custom URLs and SSL verification options.
273
274
```python { .api }
275
class GitHubEnterprise(GitHub):
276
def __init__(self, url, username="", password="", token="", verify=True, session=None):
277
"""
278
Create a client for a GitHub Enterprise instance.
279
280
Parameters:
281
- url (str, required): Base URL of the Enterprise instance
282
- username (str): Username for authentication
283
- password (str): Password for authentication
284
- token (str): Token for authentication
285
- verify (bool): Enable SSL certificate verification
286
- session (Session, optional): Custom requests session
287
"""
288
```
289
290
### Usage Examples
291
292
```python
293
# Enterprise with SSL verification
294
gh = github3.GitHubEnterprise(
295
'https://github.company.com',
296
token='enterprise_token'
297
)
298
299
# Enterprise with custom SSL settings
300
gh = github3.GitHubEnterprise(
301
'https://github.company.com',
302
token='enterprise_token',
303
verify=False # For self-signed certificates
304
)
305
```
306
307
## Authentication Types
308
309
```python { .api }
310
class Authorization:
311
"""OAuth authorization token representation"""
312
id: int
313
token: str
314
note: str
315
note_url: str
316
scopes: list
317
# ... additional authorization properties
318
```
319
320
## Common Authentication Patterns
321
322
### Personal Access Tokens (Recommended)
323
```python
324
# Most secure and flexible method
325
gh = github3.login(token='ghp_your_personal_access_token')
326
```
327
328
### OAuth Applications
329
```python
330
# For applications acting on behalf of users
331
gh = github3.GitHub()
332
gh.set_client_id('client_id', 'client_secret')
333
auth = gh.authorize('user', 'pass', scopes=['repo'])
334
```
335
336
### GitHub Apps
337
```python
338
# For applications with enhanced permissions
339
gh = github3.GitHub()
340
gh.login_as_app_installation(private_key, app_id, installation_id)
341
```
342
343
### Enterprise Instances
344
```python
345
# For GitHub Enterprise users
346
gh = github3.enterprise_login(
347
url='https://github.company.com',
348
token='enterprise_token'
349
)
350
```