Debian Codegraph @

allauth/socialaccount/providers/saml/provider.py

raw
1 from __future__ import annotations
2
3 from django.http import HttpRequest, HttpResponseRedirect
4 from django.urls import reverse
5 from django.utils.http import urlencode
6
7 from allauth.socialaccount.providers.base import Provider, ProviderAccount
8
9
10 class SAMLAccount(ProviderAccount):
11 pass
12
13
14 class SAMLProvider(Provider):
15 id = "saml"
16 name = "SAML"
17 supports_redirect = True
18 account_class = SAMLAccount
19 default_attribute_mapping = {
20 "uid": [
21 "urn:oasis:names:tc:SAML:attribute:subject-id",
22 ],
23 "email": [
24 "urn:oid:0.9.2342.19200300.100.1.3",
25 "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
26 ],
27 "email_verified": [
28 "http://schemas.auth0.com/email_verified",
29 ],
30 "first_name": [
31 "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname",
32 "urn:oid:2.5.4.42",
33 ],
34 "last_name": [
35 "urn:oid:2.5.4.4",
36 ],
37 "username": [
38 "http://schemas.auth0.com/nickname",
39 ],
40 }
41
42 def __init__(self, *args, **kwargs) -> None:
43 super().__init__(*args, **kwargs)
44 self.name = self.app.name or self.app.client_id or self.name
45
46 def get_login_url(self, request: HttpRequest, **kwargs):
47 url = reverse("saml_login", kwargs={"organization_slug": self.app.client_id})
48 if kwargs:
49 url = f"{url}?{urlencode(kwargs)}"
50 return url
51
52 def extract_extra_data(self, data):
53 return data.get_attributes()
54
55 def extract_uid(self, data):
56 """https://docs.oasis-open.org/security/saml-subject-id-attr/v1.0/csprd01/saml-subject-id-attr-v1.0-csprd01.html
57
58 Quotes:
59
60 "While the Attributes defined in this profile have as a goal the
61 explicit replacement of the <saml:NameID> element as a means of subject
62 identification, it is certainly possible to compose them with existing
63 NameID usage provided the same subject is being identified. This can
64 also serve as a migration strategy for existing applications."
65
66
67 "SAML does not define an identifier that meets all of these
68 requirements well. It does standardize a kind of NameID termed
69 “persistent” that meets some of them in the particular case of so-called
70 “pairwise” identification, where an identifier varies by relying
71 party. It has seen minimal adoption outside of a few contexts, and fails
72 at the “compact” and “simple to handle” criteria above, on top of the
73 disadvantages inherent with all NameID usage."
74
75 Overall, our strategy is to prefer a uid resulting from explicit
76 attribute mappings, and only if there is no such uid fallback to the
77 NameID.
78 """
79 uid = self._extract(data).get("uid")
80 if uid is None:
81 uid = data.get_nameid()
82 return uid
83
84 def extract_common_fields(self, data):
85 ret = self._extract(data)
86 ret.pop("uid", None)
87 return ret
88
89 def _extract(self, data):
90 provider_config = self.app.settings
91 raw_attributes = data.get_attributes()
92 attributes = {}
93 attribute_mapping = provider_config.get(
94 "attribute_mapping", self.default_attribute_mapping
95 )
96 # map configured provider attributes
97 for key, provider_keys in attribute_mapping.items():
98 if isinstance(provider_keys, str):
99 provider_keys = [provider_keys]
100 for provider_key in provider_keys:
101 attribute_list = raw_attributes.get(provider_key, None)
102 if attribute_list is not None and len(attribute_list) > 0:
103 attributes[key] = attribute_list[0]
104 break
105 email_verified = attributes.get("email_verified")
106 if email_verified:
107 email_verified = email_verified.lower() in ["true", "1", "t", "y", "yes"]
108 attributes["email_verified"] = email_verified
109
110 # If we did not find an email, check if the NameID contains the email.
111 if not attributes.get("email") and (
112 data.get_nameid_format()
113 == "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
114 # Alternatively, if `use_id_for_email` is true, then we always interpret the nameID as email
115 or provider_config.get("use_nameid_for_email", False)
116 ):
117 attributes["email"] = data.get_nameid()
118
119 return attributes
120
121 def redirect(
122 self, request: HttpRequest, process, next_url=None, data=None, **kwargs
123 ):
124 from allauth.socialaccount.providers.saml.utils import build_auth
125
126 auth = build_auth(request, self)
127 # If we pass `return_to=None` `auth.login` will use the URL of the
128 # current view.
129 redirect = auth.login(return_to="")
130 self.stash_redirect_state(
131 request,
132 process,
133 next_url,
134 data,
135 state_id=auth.get_last_request_id(),
136 **kwargs,
137 )
138 return HttpResponseRedirect(redirect)
139
140
141 provider_classes = [SAMLProvider]