0
# Authentication
1
2
User registration, login, session management, OAuth integration, and authentication state handling. Provides complete authentication functionality through integration with Supabase Auth (GoTrue), supporting various auth flows including email/password, OAuth providers, magic links, and MFA.
3
4
## Capabilities
5
6
### Authentication Client Access
7
8
Access the authentication client through the main Supabase client instance.
9
10
```python { .api }
11
@property
12
def auth(self) -> SyncSupabaseAuthClient | AsyncSupabaseAuthClient:
13
"""
14
Authentication client providing complete GoTrue functionality.
15
16
Returns:
17
Auth client instance (sync or async) with methods for:
18
- User registration and login
19
- OAuth provider integration
20
- Session management and token refresh
21
- Password reset and email verification
22
- Multi-factor authentication
23
- User profile management
24
"""
25
```
26
27
### User Registration
28
29
Register new users with email/password or other authentication methods.
30
31
```python { .api }
32
# Core registration methods (inherited from GoTrue)
33
def sign_up(self, credentials: dict) -> AuthResponse:
34
"""
35
Register a new user with email and password.
36
37
Parameters:
38
- credentials: Dict with 'email' and 'password' keys, plus optional metadata
39
40
Returns:
41
AuthResponse with user data and session information
42
43
Raises:
44
AuthWeakPasswordError: If password doesn't meet requirements
45
AuthApiError: If email already exists or other API errors
46
"""
47
48
def sign_up_with_phone(self, credentials: dict) -> AuthResponse:
49
"""
50
Register a new user with phone number and password.
51
52
Parameters:
53
- credentials: Dict with 'phone' and 'password' keys
54
55
Returns:
56
AuthResponse with user data and session information
57
"""
58
```
59
60
**Usage Examples:**
61
62
```python
63
# Basic email registration
64
try:
65
response = supabase.auth.sign_up({
66
"email": "user@example.com",
67
"password": "secure_password123"
68
})
69
user = response.user
70
session = response.session
71
print(f"User registered: {user.id}")
72
except AuthWeakPasswordError:
73
print("Password is too weak")
74
except AuthApiError as e:
75
print(f"Registration failed: {e}")
76
77
# Registration with additional metadata
78
response = supabase.auth.sign_up({
79
"email": "user@example.com",
80
"password": "secure_password123",
81
"options": {
82
"data": {
83
"full_name": "John Doe",
84
"age": 30
85
}
86
}
87
})
88
89
# Phone registration
90
response = supabase.auth.sign_up({
91
"phone": "+1234567890",
92
"password": "secure_password123"
93
})
94
```
95
96
### User Login
97
98
Authenticate existing users with various login methods.
99
100
```python { .api }
101
def sign_in_with_password(self, credentials: dict) -> AuthResponse:
102
"""
103
Sign in user with email/phone and password.
104
105
Parameters:
106
- credentials: Dict with 'email'/'phone' and 'password' keys
107
108
Returns:
109
AuthResponse with user data and session information
110
111
Raises:
112
AuthInvalidCredentialsError: If credentials are incorrect
113
AuthApiError: For other authentication errors
114
"""
115
116
def sign_in_with_otp(self, credentials: dict) -> AuthResponse:
117
"""
118
Sign in with one-time password (magic link or SMS).
119
120
Parameters:
121
- credentials: Dict with 'email'/'phone' and optional 'token'
122
123
Returns:
124
AuthResponse with user data and session information
125
"""
126
```
127
128
**Usage Examples:**
129
130
```python
131
# Email/password login
132
try:
133
response = supabase.auth.sign_in_with_password({
134
"email": "user@example.com",
135
"password": "secure_password123"
136
})
137
session = response.session
138
user = response.user
139
print(f"Signed in: {user.email}")
140
except AuthInvalidCredentialsError:
141
print("Invalid email or password")
142
143
# Phone/password login
144
response = supabase.auth.sign_in_with_password({
145
"phone": "+1234567890",
146
"password": "secure_password123"
147
})
148
149
# Magic link login (send OTP)
150
supabase.auth.sign_in_with_otp({
151
"email": "user@example.com"
152
})
153
# User receives email with magic link
154
155
# Verify OTP token
156
response = supabase.auth.verify_otp({
157
"email": "user@example.com",
158
"token": "123456",
159
"type": "email"
160
})
161
```
162
163
### OAuth Authentication
164
165
Integrate with third-party OAuth providers for social login.
166
167
```python { .api }
168
def sign_in_with_oauth(self, provider: str, options: dict = None) -> AuthResponse:
169
"""
170
Sign in with OAuth provider.
171
172
Parameters:
173
- provider: OAuth provider name (google, github, facebook, etc.)
174
- options: Additional OAuth options (redirect_to, scopes, etc.)
175
176
Returns:
177
AuthResponse with authentication URL for redirect-based flow
178
"""
179
```
180
181
**Usage Examples:**
182
183
```python
184
# Google OAuth
185
response = supabase.auth.sign_in_with_oauth("google", {
186
"options": {
187
"redirect_to": "https://myapp.com/auth/callback"
188
}
189
})
190
# Redirect user to response.url
191
192
# GitHub OAuth with custom scopes
193
response = supabase.auth.sign_in_with_oauth("github", {
194
"options": {
195
"scopes": "user:email",
196
"redirect_to": "https://myapp.com/auth/callback"
197
}
198
})
199
200
# Multiple provider support
201
providers = ["google", "github", "facebook", "twitter"]
202
for provider in providers:
203
auth_url = supabase.auth.sign_in_with_oauth(provider)
204
print(f"{provider} login: {auth_url.url}")
205
```
206
207
### Session Management
208
209
Manage user sessions, tokens, and authentication state.
210
211
```python { .api }
212
def get_session(self) -> Session | None:
213
"""
214
Get the current user session.
215
216
Returns:
217
Current session with access token and user data, or None if not authenticated
218
"""
219
220
def get_user(self) -> User | None:
221
"""
222
Get the current authenticated user.
223
224
Returns:
225
Current user data, or None if not authenticated
226
"""
227
228
def refresh_session(self) -> AuthResponse:
229
"""
230
Refresh the current session using the refresh token.
231
232
Returns:
233
AuthResponse with new session data
234
235
Raises:
236
AuthSessionMissingError: If no session exists to refresh
237
"""
238
239
def sign_out(self) -> None:
240
"""
241
Sign out the current user and clear session.
242
243
Raises:
244
AuthApiError: If sign out fails
245
"""
246
```
247
248
**Usage Examples:**
249
250
```python
251
# Check current session
252
session = supabase.auth.get_session()
253
if session:
254
print(f"User is logged in: {session.user.email}")
255
print(f"Access token expires: {session.expires_at}")
256
else:
257
print("No active session")
258
259
# Get current user
260
user = supabase.auth.get_user()
261
if user:
262
print(f"Current user: {user.email}")
263
print(f"User metadata: {user.user_metadata}")
264
265
# Refresh session
266
try:
267
response = supabase.auth.refresh_session()
268
new_session = response.session
269
print("Session refreshed successfully")
270
except AuthSessionMissingError:
271
print("No session to refresh")
272
273
# Sign out
274
supabase.auth.sign_out()
275
print("User signed out")
276
```
277
278
### Password Management
279
280
Handle password resets, updates, and security operations.
281
282
```python { .api }
283
def reset_password_email(self, email: str, options: dict = None) -> None:
284
"""
285
Send password reset email to user.
286
287
Parameters:
288
- email: User's email address
289
- options: Additional options (redirect_to, etc.)
290
291
Raises:
292
AuthApiError: If email sending fails
293
"""
294
295
def update_user(self, attributes: dict) -> AuthResponse:
296
"""
297
Update user profile and authentication data.
298
299
Parameters:
300
- attributes: Dict with user data to update (email, password, data, etc.)
301
302
Returns:
303
AuthResponse with updated user data
304
305
Raises:
306
AuthSessionMissingError: If no active session
307
AuthWeakPasswordError: If new password is too weak
308
"""
309
```
310
311
**Usage Examples:**
312
313
```python
314
# Send password reset email
315
supabase.auth.reset_password_email("user@example.com", {
316
"redirect_to": "https://myapp.com/reset-password"
317
})
318
319
# Update user password
320
response = supabase.auth.update_user({
321
"password": "new_secure_password123"
322
})
323
324
# Update user metadata
325
response = supabase.auth.update_user({
326
"data": {
327
"full_name": "Jane Smith",
328
"preferences": {"theme": "dark"}
329
}
330
})
331
332
# Update email (requires verification)
333
response = supabase.auth.update_user({
334
"email": "newemail@example.com"
335
})
336
```
337
338
### Authentication State Events
339
340
Listen for authentication state changes and handle session events.
341
342
```python { .api }
343
def on_auth_state_change(self, callback: Callable) -> None:
344
"""
345
Register callback for authentication state changes.
346
347
Parameters:
348
- callback: Function called on auth events (event, session)
349
350
Events:
351
- SIGNED_IN: User signed in
352
- SIGNED_OUT: User signed out
353
- TOKEN_REFRESHED: Session token refreshed
354
- USER_UPDATED: User profile updated
355
- PASSWORD_RECOVERY: Password reset initiated
356
"""
357
```
358
359
**Usage Examples:**
360
361
```python
362
def auth_state_handler(event, session):
363
"""Handle authentication state changes."""
364
if event == "SIGNED_IN":
365
print(f"User signed in: {session.user.email}")
366
# Update UI, redirect, etc.
367
elif event == "SIGNED_OUT":
368
print("User signed out")
369
# Clear user data, redirect to login
370
elif event == "TOKEN_REFRESHED":
371
print("Session refreshed")
372
# Update stored tokens
373
elif event == "USER_UPDATED":
374
print("User profile updated")
375
376
# Register the handler
377
supabase.auth.on_auth_state_change(auth_state_handler)
378
379
# Example: Automatic session management
380
def handle_session_change(event, session):
381
if event in ["SIGNED_IN", "TOKEN_REFRESHED"]:
382
# Update authorization headers for other clients
383
if session:
384
supabase.options.headers["Authorization"] = f"Bearer {session.access_token}"
385
elif event == "SIGNED_OUT":
386
# Clear authorization
387
supabase.options.headers.pop("Authorization", None)
388
389
supabase.auth.on_auth_state_change(handle_session_change)
390
```
391
392
### Multi-Factor Authentication
393
394
Handle MFA enrollment, verification, and management.
395
396
```python { .api }
397
# MFA methods (available through GoTrue integration)
398
def enroll_mfa(self, params: dict) -> MFAEnrollResponse:
399
"""
400
Enroll user in multi-factor authentication.
401
402
Parameters:
403
- params: MFA enrollment parameters (factor_type, friendly_name, etc.)
404
405
Returns:
406
MFA enrollment response with QR code and recovery codes
407
"""
408
409
def challenge_mfa(self, params: dict) -> MFAChallengeResponse:
410
"""
411
Create MFA challenge for verification.
412
413
Parameters:
414
- params: Challenge parameters (factor_id)
415
416
Returns:
417
MFA challenge response
418
"""
419
420
def verify_mfa(self, params: dict) -> AuthResponse:
421
"""
422
Verify MFA challenge with code.
423
424
Parameters:
425
- params: Verification parameters (factor_id, challenge_id, code)
426
427
Returns:
428
AuthResponse with verified session
429
"""
430
```
431
432
### Error Handling
433
434
Handle various authentication errors and edge cases.
435
436
```python { .api }
437
# Authentication exceptions (from supabase_auth)
438
class AuthApiError(Exception):
439
"""General Auth API errors"""
440
441
class AuthError(Exception):
442
"""Base authentication error"""
443
444
class AuthInvalidCredentialsError(Exception):
445
"""Invalid email/password or credentials"""
446
447
class AuthSessionMissingError(Exception):
448
"""No active session when required"""
449
450
class AuthWeakPasswordError(Exception):
451
"""Password doesn't meet strength requirements"""
452
453
class AuthImplicitGrantRedirectError(Exception):
454
"""OAuth redirect errors"""
455
456
class AuthRetryableError(Exception):
457
"""Temporary errors that can be retried"""
458
459
class AuthUnknownError(Exception):
460
"""Unknown authentication errors"""
461
```
462
463
**Error Handling Examples:**
464
465
```python
466
from supabase import AuthInvalidCredentialsError, AuthWeakPasswordError, AuthApiError
467
468
# Login error handling
469
try:
470
response = supabase.auth.sign_in_with_password({
471
"email": "user@example.com",
472
"password": "wrong_password"
473
})
474
except AuthInvalidCredentialsError:
475
print("Invalid email or password")
476
except AuthApiError as e:
477
print(f"Login failed: {e}")
478
479
# Registration error handling
480
try:
481
response = supabase.auth.sign_up({
482
"email": "user@example.com",
483
"password": "weak"
484
})
485
except AuthWeakPasswordError:
486
print("Password must be at least 8 characters")
487
except AuthApiError as e:
488
if "already registered" in str(e):
489
print("Email already exists")
490
else:
491
print(f"Registration failed: {e}")
492
493
# Session operation error handling
494
try:
495
response = supabase.auth.update_user({"password": "new_password"})
496
except AuthSessionMissingError:
497
print("Please log in first")
498
except AuthWeakPasswordError:
499
print("New password is too weak")
500
```