-
-
Notifications
You must be signed in to change notification settings - Fork 572
Feature/azure oid backend #1183
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
stealthycole
wants to merge
9
commits into
python-social-auth:master
Choose a base branch
from
stealthycole:feature/azure-oid-backend
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
c86bf2a
Create azuread_oid backend
stealthycole d806425
Update CHANGELOG.md for Azure OID backend
stealthycole e5eb6ec
Add semantic version and tag
stealthycole c299d6f
Merge pull request #1 from stealthycole/Azure-OID-backend
stealthycole bbaaf47
Trimming duplicate class definitions
stealthycole fa67a90
Trimming duplicate class definitions
stealthycole 2d466ea
Fixing filename, removing extra imports, fixing v2 class
stealthycole 9caccc5
Fixing filename, removing extra imports, fixing v2 class
stealthycole 782eb7e
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| import base64 | ||
|
|
||
| from cryptography.hazmat.backends import default_backend | ||
| from cryptography.x509 import load_der_x509_certificate | ||
| from jwt import DecodeError, ExpiredSignatureError, get_unverified_header | ||
| from jwt import decode as jwt_decode | ||
|
|
||
| from social_core.exceptions import AuthTokenError | ||
|
|
||
| from .azuread import AzureADOAuth2 | ||
|
|
||
| """ | ||
| Copyright (c) 2015 Microsoft Open Technologies, Inc. | ||
|
|
||
| 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. | ||
| """ | ||
|
|
||
| """ | ||
| Azure AD OAuth2 backend, docs at: | ||
| https://python-social-auth.readthedocs.io/en/latest/backends/azuread.html | ||
|
|
||
| See https://nicksnettravels.builttoroam.com/post/2017/01/24/Verifying-Azure-Active-Directory-JWT-Tokens.aspx | ||
| for verifying JWT tokens. | ||
| """ | ||
|
|
||
|
|
||
| class AzureADOIDOAuth2(AzureADOAuth2): | ||
| name = "azuread-oid-oauth2" | ||
| OPENID_CONFIGURATION_URL = "{base_url}/.well-known/openid-configuration{appid}" | ||
| JWKS_URL = "{base_url}/discovery/keys{appid}" | ||
|
|
||
| @property | ||
| def tenant_id(self): | ||
| return self.setting("TENANT_ID", "common") | ||
|
|
||
| def openid_configuration_url(self): | ||
| return self.OPENID_CONFIGURATION_URL.format( | ||
| base_url=self.base_url, appid=self._appid() | ||
| ) | ||
|
|
||
| def jwks_url(self): | ||
| return self.JWKS_URL.format(base_url=self.base_url, appid=self._appid()) | ||
|
|
||
| def _appid(self) -> str: | ||
| return ( | ||
| f"?appid={self.setting('KEY')}" if self.setting("KEY") is not None else "" | ||
| ) | ||
|
|
||
| def get_certificate(self, kid): | ||
| # retrieve keys from jwks_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: | ||
| x5c = key["x5c"][0] | ||
| break | ||
| else: | ||
| raise DecodeError(f"Cannot find kid={kid}") | ||
|
|
||
| return load_der_x509_certificate(base64.b64decode(x5c), default_backend()) | ||
|
|
||
| def get_user_id(self, details, response): | ||
| """Use account oid as unique id.""" | ||
| return response.get("oid") | ||
|
|
||
| def user_data(self, access_token, *args, **kwargs): | ||
| response = kwargs.get("response") | ||
| if response and response.get("id_token"): | ||
| id_token = response.get("id_token") | ||
| else: | ||
| id_token = access_token | ||
|
|
||
| # get key id and algorithm | ||
| key_id = get_unverified_header(id_token)["kid"] | ||
|
|
||
| try: | ||
| # retrieve certificate for key_id | ||
| certificate = self.get_certificate(key_id) | ||
|
|
||
| return jwt_decode( | ||
| id_token, | ||
| key=certificate.public_key(), # type: ignore[reportArgumentType] | ||
| algorithms=["RS256"], | ||
| audience=self.setting("KEY"), | ||
| ) | ||
| except (DecodeError, ExpiredSignatureError) as error: | ||
| raise AuthTokenError(self, error) | ||
|
|
||
|
|
||
| class AzureADV2OIDOAuth2(AzureADOIDOAuth2): | ||
| name = "azuread-v2-OID-oauth2" | ||
| OPENID_CONFIGURATION_URL = "{base_url}/v2.0/.well-known/openid-configuration{appid}" | ||
| AUTHORIZATION_URL = "{base_url}/oauth2/v2.0/authorize" | ||
| ACCESS_TOKEN_URL = "{base_url}/oauth2/v2.0/token" | ||
| JWKS_URL = "{base_url}/discovery/v2.0/keys{appid}" | ||
| DEFAULT_SCOPE = ["openid", "profile", "offline_access"] | ||
|
|
||
| def get_user_id(self, details, response): | ||
| """Use upn as unique id""" | ||
| return response.get("preferred_username") | ||
|
|
||
| def get_user_details(self, response): | ||
| """Return user details from Azure AD account""" | ||
| fullname, first_name, last_name = ( | ||
| response.get("name", ""), | ||
| response.get("given_name", ""), | ||
| response.get("family_name", ""), | ||
| ) | ||
| return { | ||
| "username": fullname, | ||
| "email": response.get("preferred_username"), | ||
| "fullname": fullname, | ||
| "first_name": first_name, | ||
| "last_name": last_name, | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.