0
# Password Management
1
2
Password-related operations for AWS Cognito User Pools, including forgot password flows, password changes, confirmation codes, new password challenges, and administrative password reset functionality. Provides both user-initiated and admin-initiated password management capabilities.
3
4
## Capabilities
5
6
### Forgot Password Flow
7
8
Initiate and complete the forgot password process using confirmation codes sent via email or SMS.
9
10
```python { .api }
11
def initiate_forgot_password(self) -> None:
12
"""
13
Send a verification code to the user to change their password.
14
15
Actions:
16
- Sends verification code via email or SMS (based on user pool config)
17
- Code expires after configured time period (usually 24 hours)
18
19
Note:
20
Uses the username set on the Cognito instance.
21
User pool must be configured with email/SMS delivery.
22
"""
23
24
def confirm_forgot_password(self, confirmation_code: str, password: str) -> None:
25
"""
26
Complete the forgot password flow with verification code and new password.
27
28
Args:
29
confirmation_code (str): Code received via email/SMS
30
password (str): New password (must meet pool requirements)
31
32
Actions:
33
- Validates confirmation code
34
- Sets new password
35
- Updates instance password attribute
36
37
Raises:
38
Exception: If code is invalid, expired, or password doesn't meet requirements
39
"""
40
```
41
42
**Usage Example:**
43
44
```python
45
from pycognito import Cognito
46
47
# Initialize with username
48
u = Cognito('your-user-pool-id', 'your-client-id', username='john.doe')
49
50
# Initiate forgot password
51
u.initiate_forgot_password()
52
print("Password reset code sent to your registered email/phone")
53
54
# User receives code and provides new password
55
code = input("Enter confirmation code: ")
56
new_password = input("Enter new password: ")
57
58
# Complete password reset
59
u.confirm_forgot_password(code, new_password)
60
print("Password successfully reset!")
61
62
# User can now authenticate with new password
63
u.authenticate(password=new_password)
64
```
65
66
### Password Change (Authenticated)
67
68
Change password for authenticated users who know their current password.
69
70
```python { .api }
71
def change_password(self, previous_password: str, proposed_password: str) -> None:
72
"""
73
Change the user's password (requires authentication).
74
75
Args:
76
previous_password (str): Current password for verification
77
proposed_password (str): New password (must meet pool requirements)
78
79
Requirements:
80
- User must be authenticated (valid access token)
81
- Previous password must be correct
82
- New password must meet user pool policy
83
84
Actions:
85
- Validates current password
86
- Sets new password
87
- Updates instance password attribute
88
89
Raises:
90
Exception: If current password is wrong or new password invalid
91
"""
92
```
93
94
**Usage Example:**
95
96
```python
97
# User must be authenticated first
98
u = Cognito('pool-id', 'client-id', username='user')
99
u.authenticate(password='current-password')
100
101
# Change password
102
u.change_password(
103
previous_password='current-password',
104
proposed_password='new-secure-password'
105
)
106
107
print("Password changed successfully!")
108
```
109
110
### Administrative Password Reset
111
112
Reset user passwords using administrative privileges without requiring the current password.
113
114
```python { .api }
115
def admin_reset_password(self, username: str, client_metadata: dict = None) -> None:
116
"""
117
Reset a user's password using admin privileges.
118
119
Args:
120
username (str): Username whose password to reset
121
client_metadata (dict, optional): Custom workflow metadata
122
123
Actions:
124
- Generates temporary password or triggers reset flow
125
- May send reset instructions to user
126
- User will be required to set new password on next login
127
128
Note:
129
Exact behavior depends on user pool configuration:
130
- May generate temporary password
131
- May trigger forgot password flow
132
- May require user to set password on next login
133
"""
134
```
135
136
**Usage Example:**
137
138
```python
139
# Admin resets user password
140
u = Cognito('pool-id', 'client-id')
141
u.admin_reset_password('target-username')
142
print("Password reset initiated for user")
143
144
# User will need to set new password on next login
145
```
146
147
### New Password Challenge
148
149
Handle the new password required challenge, typically triggered for users with temporary passwords or when forced password changes are required.
150
151
```python { .api }
152
def new_password_challenge(self, password: str, new_password: str) -> None:
153
"""
154
Respond to new password challenge using SRP protocol.
155
156
Args:
157
password (str): Current/temporary password
158
new_password (str): New permanent password
159
160
Use cases:
161
- User logging in with temporary password (admin created)
162
- User forced to change password due to policy
163
- First-time login after admin user creation
164
165
Actions:
166
- Validates current password
167
- Sets new permanent password
168
- Completes authentication flow
169
- Sets tokens on successful completion
170
"""
171
```
172
173
**Usage Example:**
174
175
```python
176
from pycognito.exceptions import ForceChangePasswordException
177
178
u = Cognito('pool-id', 'client-id', username='new-user')
179
180
try:
181
u.authenticate(password='temporary-password')
182
except ForceChangePasswordException:
183
# User must set new password
184
new_password = input("Set your new password: ")
185
u.new_password_challenge(
186
password='temporary-password',
187
new_password=new_password
188
)
189
print("New password set successfully!")
190
```
191
192
### Attribute Verification
193
194
Send and validate verification codes for email or phone number changes.
195
196
```python { .api }
197
def send_verification(self, attribute: str = "email") -> None:
198
"""
199
Send attribute verification code to the user.
200
201
Args:
202
attribute (str): Attribute to verify ("email" or "phone_number")
203
204
Actions:
205
- Sends verification code to the specified attribute
206
- Code expires after configured time period
207
208
Requirements:
209
- User must be authenticated
210
- Attribute must be configured for verification in user pool
211
"""
212
213
def validate_verification(self, confirmation_code: str, attribute: str = "email") -> dict:
214
"""
215
Verify user attribute using confirmation code.
216
217
Args:
218
confirmation_code (str): Code received via email/SMS
219
attribute (str): Attribute being verified ("email" or "phone_number")
220
221
Returns:
222
dict: Verification response from AWS Cognito
223
224
Actions:
225
- Validates confirmation code
226
- Marks attribute as verified
227
- Updates user's verification status
228
"""
229
```
230
231
**Usage Example:**
232
233
```python
234
# Send verification code for email change
235
u.send_verification("email")
236
print("Verification code sent to your email")
237
238
# User provides verification code
239
code = input("Enter verification code: ")
240
response = u.validate_verification(code, "email")
241
242
if response['ResponseMetadata']['HTTPStatusCode'] == 200:
243
print("Email verified successfully!")
244
```
245
246
## Usage Patterns
247
248
### Complete Forgot Password Flow
249
250
```python
251
from pycognito import Cognito
252
253
def forgot_password_flow(username):
254
"""Complete forgot password flow with user interaction."""
255
u = Cognito('pool-id', 'client-id', username=username)
256
257
try:
258
# Step 1: Initiate forgot password
259
u.initiate_forgot_password()
260
print(f"Password reset code sent to registered contact method")
261
262
# Step 2: Get code from user
263
code = input("Enter the confirmation code: ")
264
new_password = input("Enter your new password: ")
265
266
# Step 3: Complete password reset
267
u.confirm_forgot_password(code, new_password)
268
print("Password reset successfully!")
269
270
# Step 4: User can now login with new password
271
u.authenticate(password=new_password)
272
print("Authentication successful with new password!")
273
274
except Exception as e:
275
print(f"Password reset failed: {e}")
276
277
# Usage
278
forgot_password_flow('john.doe')
279
```
280
281
### Admin Password Management
282
283
```python
284
def admin_password_management():
285
"""Admin manages user passwords."""
286
u = Cognito('pool-id', 'client-id')
287
288
# Create user with temporary password
289
response = u.admin_create_user(
290
username='newemployee',
291
temporary_password='TempPass123!',
292
email='employee@company.com'
293
)
294
295
print("User created with temporary password")
296
297
# Later, if user has issues, admin can reset
298
u.admin_reset_password('newemployee')
299
print("Password reset initiated for user")
300
301
admin_password_management()
302
```
303
304
### New User Setup Flow
305
306
```python
307
from pycognito.exceptions import ForceChangePasswordException
308
309
def new_user_login(username, temp_password):
310
"""Handle new user first login with temporary password."""
311
u = Cognito('pool-id', 'client-id', username=username)
312
313
try:
314
u.authenticate(password=temp_password)
315
print("Login successful!")
316
317
except ForceChangePasswordException:
318
print("You must set a new password")
319
320
# Get new password from user
321
new_password = input("Enter your new password: ")
322
confirm_password = input("Confirm new password: ")
323
324
if new_password != confirm_password:
325
print("Passwords don't match!")
326
return
327
328
# Set new password
329
u.new_password_challenge(
330
password=temp_password,
331
new_password=new_password
332
)
333
334
print("New password set! You are now logged in.")
335
print(f"Access token: {u.access_token}")
336
337
# Usage for new employee
338
new_user_login('newemployee', 'TempPass123!')
339
```
340
341
### Secure Password Change
342
343
```python
344
def secure_password_change(u):
345
"""Secure password change with validation."""
346
347
# Verify user is authenticated
348
if not u.access_token:
349
print("Please authenticate first")
350
return
351
352
# Get current password for verification
353
current_password = input("Enter current password: ")
354
new_password = input("Enter new password: ")
355
confirm_password = input("Confirm new password: ")
356
357
# Validate passwords match
358
if new_password != confirm_password:
359
print("New passwords don't match!")
360
return
361
362
try:
363
u.change_password(current_password, new_password)
364
print("Password changed successfully!")
365
366
# Update any stored password reference
367
u.password = new_password
368
369
except Exception as e:
370
print(f"Password change failed: {e}")
371
372
# Usage
373
u = Cognito('pool-id', 'client-id', username='user')
374
u.authenticate(password='current-password')
375
secure_password_change(u)
376
```
377
378
### Email/Phone Verification After Update
379
380
```python
381
def update_and_verify_email(u, new_email):
382
"""Update email and handle verification."""
383
384
try:
385
# Update email attribute
386
u.update_profile({'email': new_email})
387
print(f"Email updated to {new_email}")
388
389
# Send verification code
390
u.send_verification("email")
391
print("Verification code sent to new email")
392
393
# Get verification code from user
394
code = input("Enter verification code: ")
395
396
# Verify email
397
response = u.validate_verification(code, "email")
398
399
if response['ResponseMetadata']['HTTPStatusCode'] == 200:
400
print("Email verified successfully!")
401
else:
402
print("Email verification failed")
403
404
except Exception as e:
405
print(f"Email update failed: {e}")
406
407
# Usage
408
u = Cognito('pool-id', 'client-id', username='user')
409
u.authenticate(password='password')
410
update_and_verify_email(u, 'newemail@example.com')
411
```