Skip to content

Define some Cloud Instance constants and the usage pattern of using them #433

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

Merged
merged 1 commit into from
Nov 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions msal/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,23 @@ def __init__(

:param str authority:
A URL that identifies a token authority. It should be of the format
https://login.microsoftonline.com/your_tenant
By default, we will use https://login.microsoftonline.com/common
``https://login.microsoftonline.com/your_tenant``
By default, we will use ``https://login.microsoftonline.com/common``

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By default, we will use https://login.microsoftonline.com/common

for CCA it should be tenanted and common should not be allowed?

Copy link
Collaborator Author

@rayluo rayluo Nov 4, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is true that AAD recommend to avoid "common" for confidential client, yet at the same time they can't really block such a usage due to backward compatibility concern.

We are essentially in the same boat here. Historically the input parameter authority is optional and defaults to that ".../common" value. We have, however, long been updated our samples to guide confidential app developers to use their tenant. See here and there. In practice, few people would read our API Reference doc (sad but true :-) ) but they will typically start from our samples. So, I think we are good.

UPDATE: Got some clarification that the "common" is not recommended for acquire_token_for_client(). We will emit a warning for that, in a separate PR #435.


*Changed in version 1.17*: you can also use predefined constant
and a builder like this::

from msal.authority import (
AuthorityBuilder,
AZURE_US_GOVERNMENT, AZURE_CHINA, AZURE_PUBLIC)
my_authority = AuthorityBuilder(AZURE_PUBLIC, "contoso.onmicrosoft.com")
# Now you get an equivalent of
# "https://login.microsoftonline.com/contoso.onmicrosoft.com"

# You can feed such an authority to msal's ClientApplication
from msal import PublicClientApplication
app = PublicClientApplication("my_client_id", authority=my_authority, ...)

:param bool validate_authority: (optional) Turns authority validation
on or off. This parameter default to true.
:param TokenCache cache:
Expand Down
26 changes: 24 additions & 2 deletions msal/authority.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,19 @@


logger = logging.getLogger(__name__)

# Endpoints were copied from here
# https://docs.microsoft.com/en-us/azure/active-directory/develop/authentication-national-cloud#azure-ad-authentication-endpoints
AZURE_US_GOVERNMENT = "login.microsoftonline.us"
AZURE_CHINA = "login.chinacloudapi.cn"
AZURE_PUBLIC = "login.microsoftonline.com"

WORLD_WIDE = 'login.microsoftonline.com' # There was an alias login.windows.net
WELL_KNOWN_AUTHORITY_HOSTS = set([
WORLD_WIDE,
'login.chinacloudapi.cn',
AZURE_CHINA,
'login-us.microsoftonline.com',
'login.microsoftonline.us',
AZURE_US_GOVERNMENT,
'login.microsoftonline.de',
])
WELL_KNOWN_B2C_HOSTS = [
Expand All @@ -30,6 +37,19 @@
]


class AuthorityBuilder(object):
def __init__(self, instance, tenant):
"""A helper to save caller from doing string concatenation.

Usage is documented in :func:`application.ClientApplication.__init__`.
"""
self._instance = instance.rstrip("/")
self._tenant = tenant.strip("/")

def __str__(self):
return "https://{}/{}".format(self._instance, self._tenant)


class Authority(object):
"""This class represents an (already-validated) authority.

Expand All @@ -53,6 +73,8 @@ def __init__(self, authority_url, http_client, validate_authority=True):
performed.
"""
self._http_client = http_client
if isinstance(authority_url, AuthorityBuilder):
authority_url = str(authority_url)
authority, self.instance, tenant = canonicalize(authority_url)
parts = authority.path.split('/')
is_b2c = any(self.instance.endswith("." + d) for d in WELL_KNOWN_B2C_HOSTS) or (
Expand Down
3 changes: 3 additions & 0 deletions tests/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ def get(self, url, params=None, headers=None, **kwargs):
return MinimalResponse(requests_resp=self.session.get(
url, params=params, headers=headers, timeout=self.timeout))

def close(self): # Not required, but we use it to avoid a warning in unit test
self.session.close()


class MinimalResponse(object): # Not for production use
def __init__(self, requests_resp=None, status_code=None, text=None):
Expand Down
35 changes: 28 additions & 7 deletions tests/test_authority.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,37 @@
@unittest.skipIf(os.getenv("TRAVIS_TAG"), "Skip network io during tagged release")
class TestAuthority(unittest.TestCase):

def _test_given_host_and_tenant(self, host, tenant):
c = MinimalHttpClient()
a = Authority('https://{}/{}'.format(host, tenant), c)
self.assertEqual(
a.authorization_endpoint,
'https://{}/{}/oauth2/v2.0/authorize'.format(host, tenant))
self.assertEqual(
a.token_endpoint,
'https://{}/{}/oauth2/v2.0/token'.format(host, tenant))
c.close()

def _test_authority_builder(self, host, tenant):
c = MinimalHttpClient()
a = Authority(AuthorityBuilder(host, tenant), c)
self.assertEqual(
a.authorization_endpoint,
'https://{}/{}/oauth2/v2.0/authorize'.format(host, tenant))
self.assertEqual(
a.token_endpoint,
'https://{}/{}/oauth2/v2.0/token'.format(host, tenant))
c.close()

def test_wellknown_host_and_tenant(self):
# Assert all well known authority hosts are using their own "common" tenant
for host in WELL_KNOWN_AUTHORITY_HOSTS:
a = Authority(
'https://{}/common'.format(host), MinimalHttpClient())
self.assertEqual(
a.authorization_endpoint,
'https://%s/common/oauth2/v2.0/authorize' % host)
self.assertEqual(
a.token_endpoint, 'https://%s/common/oauth2/v2.0/token' % host)
self._test_given_host_and_tenant(host, "common")

def test_wellknown_host_and_tenant_using_new_authority_builder(self):
self._test_authority_builder(AZURE_PUBLIC, "consumers")
self._test_authority_builder(AZURE_CHINA, "organizations")
self._test_authority_builder(AZURE_US_GOVERNMENT, "common")

@unittest.skip("As of Jan 2017, the server no longer returns V1 endpoint")
def test_lessknown_host_will_return_a_set_of_v1_endpoints(self):
Expand Down