-
-
Notifications
You must be signed in to change notification settings - Fork 555
/
Copy pathazuread_b2c.py
185 lines (152 loc) · 6.46 KB
/
azuread_b2c.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
"""
Copyright (c) 2018 Noderabbit Inc., d.b.a. Appsembler
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
See https://nicksnettravels.builttoroam.com/post/2017/01/24/Verifying-Azure-Active-Directory-JWT-Tokens.aspx
for verifying JWT tokens.
"""
import json
from cryptography.hazmat.primitives import serialization
from jwt import DecodeError, ExpiredSignatureError, decode as jwt_decode, \
get_unverified_header
try:
from jwt.algorithms import RSAAlgorithm
except ImportError:
raise Exception(
# Python 3.3 is not supported because of compatibility in
# Cryptography package in Python3.3 You are welcome to patch
# and open a pull request.
'Cryptography library is required for this backend ' \
'(AzureADB2COAuth2) to work. Note that this backend is only ' \
'supported on Python 2 and Python 3.4+.'
)
from ..exceptions import AuthException, AuthTokenError
from .azuread import AzureADOAuth2
class AzureADB2COAuth2(AzureADOAuth2):
name = 'azuread-b2c-oauth2'
BASE_URL = 'https://{tenant_name}.b2clogin.com/{tenant_name}.onmicrosoft.com/{policy}'
AUTHORIZATION_URL = '{base_url}/oauth2/v2.0/authorize'
OPENID_CONFIGURATION_URL = '{base_url}/v2.0/.well-known/openid-configuration'
ACCESS_TOKEN_URL = '{base_url}/oauth2/v2.0/token'
JWKS_URL = '{base_url}/discovery/v2.0/keys'
DEFAULT_SCOPE = ['openid', 'email']
EXTRA_DATA = [
('access_token', 'access_token'),
('id_token', 'id_token'),
('refresh_token', 'refresh_token'),
('id_token_expires_in', 'expires'),
('exp', 'expires_on'),
('not_before', 'not_before'),
('given_name', 'first_name'),
('family_name', 'last_name'),
('tfp', 'policy'),
('token_type', 'token_type')
]
@property
def tenant_name(self):
return self.setting('TENANT_NAME', 'common')
@property
def policy(self):
policy = self.setting('POLICY')
if not policy or not policy.lower().startswith('b2c_'):
raise AuthException('SOCIAL_AUTH_AZUREAD_B2C_OAUTH2_POLICY is '
'required and should start with `b2c_`')
return policy
@property
def base_url(self):
return self.BASE_URL.format(tenant_name=self.tenant_name, policy=self.policy)
def openid_configuration_url(self):
return self.OPENID_CONFIGURATION_URL.format(base_url=self.base_url)
def authorization_url(self):
# Policy is required, but added later by `auth_extra_arguments()`
return self.AUTHORIZATION_URL.format(base_url=self.base_url)
def access_token_url(self):
return self.ACCESS_TOKEN_URL.format(base_url=self.base_url)
def jwks_url(self):
return self.JWKS_URL.format(base_url=self.base_url)
def request_access_token(self, *args, **kwargs):
"""
This is probably a hack, but otherwise AzureADOAuth2 expects
`access_token`.
However, B2C backends provides `id_token`.
"""
response = super().request_access_token(
*args,
**kwargs
)
if 'access_token' not in response:
response['access_token'] = response['id_token']
return response
def auth_extra_arguments(self):
"""
Return extra arguments needed on auth process.
The defaults can be overridden by GET parameters.
"""
extra_arguments = super().auth_extra_arguments()
extra_arguments['p'] = self.policy or self.data.get('p')
return extra_arguments
def jwt_key_to_pem(self, key_json_dict):
"""
Builds a PEM formatted key string from a JWT public key dict.
"""
pub_key = RSAAlgorithm.from_jwk(json.dumps(key_json_dict))
return pub_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
def get_user_id(self, details, response):
"""Use subject (sub) claim as unique id."""
return response.get('sub')
def get_user_details(self, response):
"""
Email address is returned on a different attribute for AzureAD
B2C backends.
"""
details = super().get_user_details(response)
if not details['email'] and response.get('emails'):
details['email'] = response['emails']
if isinstance(details.get('email'), (list, tuple)):
details['email'] = details['email'][0]
return details
def get_public_key(self, kid):
"""
Retrieve JWT keys from the URL.
"""
resp = self.request(self.jwks_url(), method='GET')
resp.raise_for_status()
# find the proper key for the kid
for key in resp.json()['keys']:
if key['kid'] == kid:
return self.jwt_key_to_pem(key)
raise DecodeError(f'Cannot find kid={kid}')
def user_data(self, access_token, *args, **kwargs):
response = kwargs.get('response')
id_token = response.get('id_token')
# `kid` is short for key id
kid = get_unverified_header(id_token)['kid']
key = self.get_public_key(kid)
try:
return jwt_decode(
id_token,
key=key,
algorithms=['RS256'],
audience=self.setting('KEY'),
leeway=self.setting('JWT_LEEWAY', default=0),
)
except (DecodeError, ExpiredSignatureError) as error:
raise AuthTokenError(self, error)