0
# SAML Message Processing
1
2
Specialized classes for handling SAML protocol messages including authentication requests, logout requests/responses, and SAML response validation. These classes provide comprehensive message generation, validation, and data extraction capabilities for complete SSO and SLO workflows.
3
4
## Capabilities
5
6
### SAML Response Processing
7
8
Handles SAML Response messages from Identity Providers, including parsing, validation, and user data extraction with comprehensive security checks.
9
10
```python { .api }
11
class OneLogin_Saml2_Response:
12
def __init__(self, settings: OneLogin_Saml2_Settings, response: str):
13
"""
14
Initialize SAML Response processor.
15
16
Parameters:
17
- settings: SAML configuration settings
18
- response: Base64 encoded XML SAML Response
19
"""
20
```
21
22
### Response Validation
23
24
Comprehensive validation of SAML Response structure, signatures, and security conditions.
25
26
```python { .api }
27
def is_valid(self, request_data: dict, request_id: str = None, raise_exceptions: bool = False) -> bool:
28
"""
29
Validate SAML Response with comprehensive security checks.
30
31
Parameters:
32
- request_data: HTTP request information
33
- request_id: ID of AuthNRequest sent by SP
34
- raise_exceptions: Whether to raise exceptions on validation failure
35
36
Returns:
37
True if response is valid, False otherwise
38
39
Validates:
40
- SAML version compliance
41
- Response status
42
- Single assertion requirement
43
- XML schema validation
44
- Digital signatures
45
- Timestamp validity
46
- Audience restrictions
47
- Issuer verification
48
"""
49
50
def check_status(self) -> None:
51
"""
52
Validate response status is SUCCESS.
53
54
Raises:
55
- OneLogin_Saml2_ValidationError: If status is not SUCCESS
56
"""
57
58
def validate_timestamps(self, raise_exceptions: bool = True) -> bool:
59
"""
60
Validate NotBefore/NotOnOrAfter conditions.
61
62
Parameters:
63
- raise_exceptions: Whether to raise exceptions on failure
64
65
Returns:
66
True if timestamps are valid
67
"""
68
```
69
70
### User Data Extraction
71
72
Extract user identification and attributes from validated SAML assertions.
73
74
```python { .api }
75
def get_nameid(self) -> str:
76
"""
77
Extract NameID value from assertion.
78
79
Returns:
80
NameID string or None
81
"""
82
83
def get_nameid_data(self) -> dict:
84
"""
85
Get complete NameID data structure.
86
87
Returns:
88
Dictionary with Value, Format, NameQualifier, SPNameQualifier
89
"""
90
91
def get_nameid_format(self) -> str:
92
"""
93
Get NameID format.
94
95
Returns:
96
NameID format string or None
97
"""
98
99
def get_attributes(self) -> dict:
100
"""
101
Extract SAML attributes indexed by Name.
102
103
Returns:
104
Dictionary mapping attribute names to value lists
105
"""
106
107
def get_friendlyname_attributes(self) -> dict:
108
"""
109
Extract SAML attributes indexed by FriendlyName.
110
111
Returns:
112
Dictionary mapping FriendlyNames to value lists
113
"""
114
```
115
116
### Session Information
117
118
Retrieve session data for logout and session management.
119
120
```python { .api }
121
def get_session_index(self) -> str:
122
"""
123
Get SessionIndex for logout operations.
124
125
Returns:
126
SessionIndex string or None
127
"""
128
129
def get_session_not_on_or_after(self) -> int:
130
"""
131
Get session expiration time.
132
133
Returns:
134
Unix timestamp or None
135
"""
136
137
def get_assertion_not_on_or_after(self) -> int:
138
"""
139
Get assertion validity end time.
140
141
Returns:
142
Unix timestamp or None
143
"""
144
```
145
146
### Response Metadata
147
148
Access response and assertion metadata for auditing and debugging.
149
150
```python { .api }
151
def get_audiences(self) -> list:
152
"""
153
Get valid audiences from AudienceRestriction.
154
155
Returns:
156
List of audience entity IDs
157
"""
158
159
def get_authn_contexts(self) -> list:
160
"""
161
Get authentication context class references.
162
163
Returns:
164
List of authentication context strings
165
"""
166
167
def get_issuers(self) -> list:
168
"""
169
Get issuers from response and assertion.
170
171
Returns:
172
List of issuer entity IDs
173
"""
174
175
def get_in_response_to(self) -> str:
176
"""
177
Get InResponseTo attribute value.
178
179
Returns:
180
InResponseTo ID string or None
181
"""
182
183
def get_id(self) -> str:
184
"""
185
Get Response ID.
186
187
Returns:
188
Response ID string
189
"""
190
191
def get_assertion_id(self) -> str:
192
"""
193
Get Assertion ID.
194
195
Returns:
196
Assertion ID string
197
"""
198
```
199
200
## SAML Authentication Request Generation
201
202
Build SAML AuthnRequest messages to initiate Single Sign-On flows with configurable authentication parameters.
203
204
```python { .api }
205
class OneLogin_Saml2_Authn_Request:
206
def __init__(self, settings: OneLogin_Saml2_Settings, force_authn: bool = False, is_passive: bool = False, set_nameid_policy: bool = True, name_id_value_req: str = None):
207
"""
208
Initialize AuthnRequest builder.
209
210
Parameters:
211
- settings: SAML configuration settings
212
- force_authn: Forces re-authentication at IdP
213
- is_passive: Sets passive authentication mode
214
- set_nameid_policy: Whether to include NameIDPolicy
215
- name_id_value_req: Specific NameID value to request
216
"""
217
```
218
219
### Request Generation
220
221
Generate and encode SAML authentication requests for IdP redirection.
222
223
```python { .api }
224
def get_request(self, deflate: bool = True) -> str:
225
"""
226
Get encoded AuthnRequest for HTTP binding.
227
228
Parameters:
229
- deflate: Whether to compress with deflate (required for HTTP-Redirect)
230
231
Returns:
232
Base64 encoded (and optionally deflated) AuthnRequest XML
233
"""
234
235
def get_id(self) -> str:
236
"""
237
Get unique AuthnRequest ID.
238
239
Returns:
240
Request ID string for tracking
241
"""
242
243
def get_xml(self) -> str:
244
"""
245
Get raw XML AuthnRequest.
246
247
Returns:
248
Complete AuthnRequest XML string
249
"""
250
```
251
252
**Usage Example:**
253
```python
254
# Create authentication request
255
authn_request = OneLogin_Saml2_Authn_Request(
256
settings,
257
force_authn=True, # Force re-authentication
258
is_passive=False # Interactive authentication
259
)
260
261
# Get encoded request for redirect
262
encoded_request = authn_request.get_request(deflate=True)
263
request_id = authn_request.get_id()
264
265
# Build SSO URL with request
266
sso_url = f"{idp_sso_url}?SAMLRequest={encoded_request}&RelayState={return_url}"
267
```
268
269
## SAML Logout Request Processing
270
271
Handle SAML Logout Request messages for Single Logout initiation and processing.
272
273
```python { .api }
274
class OneLogin_Saml2_Logout_Request:
275
def __init__(self, settings: OneLogin_Saml2_Settings, request: str = None, name_id: str = None, session_index: str = None, nq: str = None, name_id_format: str = None, spnq: str = None):
276
"""
277
Initialize Logout Request handler.
278
279
Parameters:
280
- settings: SAML configuration settings
281
- request: Existing logout request to parse (optional)
282
- name_id: NameID for logout
283
- session_index: Session identifier
284
- nq: NameQualifier
285
- name_id_format: NameID format
286
- spnq: SPNameQualifier
287
"""
288
```
289
290
### Logout Request Operations
291
292
Generate and validate logout requests for SLO workflows.
293
294
```python { .api }
295
def get_request(self, deflate: bool = True) -> str:
296
"""
297
Get encoded logout request.
298
299
Parameters:
300
- deflate: Whether to compress with deflate
301
302
Returns:
303
Base64 encoded logout request XML
304
"""
305
306
def get_xml(self) -> str:
307
"""
308
Get raw XML logout request.
309
310
Returns:
311
Complete LogoutRequest XML string
312
"""
313
314
def is_valid(self, request_data: dict, raise_exceptions: bool = False) -> bool:
315
"""
316
Validate incoming logout request.
317
318
Parameters:
319
- request_data: HTTP request information
320
- raise_exceptions: Whether to raise validation exceptions
321
322
Returns:
323
True if request is valid
324
325
Validates:
326
- XML schema compliance
327
- Destination verification
328
- Issuer validation
329
- Timestamp checking
330
- Digital signatures
331
"""
332
```
333
334
### Logout Request Data Extraction
335
336
Extract data from incoming logout requests using static methods.
337
338
```python { .api }
339
@staticmethod
340
def get_id(request: str) -> str:
341
"""
342
Extract request ID from logout request.
343
344
Parameters:
345
- request: Base64 encoded logout request
346
347
Returns:
348
Request ID string
349
"""
350
351
@staticmethod
352
def get_nameid_data(request: str, key: str = None) -> dict:
353
"""
354
Get complete NameID data, handling encryption.
355
356
Parameters:
357
- request: Base64 encoded logout request
358
- key: Private key for NameID decryption
359
360
Returns:
361
Dictionary with NameID data
362
"""
363
364
@staticmethod
365
def get_nameid(request: str, key: str = None) -> str:
366
"""
367
Get NameID value from logout request.
368
369
Parameters:
370
- request: Base64 encoded logout request
371
- key: Private key for decryption
372
373
Returns:
374
NameID string
375
"""
376
377
@staticmethod
378
def get_issuer(request: str) -> str:
379
"""
380
Get issuer from logout request.
381
382
Parameters:
383
- request: Base64 encoded logout request
384
385
Returns:
386
Issuer entity ID string
387
"""
388
389
@staticmethod
390
def get_session_indexes(request: str) -> list:
391
"""
392
Get all session indexes from request.
393
394
Parameters:
395
- request: Base64 encoded logout request
396
397
Returns:
398
List of session index strings
399
"""
400
```
401
402
## SAML Logout Response Processing
403
404
Handle SAML Logout Response messages for Single Logout completion.
405
406
```python { .api }
407
class OneLogin_Saml2_Logout_Response:
408
def __init__(self, settings: OneLogin_Saml2_Settings, response: str = None):
409
"""
410
Initialize Logout Response handler.
411
412
Parameters:
413
- settings: SAML configuration settings
414
- response: Base64 encoded SAML logout response (optional)
415
"""
416
```
417
418
### Logout Response Building
419
420
Create logout response messages for IdP-initiated SLO.
421
422
```python { .api }
423
def build(self, in_response_to: str, status: str = OneLogin_Saml2_Constants.STATUS_SUCCESS) -> None:
424
"""
425
Build a new logout response.
426
427
Parameters:
428
- in_response_to: ID of the logout request being responded to
429
- status: Response status code (default: SUCCESS)
430
"""
431
432
def get_response(self, deflate: bool = True) -> str:
433
"""
434
Get encoded logout response.
435
436
Parameters:
437
- deflate: Whether to compress with deflate
438
439
Returns:
440
Base64 encoded logout response XML
441
"""
442
443
def get_xml(self) -> str:
444
"""
445
Get raw XML logout response.
446
447
Returns:
448
Complete LogoutResponse XML string
449
"""
450
```
451
452
### Logout Response Validation
453
454
Validate incoming logout responses from Identity Providers.
455
456
```python { .api }
457
def is_valid(self, request_data: dict, request_id: str = None, raise_exceptions: bool = False) -> bool:
458
"""
459
Validate logout response.
460
461
Parameters:
462
- request_data: HTTP request information
463
- request_id: ID of logout request sent by SP
464
- raise_exceptions: Whether to raise validation exceptions
465
466
Returns:
467
True if response is valid
468
469
Validates:
470
- XML schema compliance
471
- InResponseTo matching
472
- Issuer verification
473
- Destination validation
474
- Digital signatures
475
"""
476
477
def get_status(self) -> str:
478
"""
479
Get response status code.
480
481
Returns:
482
Status code string (SUCCESS, REQUESTER, RESPONDER, etc.)
483
"""
484
485
def get_issuer(self) -> str:
486
"""
487
Get response issuer.
488
489
Returns:
490
Issuer entity ID string
491
"""
492
493
def get_in_response_to(self) -> str:
494
"""
495
Get InResponseTo value.
496
497
Returns:
498
InResponseTo ID string
499
"""
500
```
501
502
## Error Handling
503
504
All message processing classes provide comprehensive error handling capabilities.
505
506
```python { .api }
507
def get_error(self) -> str:
508
"""
509
Get validation error message.
510
511
Returns:
512
Descriptive error message string or None
513
"""
514
```
515
516
## Usage Patterns
517
518
### Complete Response Processing
519
```python
520
# Process SAML Response in ACS endpoint
521
response = OneLogin_Saml2_Response(settings, saml_response)
522
523
if response.is_valid(request_data, request_id):
524
# Extract user data
525
user_id = response.get_nameid()
526
attributes = response.get_attributes()
527
session_index = response.get_session_index()
528
529
# Store session data
530
session['user_id'] = user_id
531
session['saml_attributes'] = attributes
532
session['saml_session_index'] = session_index
533
else:
534
# Handle validation failure
535
error = response.get_error()
536
print(f"SAML validation failed: {error}")
537
```
538
539
### Logout Request Processing
540
```python
541
# Handle incoming logout request
542
if 'SAMLRequest' in request.form:
543
logout_req = OneLogin_Saml2_Logout_Request(settings, request.form['SAMLRequest'])
544
545
if logout_req.is_valid(request_data):
546
# Extract logout data
547
nameid = OneLogin_Saml2_Logout_Request.get_nameid(request.form['SAMLRequest'])
548
session_indexes = OneLogin_Saml2_Logout_Request.get_session_indexes(request.form['SAMLRequest'])
549
550
# Build response
551
logout_resp = OneLogin_Saml2_Logout_Response(settings)
552
logout_resp.build(logout_req.get_id())
553
554
# Clear local session and return response
555
session.clear()
556
return redirect(f"{idp_slo_url}?SAMLResponse={logout_resp.get_response()}")
557
```
558
559
### Authentication Request Generation
560
```python
561
# Create AuthN request with specific parameters
562
authn_req = OneLogin_Saml2_Authn_Request(
563
settings,
564
force_authn=True,
565
set_nameid_policy=True
566
)
567
568
# Build SSO redirect URL
569
sso_url = (
570
f"{settings.get_idp_sso_url()}"
571
f"?SAMLRequest={authn_req.get_request()}"
572
f"&RelayState={urllib.parse.quote(return_url)}"
573
)
574
575
# Store request ID for validation
576
session['saml_request_id'] = authn_req.get_id()
577
```
578
579
## Security Features
580
581
### Validation Capabilities
582
- XML schema validation against SAML specifications
583
- Digital signature verification with certificate validation
584
- Timestamp validation with configurable clock drift tolerance
585
- Replay attack prevention through unique ID tracking
586
- Audience restriction enforcement
587
- Issuer verification against expected values
588
589
### Encryption Support
590
- Encrypted assertion decryption
591
- Encrypted NameID decryption
592
- Multiple certificate support for key rollover
593
- Configurable encryption algorithms
594
595
### Message Formats
596
- HTTP-POST binding (Base64 encoding)
597
- HTTP-Redirect binding (Deflate compression + Base64 encoding)
598
- Proper SAML 2.0 XML structure generation
599
- Namespace and schema compliance