0
# Authentication and SSO/SLO
1
2
Core SAML authentication functionality providing Single Sign-On (SSO) and Single Logout (SLO) capabilities. The OneLogin_Saml2_Auth class serves as the primary interface for all SAML operations, managing the complete authentication workflow from initiation to completion.
3
4
## Capabilities
5
6
### SAML Auth Instance Initialization
7
8
Creates and configures a SAML Service Provider authentication instance with request data and settings.
9
10
```python { .api }
11
class OneLogin_Saml2_Auth:
12
def __init__(self, request_data: dict, old_settings: dict = None, custom_base_path: str = None):
13
"""
14
Initialize the SP SAML instance.
15
16
Parameters:
17
- request_data: HTTP request information structure
18
- old_settings: SAML configuration settings (dict or OneLogin_Saml2_Settings)
19
- custom_base_path: Path to settings file and cert folder
20
"""
21
```
22
23
**Request Data Structure:**
24
```python
25
request_data = {
26
'https': 'on' | 'off', # Whether HTTPS is used
27
'http_host': 'example.com', # HTTP host
28
'script_name': '/path', # Script path
29
'get_data': {}, # GET parameters
30
'post_data': {}, # POST parameters
31
'query_string': '...', # Optional: raw query string
32
'lowercase_urlencoding': True, # Optional: ADFS compatibility
33
'validate_signature_from_qs': True # Optional: signature validation method
34
}
35
```
36
37
### Single Sign-On (SSO) Initiation
38
39
Initiates the SAML authentication process by redirecting users to the Identity Provider for authentication.
40
41
```python { .api }
42
def login(self, return_to: str = None, force_authn: bool = False, is_passive: bool = False, set_nameid_policy: bool = True, name_id_value_req: str = None) -> str:
43
"""
44
Initiate SSO process by building an authentication request.
45
46
Parameters:
47
- return_to: Target URL for redirection after login
48
- force_authn: Forces authentication even if user has active session
49
- is_passive: Sets IsPassive='true' for transparent authentication attempts
50
- set_nameid_policy: Whether to include NameIDPolicy element
51
- name_id_value_req: Specific subject that should be authenticated
52
53
Returns:
54
Redirection URL to IdP for authentication
55
"""
56
```
57
58
**Usage Example:**
59
```python
60
# Basic SSO initiation
61
auth = OneLogin_Saml2_Auth(request_data, settings)
62
sso_url = auth.login()
63
64
# SSO with return URL and forced authentication
65
sso_url = auth.login(
66
return_to="https://myapp.com/dashboard",
67
force_authn=True
68
)
69
```
70
71
### SAML Response Processing
72
73
Processes SAML Response sent by the Identity Provider after user authentication, validating the response and extracting user information.
74
75
```python { .api }
76
def process_response(self, request_id: str = None) -> None:
77
"""
78
Process SAML Response from IdP after authentication.
79
80
Parameters:
81
- request_id: ID of the AuthNRequest sent by this SP
82
83
Raises:
84
- OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND: No SAMLResponse in POST data
85
"""
86
```
87
88
**Usage Example:**
89
```python
90
# Process SAML response in ACS endpoint
91
auth = OneLogin_Saml2_Auth(request_data, settings)
92
auth.process_response()
93
94
if auth.is_authenticated():
95
# Authentication successful
96
user_attributes = auth.get_attributes()
97
user_id = auth.get_nameid()
98
session_index = auth.get_session_index()
99
else:
100
# Authentication failed
101
errors = auth.get_errors()
102
error_reason = auth.get_last_error_reason()
103
```
104
105
### Single Logout (SLO) Initiation
106
107
Initiates the SAML Single Logout process, redirecting users to the Identity Provider for session termination.
108
109
```python { .api }
110
def logout(self, return_to: str = None, name_id: str = None, session_index: str = None, nq: str = None, name_id_format: str = None, spnq: str = None) -> str:
111
"""
112
Initiate SLO process by building a logout request.
113
114
Parameters:
115
- return_to: Target URL for redirection after logout
116
- name_id: NameID for the LogoutRequest
117
- session_index: SessionIndex identifying user session
118
- nq: IdP Name Qualifier
119
- name_id_format: NameID Format for LogoutRequest
120
- spnq: SP Name Qualifier
121
122
Returns:
123
Redirection URL to IdP for logout
124
125
Raises:
126
- OneLogin_Saml2_Error.SAML_SINGLE_LOGOUT_NOT_SUPPORTED: IdP doesn't support SLO
127
"""
128
```
129
130
### SAML Logout Processing
131
132
Processes SAML Logout Response or Logout Request sent by the Identity Provider during the SLO workflow.
133
134
```python { .api }
135
def process_slo(self, keep_local_session: bool = False, request_id: str = None, delete_session_cb: callable = None) -> str:
136
"""
137
Process SAML Logout Response or Logout Request from IdP.
138
139
Parameters:
140
- keep_local_session: Whether to preserve local session
141
- request_id: ID of LogoutRequest sent by this SP
142
- delete_session_cb: Callback function to delete session
143
144
Returns:
145
Redirection URL or None
146
147
Raises:
148
- OneLogin_Saml2_Error.SAML_LOGOUTMESSAGE_NOT_FOUND: No logout message found
149
"""
150
```
151
152
**Usage Example:**
153
```python
154
# Process logout in SLS endpoint
155
auth = OneLogin_Saml2_Auth(request_data, settings)
156
157
def clear_user_session():
158
# Custom session cleanup logic
159
session.clear()
160
161
redirect_url = auth.process_slo(delete_session_cb=clear_user_session)
162
if redirect_url:
163
# Redirect user to continue logout flow
164
pass
165
```
166
167
### Authentication Status Checking
168
169
Verifies if the user has been successfully authenticated through the SAML process.
170
171
```python { .api }
172
def is_authenticated(self) -> bool:
173
"""
174
Check if user is authenticated.
175
176
Returns:
177
True if authenticated, False otherwise
178
"""
179
```
180
181
### User Attribute Retrieval
182
183
Extracts user attributes from SAML assertions for application use.
184
185
```python { .api }
186
def get_attributes(self) -> dict:
187
"""
188
Get all SAML attributes from assertion.
189
190
Returns:
191
Dictionary mapping attribute names to lists of values
192
"""
193
194
def get_friendlyname_attributes(self) -> dict:
195
"""
196
Get SAML attributes indexed by FriendlyName.
197
198
Returns:
199
Dictionary mapping FriendlyNames to lists of values
200
"""
201
202
def get_attribute(self, name: str) -> list:
203
"""
204
Get specific SAML attribute by name.
205
206
Parameters:
207
- name: Attribute name to retrieve
208
209
Returns:
210
List of attribute values or None
211
"""
212
213
def get_friendlyname_attribute(self, friendlyname: str) -> list:
214
"""
215
Get specific SAML attribute by FriendlyName.
216
217
Parameters:
218
- friendlyname: FriendlyName to search for
219
220
Returns:
221
List of attribute values or None
222
"""
223
```
224
225
### NameID and Session Information
226
227
Retrieves user identification and session details from SAML assertions.
228
229
```python { .api }
230
def get_nameid(self) -> str:
231
"""
232
Get NameID from SAML assertion.
233
234
Returns:
235
NameID string or None
236
"""
237
238
def get_nameid_format(self) -> str:
239
"""
240
Get NameID Format from assertion.
241
242
Returns:
243
NameID Format string or None
244
"""
245
246
def get_nameid_nq(self) -> str:
247
"""
248
Get NameID NameQualifier from assertion.
249
250
Returns:
251
NameID NameQualifier string or None
252
"""
253
254
def get_nameid_spnq(self) -> str:
255
"""
256
Get NameID SP NameQualifier from assertion.
257
258
Returns:
259
NameID SP NameQualifier string or None
260
"""
261
262
def get_session_index(self) -> str:
263
"""
264
Get SessionIndex from AuthnStatement.
265
266
Returns:
267
SessionIndex string
268
"""
269
270
def get_session_expiration(self) -> int:
271
"""
272
Get SessionNotOnOrAfter from AuthnStatement.
273
274
Returns:
275
Unix/POSIX timestamp or None
276
"""
277
278
def get_last_assertion_not_on_or_after(self) -> int:
279
"""
280
Get NotOnOrAfter value of valid SubjectConfirmationData node.
281
282
Returns:
283
Unix/POSIX timestamp or None
284
"""
285
286
def get_last_assertion_issue_instant(self) -> int:
287
"""
288
Get IssueInstant of the last assertion processed.
289
290
Returns:
291
Unix/POSIX timestamp or None
292
"""
293
```
294
295
### Error Handling
296
297
Provides comprehensive error information when SAML operations fail.
298
299
```python { .api }
300
def get_errors(self) -> list:
301
"""
302
Get list of error codes if something went wrong.
303
304
Returns:
305
List of error strings
306
"""
307
308
def get_last_error_reason(self) -> str:
309
"""
310
Get reason for the last error.
311
312
Returns:
313
Error reason string or None
314
"""
315
```
316
317
### URL and Redirection Management
318
319
Manages URLs for SAML endpoints and user redirection.
320
321
```python { .api }
322
def get_sso_url(self) -> str:
323
"""
324
Get SSO URL endpoint of the IdP.
325
326
Returns:
327
SSO URL string
328
"""
329
330
def get_slo_url(self) -> str:
331
"""
332
Get SLO URL endpoint of the IdP.
333
334
Returns:
335
SLO URL string
336
"""
337
338
def redirect_to(self, url: str = None, parameters: dict = {}) -> str:
339
"""
340
Generate redirection URL with optional parameters.
341
342
Parameters:
343
- url: Target URL for redirection
344
- parameters: Extra parameters to pass in URL
345
346
Returns:
347
Redirection URL string
348
"""
349
```
350
351
### Request and Response Information
352
353
Retrieves metadata about processed SAML messages.
354
355
```python { .api }
356
def get_last_request_id(self) -> str:
357
"""
358
Get ID of the last SAML request generated.
359
360
Returns:
361
Request ID string
362
"""
363
364
def get_last_message_id(self) -> str:
365
"""
366
Get ID of the last SAML response processed.
367
368
Returns:
369
Message ID string
370
"""
371
372
def get_last_assertion_id(self) -> str:
373
"""
374
Get ID of the last assertion processed.
375
376
Returns:
377
Assertion ID string
378
"""
379
380
def get_last_authn_contexts(self) -> list:
381
"""
382
Get authentication contexts from last SAML Response.
383
384
Returns:
385
List of authentication context strings
386
"""
387
```
388
389
### XML Message Access
390
391
Provides access to raw SAML XML messages for debugging and logging.
392
393
```python { .api }
394
def get_last_response_xml(self, pretty_print_if_possible: bool = False) -> str:
395
"""
396
Get raw XML of last SAML response or logout response.
397
398
Parameters:
399
- pretty_print_if_possible: Whether to format XML nicely
400
401
Returns:
402
SAML response XML string or None
403
"""
404
405
def get_last_request_xml(self) -> str:
406
"""
407
Get raw XML sent in last SAML request.
408
409
Returns:
410
SAML request XML string or None
411
"""
412
```
413
414
### Configuration Management
415
416
Methods for managing SAML settings and configuration state.
417
418
```python { .api }
419
def get_settings(self) -> OneLogin_Saml2_Settings:
420
"""
421
Get the current SAML settings object.
422
423
Returns:
424
OneLogin_Saml2_Settings object containing all SAML configuration
425
"""
426
427
def set_strict(self, value: bool) -> None:
428
"""
429
Enable or disable strict validation mode.
430
431
Parameters:
432
- value: Whether to enable strict mode
433
"""
434
```
435
436
### Digital Signature Management
437
438
Handles digital signatures for SAML message security.
439
440
```python { .api }
441
def add_request_signature(self, request_data: dict, sign_algorithm: str = OneLogin_Saml2_Constants.RSA_SHA256) -> None:
442
"""
443
Build signature for SAML requests.
444
445
Parameters:
446
- request_data: Request parameters to sign
447
- sign_algorithm: Signature algorithm method
448
"""
449
450
def validate_request_signature(self, request_data: dict) -> bool:
451
"""
452
Validate signature of SAML request.
453
454
Parameters:
455
- request_data: Request data to validate
456
457
Returns:
458
True if signature is valid, False otherwise
459
"""
460
```
461
462
## Usage Patterns
463
464
### Complete SSO Flow
465
```python
466
# 1. Initiate SSO
467
auth = OneLogin_Saml2_Auth(request_data, settings)
468
if 'sso' in request.form:
469
return redirect(auth.login())
470
471
# 2. Process response in ACS endpoint
472
elif 'SAMLResponse' in request.form:
473
auth.process_response()
474
if auth.is_authenticated():
475
session['user_id'] = auth.get_nameid()
476
session['attributes'] = auth.get_attributes()
477
return redirect('/dashboard')
478
else:
479
return f"Authentication failed: {auth.get_errors()}"
480
```
481
482
### Complete SLO Flow
483
```python
484
# 1. Initiate logout
485
if 'slo' in request.form:
486
return redirect(auth.logout())
487
488
# 2. Process logout in SLS endpoint
489
elif 'SAMLRequest' in request.form or 'SAMLResponse' in request.form:
490
url = auth.process_slo(delete_session_cb=lambda: session.clear())
491
if url:
492
return redirect(url)
493
else:
494
return redirect('/logged_out')
495
```