| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import binascii |
| 4 |
import logging |
| 5 |
from http import HTTPStatus |
| 6 |
|
| 7 |
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, JsonResponse |
| 8 |
from django.urls import reverse |
| 9 |
from django.utils.decorators import method_decorator |
| 10 |
from django.views import View |
| 11 |
from django.views.decorators.csrf import csrf_exempt |
| 12 |
|
| 13 |
from onelogin.saml2.auth import OneLogin_Saml2_Settings |
| 14 |
from onelogin.saml2.errors import OneLogin_Saml2_Error |
| 15 |
|
| 16 |
from allauth.account.adapter import get_adapter as get_account_adapter |
| 17 |
from allauth.account.internal.decorators import login_not_required |
| 18 |
from allauth.core.internal import httpkit |
| 19 |
from allauth.socialaccount.helpers import ( |
| 20 |
complete_social_login, |
| 21 |
render_authentication_error, |
| 22 |
) |
| 23 |
from allauth.socialaccount.providers.base.constants import AuthError, AuthProcess |
| 24 |
from allauth.socialaccount.providers.base.views import BaseLoginView |
| 25 |
from allauth.socialaccount.sessions import LoginSession |
| 26 |
|
| 27 |
from .utils import build_auth, build_saml_config, decode_relay_state, get_app_or_404 |
| 28 |
|
| 29 |
|
| 30 |
logger = logging.getLogger(__name__) |
| 31 |
|
| 32 |
|
| 33 |
class SAMLViewMixin: |
| 34 |
def get_app(self, organization_slug): |
| 35 |
app = get_app_or_404(self.request, organization_slug) |
| 36 |
return app |
| 37 |
|
| 38 |
def get_provider(self, organization_slug): |
| 39 |
app = self.get_app(organization_slug) |
| 40 |
return app.get_provider(self.request) |
| 41 |
|
| 42 |
|
| 43 |
@method_decorator(csrf_exempt, name="dispatch") |
| 44 |
@method_decorator(login_not_required, name="dispatch") |
| 45 |
class ACSView(SAMLViewMixin, View): |
| 46 |
def dispatch(self, request: HttpRequest, organization_slug) -> HttpResponse: |
| 47 |
url = reverse( |
| 48 |
"saml_finish_acs", |
| 49 |
kwargs={"organization_slug": organization_slug}, |
| 50 |
) |
| 51 |
response = HttpResponseRedirect(url) |
| 52 |
acs_session = LoginSession(request, "saml_acs_session", "saml-acs-session") |
| 53 |
acs_session.store.update({"request": httpkit.serialize_request(request)}) |
| 54 |
acs_session.save(response) |
| 55 |
return response |
| 56 |
|
| 57 |
|
| 58 |
acs = ACSView.as_view() |
| 59 |
|
| 60 |
|
| 61 |
@method_decorator(login_not_required, name="dispatch") |
| 62 |
class FinishACSView(SAMLViewMixin, View): |
| 63 |
def dispatch(self, request: HttpRequest, organization_slug) -> HttpResponse: |
| 64 |
provider = self.get_provider(organization_slug) |
| 65 |
acs_session = LoginSession(request, "saml_acs_session", "saml-acs-session") |
| 66 |
acs_request = None |
| 67 |
acs_request_data = acs_session.store.get("request") |
| 68 |
if acs_request_data: |
| 69 |
acs_request = httpkit.deserialize_request(acs_request_data, HttpRequest()) |
| 70 |
acs_session.delete() |
| 71 |
if not acs_request: |
| 72 |
logger.error("Unable to finish login, SAML ACS session missing") |
| 73 |
return render_authentication_error(request, provider) |
| 74 |
|
| 75 |
auth = build_auth(acs_request, provider) |
| 76 |
error_reason = None |
| 77 |
errors = [] |
| 78 |
try: |
| 79 |
# We're doing the check for a valid `InResponeTo` ourselves later on |
| 80 |
# (*) by checking if there is a matching state stashed. |
| 81 |
auth.process_response(request_id=None) |
| 82 |
except binascii.Error: |
| 83 |
errors = ["invalid_response"] |
| 84 |
error_reason = "Invalid response" |
| 85 |
except OneLogin_Saml2_Error as e: |
| 86 |
errors = ["error"] |
| 87 |
error_reason = str(e) |
| 88 |
if not errors: |
| 89 |
errors = auth.get_errors() |
| 90 |
if errors: |
| 91 |
# e.g. ['invalid_response'] |
| 92 |
error_reason = auth.get_last_error_reason() or error_reason |
| 93 |
logger.error( |
| 94 |
"Error processing SAML ACS response: %s: %s" |
| 95 |
% (", ".join(errors), error_reason) |
| 96 |
) |
| 97 |
return render_authentication_error( |
| 98 |
request, |
| 99 |
provider, |
| 100 |
extra_context={ |
| 101 |
"saml_errors": errors, |
| 102 |
"saml_last_error_reason": error_reason, |
| 103 |
}, |
| 104 |
) |
| 105 |
if not auth.is_authenticated(): |
| 106 |
return render_authentication_error( |
| 107 |
request, provider, error=AuthError.CANCELLED |
| 108 |
) |
| 109 |
login = provider.sociallogin_from_response(request, auth) |
| 110 |
# (*) If we (the SP) initiated the login, there should be a matching |
| 111 |
# state. |
| 112 |
state_id = auth.get_last_response_in_response_to() |
| 113 |
if state_id: |
| 114 |
login.state = provider.unstash_redirect_state(request, state_id) |
| 115 |
else: |
| 116 |
# IdP initiated SSO |
| 117 |
reject = provider.app.settings.get("advanced", {}).get( |
| 118 |
"reject_idp_initiated_sso", True |
| 119 |
) |
| 120 |
if reject: |
| 121 |
logger.error("IdP initiated SSO rejected") |
| 122 |
return render_authentication_error(request, provider) |
| 123 |
next_url = decode_relay_state(acs_request.POST.get("RelayState")) |
| 124 |
login.state["process"] = AuthProcess.LOGIN |
| 125 |
if next_url: |
| 126 |
login.state["next"] = next_url |
| 127 |
return complete_social_login(request, login) |
| 128 |
|
| 129 |
|
| 130 |
finish_acs = FinishACSView.as_view() |
| 131 |
|
| 132 |
|
| 133 |
@method_decorator(csrf_exempt, name="dispatch") |
| 134 |
@method_decorator(login_not_required, name="dispatch") |
| 135 |
class SLSView(SAMLViewMixin, View): |
| 136 |
def dispatch(self, request: HttpRequest, organization_slug) -> HttpResponse: |
| 137 |
provider = self.get_provider(organization_slug) |
| 138 |
auth = build_auth(self.request, provider) |
| 139 |
should_logout = request.user.is_authenticated |
| 140 |
account_adapter = get_account_adapter(request) |
| 141 |
|
| 142 |
def force_logout() -> None: |
| 143 |
account_adapter.logout(request) |
| 144 |
|
| 145 |
redirect_to = None |
| 146 |
error_reason = None |
| 147 |
try: |
| 148 |
redirect_to = auth.process_slo( |
| 149 |
delete_session_cb=force_logout, keep_local_session=not should_logout |
| 150 |
) |
| 151 |
# We do not validate ``redirect_to``: The IdP is a trusted party, |
| 152 |
# when using SAML the SP is configured to trust it. Restricting its |
| 153 |
# SLO redirect URL with ``is_safe_url`` (which typically only allows |
| 154 |
# same-origin URLs) could break legitimate cross-domain redirects |
| 155 |
# the IdP provides, e.g. redirecting back to the IdP's own logout |
| 156 |
# landing page. The python3-saml library already validates the SAML |
| 157 |
# response signature before returning the redirect URL. |
| 158 |
except OneLogin_Saml2_Error as e: |
| 159 |
error_reason = str(e) |
| 160 |
errors = auth.get_errors() |
| 161 |
if errors: |
| 162 |
error_reason = auth.get_last_error_reason() or error_reason |
| 163 |
logger.error( |
| 164 |
"Error processing SAML SLS response: %s: %s" |
| 165 |
% (", ".join(errors), error_reason) |
| 166 |
) |
| 167 |
resp = HttpResponse(error_reason, content_type="text/plain") |
| 168 |
resp.status_code = HTTPStatus.BAD_REQUEST |
| 169 |
return resp |
| 170 |
if not redirect_to: |
| 171 |
redirect_to = account_adapter.get_logout_redirect_url(request) |
| 172 |
return HttpResponseRedirect(redirect_to) |
| 173 |
|
| 174 |
|
| 175 |
sls = SLSView.as_view() |
| 176 |
|
| 177 |
|
| 178 |
@method_decorator(login_not_required, name="dispatch") |
| 179 |
class MetadataView(SAMLViewMixin, View): |
| 180 |
def dispatch(self, request: HttpRequest, organization_slug) -> HttpResponse: |
| 181 |
provider = self.get_provider(organization_slug) |
| 182 |
config = build_saml_config( |
| 183 |
self.request, provider.app.settings, organization_slug |
| 184 |
) |
| 185 |
saml_settings = OneLogin_Saml2_Settings( |
| 186 |
settings=config, sp_validation_only=True |
| 187 |
) |
| 188 |
metadata = saml_settings.get_sp_metadata() |
| 189 |
errors = saml_settings.validate_metadata(metadata) |
| 190 |
|
| 191 |
if len(errors) > 0: |
| 192 |
resp = JsonResponse({"errors": errors}) |
| 193 |
resp.status_code = HTTPStatus.INTERNAL_SERVER_ERROR |
| 194 |
return resp |
| 195 |
|
| 196 |
return HttpResponse(content=metadata, content_type="text/xml") |
| 197 |
|
| 198 |
|
| 199 |
metadata = MetadataView.as_view() |
| 200 |
|
| 201 |
|
| 202 |
@method_decorator(login_not_required, name="dispatch") |
| 203 |
class LoginView(SAMLViewMixin, BaseLoginView): |
| 204 |
def get_provider(self): |
| 205 |
app = self.get_app(self.kwargs["organization_slug"]) |
| 206 |
return app.get_provider(self.request) |
| 207 |
|
| 208 |
|
| 209 |
login = LoginView.as_view() |