
    #	h                       S SK r S SKrS SKrS SKrS SKrS SKrS SKJr  S SKJ	r	  S SK
Jr  S SKrSSKJrJr  SSKJr  SSKJrJr  SS	KJr  SS	KJr  SS
K7  SSKJrJrJr  S SKr SSK!J"r"  SSK#J$r$  SSK%J&r&  SSK'J(r(J)r)  \RT                  " \+5      r,Sr-S r.S r/S r0S r1S r2S r3S r4S r5S r6 " S S\5      r7S r8 " S S\95      r: " S S \:5      r; " S! S"\:5      r<g)#    N)Lock)Optional)urlparse   )ClientJwtAssertionCreator)decode_part)	Authority
WORLD_WIDE)send_request)*)
TokenCache_get_username_GRANT_TYPE_BROKER)_detect_region)ThrottledHttpClient)_is_running_in_cloud_shell)SKU__version__
CLOUDSHELLc                 @    SSK Jn  U (       a  UR                  5         g g )Nr   )broker) r   _enable_pii_log)enable_pii_logr   s     B/var/www/html/env/lib/python3.13/site-packages/msal/application.py_init_brokerr      s          c                     [         R                  SU [         R                  5      nU(       a   U Vs/ s H  o"R                  5       PM     sn$ SU ;   a  [	        S5      eU R                  5       /$ s  snf )NzI-----BEGIN CERTIFICATE-----(?P<cert_value>[^-]+)-----END CERTIFICATE-----zPRIVATE KEYz:We expect your public key but detect a private key instead)refindallIstrip
ValueError)public_cert_contentpublic_certificatescerts      r   extract_certsr(   #   ss     **TRTT# )<=)<

)<== ++HJ 	J%%'(( >s   A/c                     U (       d  U$ U(       a  [         R                  " U5      O0 nS H$  nUR                  U0 5      R                  SU 0S9  M&     [         R                  " U5      $ )N)access_tokenvalues)xms_cc)jsonloads
setdefaultupdatedumps)capabilitiesclaims_challengeclaims_dictkeys       r   (_merge_claims_challenge_and_capabilitiesr6   3   s\     2B$**-.KsB'..x6N.O  ::k""r   c                 4     U R                  SS9$ !   U s $ = f)Nzutf-8encoding)encode)raws    r   
_str2bytesr<   >   s$    zz7z++
s    c                 F   SSK JnJn  SSKJn  [        U S5       nUR                  UR                  5       U5      u  pgnS S S 5        W(       a  W(       d  [        S5      eUR                  UR                  R                  S9R                  5       n	SR                  U	R                  5       SS	 5      /n
UR                  UR!                  5       5      R#                  5       nUR                  UR%                  5       5      R#                  5       nXkX4$ ! , (       d  f       N= f)
Nr   )hashesserialization)pkcs12rbz5Your PFX file shall contain both private key and certr8   
r   )cryptography.hazmat.primitivesr>   r?   ,cryptography.hazmat.primitives.serializationr@   openload_key_and_certificatesreadr$   public_bytesEncodingPEMdecodejoin
splitlinesfingerprintSHA256hexSHA1)pfx_pathpassphrase_bytesr>   r?   r@   fprivate_keyr'   _cert_pemx5csha256_thumbprintsha1_thumbprints                r   
_parse_pfxr\   F   s    DC	h	%??FFH& (1 
 DPQQ  -*@*@*D*D ELLNH		(%%'"-.C ((9==?&&v{{}599;O??? 
	s   $D
D c                 X    SSK Jn  SSKJn  UR	                  [        U 5      UU" 5       S9$ )Nr   )r?   )default_backend)backend)rD   r?   cryptography.hazmat.backendsr^   load_pem_private_keyr<   )private_key_pem_strrT   r?   r^   s       r   _load_private_key_from_pem_strrc   Z   s2    <<--&'! . 
 
r   c                 P    U R                  S5      nSUS'   SR                  U5      $ )N.z********r   )splitrM   )home_account_idpartss     r   _pii_less_home_account_idri   d   s)    !!#&EE!H88E?r   c                    [        U [        5      (       a  SU ;   d  SU ;   a9  [        R                  " U R	                  S5      U R	                  S5      S.SS9U S'   U  Vs0 s H(  nUS:w  d  M  UR                  S5      (       a  M#  XU   _M*     nnSU ;   a'  [        [        R                  " 5       U S   -   5      US	'   U$ U $ s  snf )
N_msalruntime_telemetry_msal_python_telemetry)msalruntime_telemetrymsal_python_telemetry),:)
separatorsmsal_telemetry
refresh_inrW   
refresh_on)
isinstancedictr-   r1   get
startswithinttime)resultkreturn_values      r   	_clean_upr~   j   s    &$#v-1IV1S'+zz)/4L)M)/4L)M3 )(*F#$
 #)"(QL  LL% AayL& 	 
 6!),TYY[6,;O-O)PL&Ms   
C-C	Cc                  .   [         R                  S:w  a  gSn S[        R                  ;  nS[        R                  R	                  SS5      ;   nU(       d  U(       a  [        R
                  R                  U 5      (       an   SSKnSn [        UR	                  U5      UR                  5      nU(       d8  [        R                  S
X@5        UR                  USUR                  U 5      5        U$ g! UR                   a    S	n NVf = f! [         a     gf = f)zuRegister Edge and return a name suitable for subsequent webbrowser.get(...)
when appropriate. Otherwise return None.
linuxNz/usr/bin/microsoft-edgeBROWSERzmicrosoft-edger   r   z	msal-edgeFzRegister %s with %s)sysplatformosenvironrw   pathexists
webbrowserru   BackgroundBrowserErrorloggerdebugregisterImportError)browser_pathuser_has_no_preferenceuser_wont_mind_edger   browser_nameregistration_availables         r   _preferred_browserr   |   s   
 ||w,L
 'bjj8*bjjnnY.KK 	"5277>>,;W;W	&L/)3NN<0*2N2N*P& *2LO ## $
(D(D\(RT  ## /).&/  		s7   D %C/ -A D /DD DD 
DDc                   @   ^  \ rS rSrU 4S jrU 4S jrU 4S jrSrU =r$ )_ClientWithCcsRoutingInfo   c                 r   > UR                  S5      (       a  SUS   -  US'   [        [        U ]  " SSS0UD6$ )N
login_hintzUPN:%sX-AnchorMailboxclient_infor    )rw   superr   initiate_auth_code_flow)selfkwargs	__class__s     r   r   1_ClientWithCcsRoutingInfo.initiate_auth_code_flow   sL    ::l##(06,3G(GF$%.M  	r   c                 d  > [        U[        5      (       a  [        U[        5      (       d   eUR                  S0 5      nUR                  S5      (       a"  [        R
                  " [        US   5      5      O0 nSU;   a  SU;   a  SR                  " S0 UD6US'   [        [        U ]*  " X4SU0UD6$ )Nheadersr   uidutidzOid:{uid}@{utid}r   r   )ru   rv   poprw   r-   r.   r	   formatr   r   obtain_token_by_auth_code_flow)r   auth_code_flowauth_responser   r   r   r   s         r   r   8_ClientWithCcsRoutingInfo.obtain_token_by_auth_code_flow   s     .$//J}d4S4SSS**Y+ ""=11 jjm4579 	 KFk$9);)B)B)Q[)QG%&.TF3:F>DF 	Fr   c                 ~   > UR                  S0 5      nSR                  U5      US'   [        [        U ]  " X4SU0UD6$ )Nr   zupn:{}r   )r   r   r   r   !obtain_token_by_username_password)r   usernamepasswordr   r   r   s        r   r   ;_ClientWithCcsRoutingInfo.obtain_token_by_username_password   sO    **Y+%-__X%>!".W;(/;39; 	;r   r   )	__name__
__module____qualname____firstlineno__r   r   r   __static_attributes____classcell__r   s   @r   r   r      s    F; ;r   r   c                  
    SSK Jn   U R                  SSS9u  pn[        U5      S:  a  [        U5      S:  d  [        R
                  " S5        g g ! [         a     g [         a    [        R                  S	W  S
35         g f = f)Nr   )r   re      )maxsplitr      zRPlease upgrade msal-extensions. Only msal-extensions 1.2+ can work with msal 1.30+zmsal_extensions version z  not in major.minor.patch format)
msal_extensionsr   rf   ry   warningswarnr   r$   r   	exception)vmajorminorrW   s       r   _msal_extension_checkr      s    
Y4''#'2aE
aCJ!OMMEF %4   Y3A36VWXYs   AA 
B"BBc                      \ rS rSrSrSrSrSrSrSr	Sr
S	rS
rSrSrSrSrSrSrSrSrSrSr             S8S jrS rS r\" / SQ5      4S jr S9S jrS\\   4S jrS:S jr         S;S jr!        S<S jr" S=S  jr#   S>S! jr$S=S" jr%S# r&S$ r'S% r(S& r)S' r*S( r+S=S) jr,    S?S* jr-    S?S+ jr.    S?S, jr/     S@S- jr0S. r1S/ r2S0 r3SS1 SSS4S2 jr4S3 r5S4 r6  S9S5 jr7 S=S6 jr8S7r9g)AClientApplication   zYou do not usually directly use this class. Use its subclasses instead:
:class:`PublicClientApplication` and :class:`ConfidentialClientApplication`.
8485301523622730832169902903TFtoken_sourceidentity_providercacher   zauth_scheme is currently only available from broker. You can enable broker by following these instructions. https://msal-python.readthedocs.io/en/latest/#publicclientapplicationNc                    Xl         X l        Xl        Xl        UU l        U(       a8  [        U[        5      (       d#  [        SR                  [        U5      5      5      e[        U=(       d    / 5      U l        SU R                  ;   a#  [        SR                  [        U5      5      5      eU(       a  X`l        OSSKnUR                  5       U l        XpR                  l        XR                  l        ["        R$                  " U R                  R&                  U	S9U R                  l        UR(                  R+                  SS9nU R                  R-                  S	U5        U R                  R-                  S
U5        [/        U R                  U[        U [0        5      (       a  SOSS9U l        Xl        Xl        U(       a  U(       a  [        S5      e[        U[6        5      (       a+  [9        U5      R:                  R=                  S5      (       a  Un U=(       d    SR                  [>        5      n[A        UU R                  UU R                  US9U l!        U RK                  UU5        U=(       d
    [M        5       U l'        Xl(        SU l)        U RU                  X RB                  5      u  U l+        U l,        SU l-        0 U l.        [_        5       U l0        [c        5         g! [         a    e [D         aQ    U(       aH  U(       dA  U(       d  Uc7  [F        RH                  " S5      (       a  [A        WU R                  SS9U l!         Ne f = f)a7  Create an instance of application.

:param str client_id: Your app has a client_id after you register it on Microsoft Entra admin center.

:param client_credential:
    For :class:`PublicClientApplication`, you use `None` here.

    For :class:`ConfidentialClientApplication`,
    it supports many different input formats for different scenarios.

    .. admonition:: Support using a client secret.

        Just feed in a string, such as ``"your client secret"``.

    .. admonition:: Support using a certificate in X.509 (.pem) format

        Feed in a dict in this form::

            {
                "private_key": "...-----BEGIN PRIVATE KEY-----... in PEM format",
                "thumbprint": "A1B2C3D4E5F6...",
                "passphrase": "Passphrase if the private_key is encrypted (Optional. Added in version 1.6.0)",
            }

        MSAL Python requires a "private_key" in PEM format.
        If your cert is in PKCS12 (.pfx) format,
        you can convert it to X.509 (.pem) format,
        by ``openssl pkcs12 -in file.pfx -out file.pem -nodes``.

        The thumbprint is available in your app's registration in Azure Portal.
        Alternatively, you can `calculate the thumbprint <https://github.com/Azure/azure-sdk-for-python/blob/07d10639d7e47f4852eaeb74aef5d569db499d6e/sdk/identity/azure-identity/azure/identity/_credentials/certificate.py#L94-L97>`_.

    .. admonition:: Support Subject Name/Issuer Auth with a cert in .pem

        `Subject Name/Issuer Auth
        <https://github.com/AzureAD/microsoft-authentication-library-for-python/issues/60>`_
        is an approach to allow easier certificate rotation.

        *Added in version 0.5.0*::

            {
                "private_key": "...-----BEGIN PRIVATE KEY-----... in PEM format",
                "thumbprint": "A1B2C3D4E5F6...",
                "public_certificate": "...-----BEGIN CERTIFICATE-----...",
                "passphrase": "Passphrase if the private_key is encrypted (Optional. Added in version 1.6.0)",
            }

        ``public_certificate`` (optional) is public key certificate
        which will be sent through 'x5c' JWT header only for
        subject name and issuer authentication to support cert auto rolls.

        Per `specs <https://tools.ietf.org/html/rfc7515#section-4.1.6>`_,
        "the certificate containing
        the public key corresponding to the key used to digitally sign the
        JWS MUST be the first certificate.  This MAY be followed by
        additional certificates, with each subsequent certificate being the
        one used to certify the previous one."
        However, your certificate's issuer may use a different order.
        So, if your attempt ends up with an error AADSTS700027 -
        "The provided signature value did not match the expected signature value",
        you may try use only the leaf cert (in PEM/str format) instead.

    .. admonition:: Supporting raw assertion obtained from elsewhere

        *Added in version 1.13.0*:
        It can also be a completely pre-signed assertion that you've assembled yourself.
        Simply pass a container containing only the key "client_assertion", like this::

            {
                "client_assertion": "...a JWT with claims aud, exp, iss, jti, nbf, and sub..."
            }

    .. admonition:: Supporting reading client cerficates from PFX files

        *Added in version 1.29.0*:
        Feed in a dictionary containing the path to a PFX file::

            {
                "private_key_pfx_path": "/path/to/your.pfx",
                "passphrase": "Passphrase if the private_key is encrypted (Optional)",
            }

        The following command will generate a .pfx file from your .key and .pem file::

            openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.pem

    .. admonition:: Support Subject Name/Issuer Auth with a cert in .pfx

        *Added in version 1.30.0*:
        If your .pfx file contains both the private key and public cert,
        you can opt in for Subject Name/Issuer Auth like this::

            {
                "private_key_pfx_path": "/path/to/your.pfx",
                "public_certificate": True,
                "passphrase": "Passphrase if the private_key is encrypted (Optional)",
            }

:type client_credential: Union[dict, str, None]

:param dict client_claims:
    *Added in version 0.5.0*:
    It is a dictionary of extra claims that would be signed by
    by this :class:`ConfidentialClientApplication` 's private key.
    For example, you can use {"client_ip": "x.x.x.x"}.
    You may also override any of the following default claims::

        {
            "aud": the_token_endpoint,
            "iss": self.client_id,
            "sub": same_as_issuer,
            "exp": now + 10_min,
            "iat": now,
            "jti": a_random_uuid
        }

: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``

    *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 token_cache:
    Sets the token cache used by this ClientApplication instance.
    By default, an in-memory cache will be created and used.
:param http_client: (optional)
    Your implementation of abstract class HttpClient <msal.oauth2cli.http.http_client>
    Defaults to a requests session instance.
    Since MSAL 1.11.0, the default session would be configured
    to attempt one retry on connection error.
    If you are providing your own http_client,
    it will be your http_client's duty to decide whether to perform retry.

:param verify: (optional)
    It will be passed to the
    `verify parameter in the underlying requests library
    <http://docs.python-requests.org/en/v2.9.1/user/advanced/#ssl-cert-verification>`_
    This does not apply if you have chosen to pass your own Http client
:param proxies: (optional)
    It will be passed to the
    `proxies parameter in the underlying requests library
    <http://docs.python-requests.org/en/v2.9.1/user/advanced/#proxies>`_
    This does not apply if you have chosen to pass your own Http client
:param timeout: (optional)
    It will be passed to the
    `timeout parameter in the underlying requests library
    <http://docs.python-requests.org/en/v2.9.1/user/advanced/#timeouts>`_
    This does not apply if you have chosen to pass your own Http client
:param app_name: (optional)
    You can provide your application name for Microsoft telemetry purposes.
    Default value is None, means it will not be passed to Microsoft.
:param app_version: (optional)
    You can provide your application version for Microsoft telemetry purposes.
    Default value is None, means it will not be passed to Microsoft.
:param list[str] client_capabilities: (optional)
    Allows configuration of one or more client capabilities, e.g. ["CP1"].

    Client capability is meant to inform the Microsoft identity platform
    (STS) what this client is capable for,
    so STS can decide to turn on certain features.
    For example, if client is capable to handle *claims challenge*,
    STS may issue
    `Continuous Access Evaluation (CAE) <https://learn.microsoft.com/entra/identity/conditional-access/concept-continuous-access-evaluation>`_
    access tokens to resources,
    knowing that when the resource emits a *claims challenge*
    the client will be able to handle those challenges.

    Implementation details:
    Client capability is implemented using "claims" parameter on the wire,
    for now.
    MSAL will combine them into
    `claims parameter <https://openid.net/specs/openid-connect-core-1_0-final.html#ClaimsParameter>`_
    which you will later provide via one of the acquire-token request.

:param str azure_region: (optional)
    Instructs MSAL to use the Entra regional token service. This legacy feature is only available to
    first-party applications. Only ``acquire_token_for_client()`` is supported.

    Supports 4 values:

    1. ``azure_region=None`` - This default value means no region is configured.
       MSAL will use the region defined in env var ``MSAL_FORCE_REGION``.
    2. ``azure_region="some_region"`` - meaning the specified region is used.
    3. ``azure_region=True`` - meaning
       MSAL will try to auto-detect the region. This is not recommended.
    4. ``azure_region=False`` - meaning MSAL will use no region.

    .. note::
        Region auto-discovery has been tested on VMs and on Azure Functions. It is unreliable.
        Applications using this option should configure a short timeout.

        For more details and for the values of the region string
          see https://learn.microsoft.com/entra/msal/dotnet/resources/region-discovery-troubleshooting

    New in version 1.12.0.

:param list[str] exclude_scopes: (optional)
    Historically MSAL hardcodes `offline_access` scope,
    which would allow your app to have prolonged access to user's data.
    If that is unnecessary or undesirable for your app,
    now you can use this parameter to supply an exclusion list of scopes,
    such as ``exclude_scopes = ["offline_access"]``.

:param dict http_cache:
    MSAL has long been caching tokens in the ``token_cache``.
    Recently, MSAL also introduced a concept of ``http_cache``,
    by automatically caching some finite amount of non-token http responses,
    so that *long-lived*
    ``PublicClientApplication`` and ``ConfidentialClientApplication``
    would be more performant and responsive in some situations.

    This ``http_cache`` parameter accepts any dict-like object.
    If not provided, MSAL will use an in-memory dict.

    If your app is a command-line app (CLI),
    you would want to persist your http_cache across different CLI runs.
    The following recipe shows a way to do so::

        # Just add the following lines at the beginning of your CLI script
        import sys, atexit, pickle
        http_cache_filename = sys.argv[0] + ".http_cache"
        try:
            with open(http_cache_filename, "rb") as f:
                persisted_http_cache = pickle.load(f)  # Take a snapshot
        except (
                FileNotFoundError,  # Or IOError in Python 2
                pickle.UnpicklingError,  # A corrupted http cache file
                ):
            persisted_http_cache = {}  # Recover by starting afresh
        atexit.register(lambda: pickle.dump(
            # When exit, flush it back to the file.
            # It may occasionally overwrite another process's concurrent write,
            # but that is fine. Subsequent runs will reach eventual consistency.
            persisted_http_cache, open(http_cache_file, "wb")))

        # And then you can implement your app as you normally would
        app = msal.PublicClientApplication(
            "your_client_id",
            ...,
            http_cache=persisted_http_cache,  # Utilize persisted_http_cache
            ...,
            #token_cache=...,  # You may combine the old token_cache trick
                # Please refer to token_cache recipe at
                # https://msal-python.readthedocs.io/en/latest/#msal.SerializableTokenCache
            )
        app.acquire_token_interactive(["your", "scope"], ...)

    Content inside ``http_cache`` are cheap to obtain.
    There is no need to share them among different apps.

    Content inside ``http_cache`` will contain no tokens nor
    Personally Identifiable Information (PII). Encryption is unnecessary.

    New in version 1.16.0.

:param boolean instance_discovery:
    Historically, MSAL would connect to a central endpoint located at
    ``https://login.microsoftonline.com`` to acquire some metadata,
    especially when using an unfamiliar authority.
    This behavior is known as Instance Discovery.

    This parameter defaults to None, which enables the Instance Discovery.

    If you know some authorities which you allow MSAL to operate with as-is,
    without involving any Instance Discovery, the recommended pattern is::

        known_authorities = frozenset([  # Treat your known authorities as const
            "https://contoso.com/adfs", "https://login.azs/foo"])
        ...
        authority = "https://contoso.com/adfs"  # Assuming your app will use this
        app1 = PublicClientApplication(
            "client_id",
            authority=authority,
            # Conditionally disable Instance Discovery for known authorities
            instance_discovery=authority not in known_authorities,
            )

    If you do not know some authorities beforehand,
    yet still want MSAL to accept any authority that you will provide,
    you can use a ``False`` to unconditionally disable Instance Discovery.

    New in version 1.19.0.

:param boolean allow_broker:
    Deprecated. Please use ``enable_broker_on_windows`` instead.

:param boolean enable_pii_log:
    When enabled, logs may include PII (Personal Identifiable Information).
    This can be useful in troubleshooting broker behaviors.
    The default behavior is False.

    New in version 1.24.0.

:param str oidc_authority:
    *Added in version 1.28.0*:
    It is a URL that identifies an OpenID Connect (OIDC) authority of
    the format ``https://contoso.com/tenant``.
    MSAL will append ".well-known/openid-configuration" to the authority
    and retrieve the OIDC metadata from there, to figure out the endpoints.

    Note: Broker will NOT be used for OIDC authority.
z;Invalid exclude_scopes={}. It need to be a list of strings.openidz=Invalid exclude_scopes={}. You can not opt out "openid" scoper   N)timeoutr   )max_retrieszhttp://https://<      )
http_cachedefault_throttle_timez5You can not provide both authority and oidc_authorityz/dstsv2zhttps://{}/common/)validate_authorityinstance_discoveryoidc_authority_urlMSAL_FORCE_REGIONFr   )2	client_idclient_credentialclient_claims_client_capabilities_instance_discoveryru   listr$   r   repr	frozenset_exclude_scopeshttp_clientrequestsSessionverifyproxies	functoolspartialrequestadaptersHTTPAdaptermountr   PublicClientApplicationapp_nameapp_versionstrr   r   rx   r   r
   	authority	Exceptionr   getenv_decide_brokerr   token_cache_region_configured_region_detected_build_clientclient_regional_clientauthority_groups_telemetry_bufferr   _telemetry_lockr   )r   r   r   r   r   r   r   r   r   r   r   r   r   client_capabilitiesazure_regionexclude_scopesr   r   allow_brokerr   oidc_authorityr   aauthority_to_uses                           r   __init__ClientApplication.__init__   s   `
 #!2*$7!#5 *^T"B"BMTT^$&' '  ))=2>t+++OVV^$&' ' *'//1D&,#'.$ (1'8'8  (('(;D$
 !!--!-<A""9a0"":q1.! d$;<< #% CD !& iTUUi%%(9*=*B*B*M*M+ +&N	(S,@,G,G
,S&   #5#'#;#;#1DN0 	L.9&6*,". $-1-?-?~~./*T* $!##v5  	 	!. (RYY7J-K-K "+$$$'," 	s   AK A!M Mc                    U R                   =(       d    [        U [        5      nU(       a  U(       a  [        S5      eU(       a  [        R
                  " S[        5        U R                  =(       d    U=(       a    [        R                  S:H  nU=(       aK    U(       + =(       a=    U R                  R                  (       + =(       a    U R                  R                  (       + U l        U R                  (       a   [        U5        [        R#                  SU R                  5        g ! [         a    SU l        [        R!                  S5         NIf = f)Nz>allow_broker=True is only supported in PublicClientApplicationzgallow_broker is deprecated. Please use PublicClientApplication(..., enable_broker_on_windows=True, ...)win32FzGBroker is unavailable on this platform. We will fallback to non-broker.zBroker enabled? %s)r   ru   ConfidentialClientApplicationr$   r   r   DeprecationWarning_enable_brokerr   r   r   is_adfs_is_b2cr   RuntimeErrorr   warningr   )r   r  r   is_confidential_appopted_in_for_brokers        r   r    ClientApplication._decide_broker  s   "44 1
/91<]^^MM
 #$  6 4S\\W4 	   +''+NN***+ NN***	 	 7^, 	)4+>+>?   7&+#677s   9D% %&EEc                     U R                   $ )zFReturns True if this client supports Proof-of-Possession Access Token.r  )r   s    r   is_pop_supported"ClientApplication.is_pop_supported  s    """r   )r   profileoffline_accessc                    [        U[        [        [        45      (       d  [	        S5      e[        U5      nX2-  (       a-  [	        SR                  [        U5      [        U5      5      5      eX2-  nX@R                  -  n[        U5      $ )Nz0The input scopes should be a list, tuple, or setzUYou cannot use any scope value that is reserved.
Your input: {}
The reserved list: {})ru   r   settupler$   r   r   )r   scopesreserved_scope	scope_set	decorateds        r   _decorate_scope!ClientApplication._decorate_scope  s     &4e"455OPPK	% Yn1EFH H .	)))	Ir   c                 j    [         R                  R                  U R                  U R                  UX#S9$ )Ncorrelation_idrefresh_reason)msal	telemetry_TelemetryContextr  r  )r   api_idr.  r/  s       r   _build_telemetry_context*ClientApplication._build_telemetry_context  s6    ~~//""D$8$8&) 0 J 	Jr   returnc                    U R                   SL a  g U R                   c$  [        R                  " S5      =(       d    S U l         U R                  =(       d$    [	        U R                   b  U R
                  OS 5      U l        U R                   U R                  :w  ae  U R                   U R                  :w  aK  [        R                  SR                  [        U R                   5      [        U R                  5      5      5        U R                   U R                  :X  a  U R                  OU R                   n[        R                  SR                  [        U5      5      5        U(       aj  UR                  S;   a  SR                  U5      OSR                  X!R                  5      n[        SR                  X1R                  5      U R
                  SS	9$ g )
NFr   z.Region configured ({}) != region detected ({})zRegion to be used: {})zlogin.microsoftonline.comzlogin.microsoft.comzlogin.windows.netzsts.windows.netz{}.login.microsoft.comz{}.{}https://{}/{}r   )r   r   r   r  r   r   ATTEMPT_REGION_DISCOVERYr   r  r   r   r   instancer
   tenant)r   central_authorityregion_to_useregional_hosts       r   _get_regional_authority)ClientApplication._get_regional_authority  s   ""e+""*&(ii0C&D&LD# $ 5 5 !O $ 7 7 CD:O##t'D'DD++t/D/DDNNKRRT,,-tD4I4I/JL M &&$*G*GG !!(( 	 	,33D4GHI$-- 2  6<<]K ^^M3M3MN  &&}6N6NO  #( 
 r   c                   ^ ^ S nS n[         [        [        R                  SS.nT R                  (       a  T R                  US'   T R
                  (       a  T R
                  US'   SS0n[        U[        5      (       Ga  [        R                  nUR                  S5      (       a  US   nGO0 nS =pUR                  S5      (       a  [        US   5      OS nUR                  S	5      (       a2  [        US	   U5      u  ppUR                  S
5      SL a  U(       a  XS'   OYUR                  S5      (       a8  UR                  S5      (       a"  US   n	U(       a  [        US   U5      nOUS   nO[        S5      eSU;  a5  [        UR                  S
5      [        5      (       a  [!        US
   5      US'   U
(       a  TR"                  (       d  SU
S.nOU	(       d  [        S5      eSU	S.n[%        U4SU0UD6nUR'                  TR(                  T R*                  T R,                  =(       d    0 S9nOXS'   TR.                  TR(                  TR0                  S.n[3        UT R*                  T R4                  UUUUUU 4S jT R6                  R8                  T R6                  R:                  S9
nS nU(       a  U(       d  T R=                  T5      nU(       aw  UR.                  UR(                  UR0                  S.n[3        UT R*                  T R4                  UUUUUU 4S jT R6                  R8                  T R6                  R:                  S9
nUU4$ )Nzretry-after, h429)zx-client-skuzx-client-verzx-client-oszx-ms-lib-capabilityz
x-app-namez	x-app-verr   r   client_assertion
passphraseprivate_key_pfx_pathpublic_certificateTrY   rV   
thumbprintzclient_credential needs to follow this format https://msal-python.readthedocs.io/en/latest/#msal.ClientApplication.params.client_credentialPS256)	algorithmrZ   z'You shall provide a thumbprint in SHA1.RS256)rH  r[   r   )audienceissueradditional_claimsclient_secret)authorization_endpointtoken_endpointdevice_authorization_endpointc                 ^   > TR                   R                  [        U TR                  S95      $ Nenvironmentr   addrv   r:  eventr   r   s    r   <lambda>1ClientApplication._build_client.<locals>.<lambda>S  s)    d.>.>.B.B49#5#5D7 /8r   )r   default_headersdefault_bodyrB  client_assertion_typeon_obtaining_tokenson_removing_rton_updating_rtc                 ^   > TR                   R                  [        U TR                  S95      $ rR  rU  rW  s    r   rY  rZ  k  s*    d6F6F6J6J49+=+=L? 7@r   )r   r   r   r   r   r   ru   rv   r   CLIENT_ASSERTION_TYPE_JWTrw   r<   r\   rc   r$   r   r(   r  r   create_regenerative_assertionrO  r   r   rN  rP  r   r   r   	remove_rt	update_rtr?  )r   r   r   skip_regional_clientrB  r]  r[  r\  r   r[   rZ   rT   rV   rY   assertion_params	assertioncentral_configurationcentral_clientregional_clientregional_authorityregional_configurations   ` `                  r   r  ClientApplication._build_client  sl    $<<#6

 ==,0MMOL)+/+;+;OK(%q)'..$*$D$D! !$$%788#45G#H 6:: +..|<< $.%l3$BF ! %(()?@@KU)*@A(L*HKO ),,-ABdJs),)--m<<-11,??&7&EO'&D-m<>N'P '8&F$xy y ("#4#8#89M#NPSTT%23DEY3Z%[GEN$Y->->%,CT($ +()RSS%,($ 0F)0F4DF	#,#J#J&55dnn&*&8&8&>B $K $@  ->)&/&F&F'66-6-T-T!
 3!NN((+%-"7!8++55++557 ,!%!=!=i!H!.@.W.W&8&G&G*HH	*& #<*NN $ 0 0$3!-%5*?)@#'#3#3#=#=#'#3#3#=#=#? ..r   c
                     [        SU R                  R                  0U R                  U R                  S9n
U
R                  X#UUU R                  U5      U[        U R                  U5      UU	S9	nX{S'   U$ )a  Initiate an auth code flow.

Later when the response reaches your redirect_uri,
you can use :func:`~acquire_token_by_auth_code_flow()`
to complete the authentication/authorization.

:param list scopes:
    It is a list of case-sensitive strings.
:param str redirect_uri:
    Optional. If not specified, server will use the pre-registered one.
:param str state:
    An opaque value used by the client to
    maintain state between the request and callback.
    If absent, this library will automatically generate one internally.
:param str prompt:
    By default, no prompt value will be sent, not even string ``"none"``.
    You will have to specify a value explicitly.
    Its valid values are the constants defined in
    :class:`Prompt <msal.Prompt>`.

:param str login_hint:
    Optional. Identifier of the user. Generally a User Principal Name (UPN).
:param domain_hint:
    Can be one of "consumers" or "organizations" or your tenant domain "contoso.com".
    If included, it will skip the email-based discovery process that user goes
    through on the sign-in page, leading to a slightly more streamlined user experience.
    More information on possible values available in
    `Auth Code Flow doc <https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code>`_ and
    `domain_hint doc <https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-oapx/86fb452d-e34a-494e-ac61-e526e263b6d8>`_.

:param int max_age:
    OPTIONAL. Maximum Authentication Age.
    Specifies the allowable elapsed time in seconds
    since the last time the End-User was actively authenticated.
    If the elapsed time is greater than this value,
    Microsoft identity platform will actively re-authenticate the End-User.

    MSAL Python will also automatically validate the auth_time in ID token.

    New in version 1.15.

:param str response_mode:
    OPTIONAL. Specifies the method with which response parameters should be returned.
    The default value is equivalent to ``query``, which is still secure enough in MSAL Python
    (because MSAL Python does not transfer tokens via query parameter in the first place).
    For even better security, we recommend using the value ``form_post``.
    In "form_post" mode, response parameters
    will be encoded as HTML form values that are transmitted via the HTTP POST method and
    encoded in the body using the application/x-www-form-urlencoded format.
    Valid values can be either "form_post" for HTTP POST to callback URI or
    "query" (the default) for HTTP GET with parameters encoded in query string.
    More information on possible values
    `here <https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes>`
    and `here <https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html#FormPostResponseMode>`

:return:
    The auth code flow. It is a dict in this form::

        {
            "auth_uri": "https://...",  // Guide user to visit this
            "state": "...",  // You may choose to verify it by yourself,
                             // or just let acquire_token_by_auth_code_flow()
                             // do that for you.
            "...": "...",  // Everything else are reserved and internal
        }

    The caller is expected to:

    1. somehow store this content, typically inside the current session,
    2. guide the end user (i.e. resource owner) to visit that auth_uri,
    3. and then relay this dict and subsequent auth response to
       :func:`~acquire_token_by_auth_code_flow()`.
rN  r   )	redirect_uristater   promptscopedomain_hintclaimsmax_ageresponse_moder3   )	r   r   rN  r   r   r   r*  r6   r   )r   r&  rq  rr  rs  r   ru  r3   rw  rx  r  flows               r   r   )ClientApplication.initiate_auth_code_flowq  s    j +%t~~'L'LMNN((* --%z&&v.#;))+;=' . 	 $4 r   c
                     U
R                  SS5      nU(       a  [        R                  " S5        U(       a  [        UU R                  U R
                  S9OU R                  n[        SUR                  0U R                  U R                  S9n[        R                  " S[        5        [        R                  " SS	9   UR                  UXCUUU R                  U5      UU[        U R                  U	5      S
9	sSSS5        $ ! , (       d  f       g= f)a  Constructs a URL for you to start a Authorization Code Grant.

:param list[str] scopes: (Required)
    Scopes requested to access a protected API (a resource).
:param str state: Recommended by OAuth2 for CSRF protection.
:param str login_hint:
    Identifier of the user. Generally a User Principal Name (UPN).
:param str redirect_uri:
    Address to return to upon receiving a response from the authority.
:param str response_type:
    Default value is "code" for an OAuth2 Authorization Code grant.

    You could use other content such as "id_token" or "token",
    which would trigger an Implicit Grant, but that is
    `not recommended <https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow#is-the-implicit-grant-suitable-for-my-app>`_.

:param str prompt:
    By default, no prompt value will be sent, not even string ``"none"``.
    You will have to specify a value explicitly.
    Its valid values are the constants defined in
    :class:`Prompt <msal.Prompt>`.
:param nonce:
    A cryptographically random value used to mitigate replay attacks. See also
    `OIDC specs <https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest>`_.
:param domain_hint:
    Can be one of "consumers" or "organizations" or your tenant domain "contoso.com".
    If included, it will skip the email-based discovery process that user goes
    through on the sign-in page, leading to a slightly more streamlined user experience.
    More information on possible values available in
    `Auth Code Flow doc <https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code>`_ and
    `domain_hint doc <https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-oapx/86fb452d-e34a-494e-ac61-e526e263b6d8>`_.
:param claims_challenge:
     The claims_challenge parameter requests specific claims requested by the resource provider
     in the form of a claims_challenge directive in the www-authenticate header to be
     returned from the UserInfo Endpoint and/or in the ID Token and/or Access Token.
     It is a string of a JSON object which contains lists of claims being requested from these locations.

:return: The authorization url as a string.
r   NzAWe haven't decided if this method will accept authority parameterr   rN  rp  zHChange your get_authorization_request_url() to initiate_auth_code_flow()Trecord)	response_typerq  rr  r   rs  rt  nonceru  rv  )r   r   r   r
   r   r   r   r   rN  r   r  catch_warningsbuild_auth_request_urir*  r6   r   )r   r&  r   rr  rq  r~  rs  r  ru  r3   r   r   the_authorityr  s                 r   get_authorization_request_url/ClientApplication.get_authorization_request_url  s    f JJ{D1	MMSU 	 "#77 !%	 	 +%}'K'KLNN((* 	+,>	@ $$D100+):**62'?--/?A 1 	 211s   <9C??
Dc                    U R                  UR                  S0 5      5        U R                  U R                  5      n[	        U R
                  R                  " UU4U(       a  U R                  U5      OSUR                  5       [        UR                  S0 5      [        U R                  UR                  SS5      5      S9S.UD65      nSU;   a  U R                  X`R                  '   UR                  U5        U$ )a  Validate the auth response being redirected back, and obtain tokens.

It automatically provides nonce protection.

:param dict auth_code_flow:
    The same dict returned by :func:`~initiate_auth_code_flow()`.
:param dict auth_response:
    A dict of the query string received from auth server.
:param list[str] scopes:
    Scopes requested to access a protected API (a resource).

    Most of the time, you can leave it empty.

    If you requested user consent for multiple resources, here you will
    need to provide a subset of what you required in
    :func:`~initiate_auth_code_flow()`.

    OAuth2 was designed mostly for singleton services,
    where tokens are always meant for the same resource and the only
    changes are in the scopes.
    In Microsoft Entra, tokens can be issued for multiple 3rd party resources.
    You can ask authorization code for multiple resources,
    but when you redeem it, the token is for only one intended
    recipient, called audience.
    So the developer need to specify a scope so that we can restrict the
    token to be issued for the corresponding audience.

:return:
    * A dict containing "access_token" and/or "id_token", among others,
      depends on what scope was used.
      (See https://tools.ietf.org/html/rfc6749#section-5.1)
    * A dict containing "error", optionally "error_description", "error_uri".
      (It is either `this <https://tools.ietf.org/html/rfc6749#section-4.1.2.1>`_
      or `that <https://tools.ietf.org/html/rfc6749#section-5.2>`_)
    * Most client-side data error would result in ValueError exception.
      So the usage pattern could be without any protocol details::

        def authorize():  # A controller in a web app
            try:
                result = msal_app.acquire_token_by_auth_code_flow(
                    session.get("flow", {}), request.args)
                if "error" in result:
                    return render_template("error.html", result)
                use(result)  # Token(s) are available in result and cache
            except ValueError:  # Usually caused by CSRF
                pass  # Simply ignore them
            return redirect(url_for("index"))
dataNr3   rv  rt  r   r  r*   )_validate_ssh_cert_input_datarw   r4  &ACQUIRE_TOKEN_BY_AUTHORIZATION_CODE_IDr~   r  r   r*  generate_headersrv   r   r6   r   _TOKEN_SOURCE_IDP_TOKEN_SOURCEupdate_telemetry)r   r   r   r&  r   telemetry_contextresponses          r   acquire_token_by_auth_code_flow1ClientApplication.acquire_token_by_auth_code_flow)  s    d 	**6::fb+AB 99779T[[GG
 39$&&v.d%668

62&?--"&&'94@BC
 
 
 X%+/+A+AH''(**84r   c                    [        U[        5      (       d   S5       eU R                  UR                  S0 5      5        [        R
                  " S[        5        [        R                  " SS9   U R                  U R                  5      n[        U R                  R                  " U4UU R                  U5      UR                  5       [        UR!                  S0 5      [#        U R$                  U5      S9US.UD65      nSU;   a  U R&                  XR(                  '   UR+                  U5        UsS	S	S	5        $ ! , (       d  f       g	= f)
a  The second half of the Authorization Code Grant.

:param code: The authorization code returned from Authorization Server.
:param list[str] scopes: (Required)
    Scopes requested to access a protected API (a resource).

    If you requested user consent for multiple resources, here you will
    typically want to provide a subset of what you required in AuthCode.

    OAuth2 was designed mostly for singleton services,
    where tokens are always meant for the same resource and the only
    changes are in the scopes.
    In Microsoft Entra, tokens can be issued for multiple 3rd party resources.
    You can ask authorization code for multiple resources,
    but when you redeem it, the token is for only one intended
    recipient, called audience.
    So the developer need to specify a scope so that we can restrict the
    token to be issued for the corresponding audience.

:param nonce:
    If you provided a nonce when calling :func:`get_authorization_request_url`,
    same nonce should also be provided here, so that we'll validate it.
    An exception will be raised if the nonce in id token mismatches.

:param claims_challenge:
    The claims_challenge parameter requests specific claims requested by the resource provider
    in the form of a claims_challenge directive in the www-authenticate header to be
    returned from the UserInfo Endpoint and/or in the ID Token and/or Access Token.
    It is a string of a JSON object which contains lists of claims being requested from these locations.

:return: A dict representing the json response from Microsoft Entra:

    - A successful response would contain "access_token" key,
    - an error response would contain "error" and usually "error_description".
Invalid parameter typer  zVChange your acquire_token_by_authorization_code() to acquire_token_by_auth_code_flow()Tr|  r  )rq  rt  r   r  r  r*   N)ru   r   r  rw   r   r   r  r  r4  r  r~   r  "obtain_token_by_authorization_coder*  r  rv   r   r6   r   r  r  r  )	r   coder&  rq  r  r3   r   r  r  s	            r   #acquire_token_by_authorization_code5ClientApplication.acquire_token_by_authorization_coden  s,   f &$''A)AA'**6::fb+AB34F	H $$D1 $ = =;;!= !O!O	"#/**62)::<JJvr*C113CEF 	" 	" 	H )/3/E/E++,..x8! 211s   -CD88
Ec                    U R                  U R                  R                  S9nU(       dD  U R                  U R                  R                  5       H  nU R                  US9nU(       d  M    O   U(       af  UR	                  5       nU Vs/ s H  nUS   R	                  5       U:X  d  M  UPM      nnU(       d$  [
        R                  SR                  U5      5        U$ s  snf )a  Get a list of accounts which previously signed in, i.e. exists in cache.

An account can later be used in :func:`~acquire_token_silent`
to find its tokens.

:param username:
    Filter accounts with this username only. Case insensitive.
:return: A list of account objects.
    Each account is a dict. For now, we only document its "username" field.
    Your app can choose to display those information to end user,
    and allow user to choose one of his/her accounts to proceed.
rS  r   zget_accounts(username='{}') finds no account. If tokens were acquired without 'profile' scope, they would contain no username for filtering. Consider calling get_accounts(username=None) instead.)_find_msal_accountsr   r:  _get_authority_aliaseslowerr   r   r   )r   r   accountsaliaslowercase_usernamer  s         r   get_accountsClientApplication.get_accounts  s     ++8O8O+P44T^^5L5LM333F8 N !)!1#+ @8aZ=&&(,>> 8H @L fX&( @s   
C)Cc                    [         R                  R                  [         R                  R                  /n[	        5       (       a  UR                  [        5        U R                  R                  [         R                  R                  SU0S9 Vs0 s H  nUS   U;   d  M  UR                  S5      UR                  S5      UR                  S5      UR                  S5      UR                  S5      UR                  S5      UR                  S5      UR                  S5      S	._M     nn[        UR                  5       5      $ s  snf )
NrT  queryauthority_typerg   r   account_sourcelocal_account_idrealm)rg   rT  r   r  r  r  r  )r   AuthorityTypeADFSMSSTSr   append_AUTHORITY_TYPE_CLOUDSHELLr   searchCredentialTypeACCOUNTrw   r   r+   )r   rT  interested_authority_typesr  grouped_accountss        r   r  %ClientApplication._find_msal_accounts  s/   $$)):+C+C+I+I&K"%''&--.HI %%,,))11$k2 - 44 !"&@@AEE#$'(uu->'?#$55#7 !j 1&'ee,<&= '(ee,<&=().@(AUU7^
4 	 $ $++-..%s   E BEc                     U R                   R                  SSS0S9nUR                  5         [        R                  " UR
                  5      S   $ )Nzhttps://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=https://login.microsoftonline.com/common/oauth2/authorizeAcceptzapplication/json)r   metadata)r   rw   raise_for_statusr-   r.   text)r   resps     r   _get_instance_metadata(ClientApplication._get_instance_metadata  sR    ## k12 $ 4 	zz$))$Z00r   c                 d   U R                   SL a  / $ U R                  R                  (       a  / $ U R                  (       d2  U R	                  5        Vs/ s H  n[        US   5      PM     snU l        U R                   H$  nX;   d  M
  U Vs/ s H  o3U:w  d  M
  UPM     sns  $    / $ s  snf s  snf )NFaliases)r   r   _is_known_to_developerr  r  r$  )r   r:  groupr  s       r   r  (ClientApplication._get_authority_aliases  s    ##u,I>>00 I$$373N3N3P%R3P%E)$%3P%RD!**E +0F5%X4E5FF + 	%R Gs   B(	B-B-c                     U R                   (       a9  SSKJn  U" U R                  US   5      nU(       a  [        R                  SU5        U R                  U5        g)z*Sign me out and forget me from token cacher   )_signout_silentlyr  z%_signout_silently() returns error: %sN)r  r   r  r   r   r   
_forget_me)r   accountr  errors       r   remove_account ClientApplication.remove_account  sB    1%dnng>P6QREDeL r   c                 Z   US   US   S.nU R                  US   5      nU R                  R                  [        R                  R
                  US9 Vs/ s HJ  nUS   U R                  :X  d2  UR                  S5      (       d  M.  UR                  S5      US   :X  d  MH  UPML     sn H  nU R                  R                  U5        M      [        U R                  R                  [        R                  R                  US95       H  nU R                  R                  U5        M      g s  snf )NrT  rg   rT  rg   r  r   	family_id)_get_app_metadatar   r  r   r  REFRESH_TOKENr   rw   rd  r   ACCESS_TOKEN	remove_at)r   home_accountowned_by_home_accountapp_metadatartats         r   	_sign_outClientApplication._sign_out  s1    (6+,=>!A --l=.IJ ))00))77?T 1 V	
V2 k?dnn4 $$[1  {+|K/HH  V	
B &&r*	
 t''..%%22:O / 
 B &&r*	
s   -D(D(D(c                    U R                  U5        US   US   S.n[        U R                  R                  [        R
                  R                  US95       H  nU R                  R                  U5        M      [        U R                  R                  [        R
                  R                  US95       H  nU R                  R                  U5        M      g )NrT  rg   r  r  )
r  r   r   r  r   r  ID_TOKEN
remove_idtr  r  )r   r  r  idtr  s        r   r  ClientApplication._forget_me5  s    |$'6+,=>!A ((//%%..6K 0 
 C '',	
 d&&--%%--5J . 
 A ++A.	r   c                 h   SSK Jn  U" U R                  XR                  US9nSU;  ak  U R                  R                  [        U R                  SU;   a  US   R                  5       OUU R                  R                  UU=(       d    0 [        S95        SU;   a  U R                  X@R                  '   U$ )Nr   )_obtain_token)r   r  r  rt  )r   rt  rO  r  r  r  r*   )
cloudshellr  r   r   r   rV  rv   rf   r   rO  r  _TOKEN_SOURCE_BROKERr  )r   r&  r  r  r  s        r   _acquire_token_by_cloud_shell/ClientApplication._acquire_token_by_cloud_shellF  s    - fTK("  ..3:h3Fhw'--/F#~~<<!ZR9"  X%+/+D+DH''(r   c           
      r    U(       d  g[        U R                  " X4X4XVS.UD65      nU(       a  SU;  a  U$ S$ )a^  Acquire an access token for given account, without user interaction.

It has same parameters as the :func:`~acquire_token_silent_with_error`.
The difference is the behavior of the return value.
This method will combine the cache empty and refresh error
into one return value, `None`.
If your app does not care about the exact token refresh error during
token cache look-up, then this method is easier and recommended.

:return:
    - A dict containing no "error" key,
      and typically contains an "access_token" key,
      if cache lookup succeeded.
    - None when cache lookup does not yield a token.
Nr   force_refreshr3   auth_schemer  r~    _acquire_token_silent_with_error)	r   r&  r  r   r  r3   r  r   r{   s	            r   acquire_token_silent&ClientApplication.acquire_token_silentW  sQ    0 4@@R'0-RJPR S  G6$9vCtCr   c           
      P    U(       d  g[        U R                  " X4X4XVS.UD65      $ )a  Acquire an access token for given account, without user interaction.

It is done either by finding a valid access token from cache,
or by finding a valid refresh token from cache and then automatically
use it to redeem a new access token.

This method will differentiate cache empty from token refresh error.
If your app cares the exact token refresh error during
token cache look-up, then this method is suitable.
Otherwise, the other method :func:`~acquire_token_silent` is recommended.

:param list[str] scopes: (Required)
    Scopes requested to access a protected API (a resource).
:param account: (Required)
    One of the account object returned by :func:`~get_accounts`.
    Starting from MSAL Python 1.23,
    a ``None`` input will become a NO-OP and always return ``None``.
:param force_refresh:
    If True, it will skip Access Token look-up,
    and try to find a Refresh Token to obtain a new Access Token.
:param claims_challenge:
    The claims_challenge parameter requests specific claims requested by the resource provider
    in the form of a claims_challenge directive in the www-authenticate header to be
    returned from the UserInfo Endpoint and/or in the ID Token and/or Access Token.
    It is a string of a JSON object which contains lists of claims being requested from these locations.
:param object auth_scheme:
    You can provide an ``msal.auth_scheme.PopAuthScheme`` object
    so that MSAL will get a Proof-of-Possession (POP) token for you.

    New in version 1.26.0.

:return:
    - A dict containing no "error" key,
      and typically contains an "access_token" key,
      if cache lookup succeeded.
    - None when there is simply no token in the cache.
    - A dict containing an "error" key, when token refresh failed.
Nr  r  )r   r&  r  r   r  r3   r  r   s           r   acquire_token_silent_with_error1ClientApplication.acquire_token_silent_with_errorv  s@    ^ >>R'0-RJPR S 	Sr   c           	         [        U[        5      (       d   S5       eU R                  UR                  S0 5      5        [        R
                  R                  5       nU(       a  [        R                  " S5        U R                  " XU R                  4UUUUS.UD6n	U	(       a  SU	;  a  U	$ U	n
U R                  U R                  R                  5       H  n[        U R                  R                  U R                  R                  R                   SU0S95      (       d  MM  [#        SU-   S	-   U R                  R$                  -   U R&                  S
S9nU R                  " XU4UUUUS.UD6n	U	(       d  M  SU	;  a  U	s  $ U	n
M     U
(       a7  U
R                  S5      (       a!  SSSSSS.R                  U
S   U
S   5      U
S'   U
$ )Nr  r  zEWe haven't decided how/if this method will accept authority parameter)r  r3   r.  r  r  rT  r  r   /Fr   suberrorr   )	bad_tokentoken_expiredprotection_policy_requiredclient_mismatchdevice_authentication_failedclassification)ru   r   r  rw   r0  r1  _get_new_correlation_idr   r   8_acquire_token_silent_from_cache_and_possibly_refresh_itr   r  r:  r   r  r  r  r
   r;  r   )r   r&  r  r   r  r3   r  r   r.  r{   final_resultr  r  s                r   r  2ClientApplication._acquire_token_silent_with_error  s    &$''A)AA'**6::fb+AB??AMMab NNT^^;H-)#	
  gV+M001H1HIE((//$$33AA )%0 0 2 3 3 %U"S(4>>+@+@@  #(M
 RR>K!1-'	
 F v&(!M%/ J0 L,,Z88!#.0#%02. #l:.Z0HI )* r   c	           	         S n
U(       Gd  U(       Gd  U(       Gd  U R                   UR                  UR                  U=(       d    0 R                  S5      S.nU	R                  S0 5      R                  S5      nU(       a  XS'   [        R                  " 5       n[
        R                  R                  nU R                  R                  U R                  R                  R                  UUS9 H  n[        US   5      U-
  nUS:  a  [
        R                  R                  nM6  [        R                  S5        S	US
   SUR                  SS5      S[        U5      U R                   U R"                  0n
SU;   a?  [        US   5      U
S'   [        US   5      U:  a  [
        R                  R$                  n  O@U R'                  S5      R)                  5         U
s  $    O[
        R                  R*                  nU(       d   S5       eU(       d	  SSKJn  U4n U	R                  S0 5      nU(       a;  UR                  S5      [0        :X  a"  U(       a  [3        S5      eU R5                  UUS9$ U R6                  (       a  U(       a  UR                  S5      [8        S 4;   a  SSKJn  U" SR?                  U R@                  R                  U R@                  R                  5      U R                   US   U4[C        U RD                  U5      UUS.UD6nU(       a>  UR                  S5      [8        :H  nSU;  nU(       d  U(       a  U RG                  UUU5      $ U(       a  [3        U RH                  5      eU(       a'  U RJ                  " X0RM                  U5      U4XUS.U	D6nOU RN                  " X4SU0U	D6nU(       a  S	U;   a  U RP                  UU R                   '   U(       a  SU;  d  U
(       d  U$  U
$ ! U a    U
(       d  e  U
$ f = f)Nrg   )r   rT  r  rg   r  key_id)targetr  
expires_oni,  zCache hit an ATr*   secret
token_typeBearer
expires_inrt   rC   z-It should have been established at this pointr   )RequestExceptionr  z+auth_scheme is not supported in Cloud Shellr  r  r   )_acquire_token_silentlyr8  r  )rv  r.  r  r  )r/  r3   r.  r3   ))r   r:  r;  rw   rz   r0  r1  	AT_ABSENTr   r  r  r  ry   
AT_EXPIREDr   r   r  _TOKEN_SOURCE_CACHEAT_AGINGr4  hit_an_access_tokenFORCE_REFRESHrequests.exceptionsr  r  r$   r  r  r   r   r  r   r   r6   r   _process_broker_response_AUTH_SCHEME_UNSUPPORTED>_acquire_token_silent_by_finding_rt_belongs_to_me_or_my_familyr*  _acquire_token_for_clientr  )r   r&  r  r   r  r3   r.  http_exceptionsr  r   access_token_from_cacher  r  nowr/  entryr   r  r  r  r  !account_was_established_by_broker!broker_attempt_succeeded_just_nowr{   s                           r   r  JClientApplication._acquire_token_silent_from_cache_and_possibly_refresh_it  s    #'!1[!%#,#5#5&--(/2':':;L'M	E ZZ+//9F"(h))+C!^^55N))00  //<<	 1  !|!45;
$%)^^%>%>N./"E(O %))L("C #j/&&(@(@	+'  5(<?l@S<T+L95./#5)-)@)@--b1EEG..36 "^^99NNNN~</1O0	::fb)D7;;'78<VV$%RSS99&t9LL""w7;;?O3P"U 4 <2#**4>>+B+BDNNDYDYZNN./		
 D113CE#1 +	 	 8?(9*-?9@58?x8O58<]#<<XvtTT !>!>??\\33F;W#1#1 	 77=M .F2-1-C-Ct))*7&0:Q ;R '&	  	* +&&		s!   AO. )C&O. BO. .P ?P c                 J   SU;  a  U R                   R                  [        U R                  SU;   a  US   R	                  5       OUU R
                  R                  UUUS   U R
                  R                  [        S95        U R                  XR                  '   [        U5      $ )Nr  rt  _account_id)r   rt  rO  r  r  r  rT  
grant_type)r   rV  rv   r   rf   r   rO  r:  r   r  r  r~   )r   r  r&  r  s       r   r  *ClientApplication._process_broker_responseX  s    ("  ..3:h3Fhw'--/F#~~<<!$]3 NN33-	" 	 ,0+D+DH''(""r   c           	         UR                   U=(       d    0 R                  S5      S.nU R                  UR                   5      nU(       d0  U R                  " X[	        USS94S S S.UD6nU(       a  SU;  a  U$ S nUR                  S	5      (       a.  U R                  " X[	        XVS	   S940 UD6=pU(       a  SU;  a  U$ U R                  " X[	        XPR
                  S
940 UD6=(       d    U$ )Nrg   r  1)r  c                     g Nr   rt_items    r   rY  bClientApplication._acquire_token_silent_by_finding_rt_belongs_to_me_or_my_family.<locals>.<lambda>x      4r   c                 ,    SU R                  S/ 5      ;   $ )Nr  error_additional_info)rw   r  s    r   rY  r   y  s     &6Mr)RRr   )
rt_removerbreak_conditionr  r  )r   )r:  rw   r  7_acquire_token_silent_by_finding_specific_refresh_tokenrv   r   )	r   r   r&  r  r   r  r  r  	last_resps	            r   r  PClientApplication._acquire_token_silent_by_finding_rt_belongs_to_me_or_my_familyg  s    %-- '2223DE
 --i.@.@A MMUc* 0!S	 B gR'		K((!YY4k9R#S I gR'	 KKtE^^D #"	#r   c                 J    U R                   R                  XR                  0 S9$ )N)rT  r   default)r   r  r   )r   rT  s     r   r  #ClientApplication._get_app_metadata  s+    11#~~r 2 K 	Kr   c                     g)NFr   r$  s    r   rY  ClientApplication.<lambda>  s    er   c	                 2  ^ ^ [        T R                  R                  T R                  R                  R                  US95      n
[
        R                  S[        U
5      UR                  5        VVs0 s H  u  pXS:X  a  U(       a  [        U5      OU_M!     snn5        S nU
(       d  U$ T R                  T R                  TSS9u  pT R                  T R                  XvS9n[        U
S SS9 GH  n[
        R                  S	5        UR                  5       nUR!                  S5      (       a'  S
R#                  US   R%                  SS5      5      US'   UR&                  " U4S S UU 4S jUU[)        U	R+                  S0 5      [-        T R.                  U5      S9S.U	D6nUR1                  U5        SU;  a  Us  $ [
        R                  SR#                  UR!                  S5      UR!                  S5      S95        U" U5      (       d  GM    U$    U$ s  snnf )Nr  zFound %d RTs matching %srg   T)rf  r-  c                 8    [        U R                  SS5      5      $ )Nlast_modification_time0)ry   rw   )es    r   rY  [ClientApplication._acquire_token_silent_by_finding_specific_refresh_token.<locals>.<lambda>  s    c!%%(@#"FGr   )r5   reversezCache attempts an RTzOid:{}re   @r   c                     U S   $ )Nr  r   )
token_items    r   rY  r4    s	    Jx4Hr   c                     g r  r   r  s    r   rY  r4    s    tr   c                 `   > TR                   R                  [        U TR                  SS95      $ )NT)rT  skip_account_creationrU  rW  s    r   rY  r4    s-    $2B2B2F2Ft ) 2 2*.H 3r   r  r  )	rt_getterr_  r^  rt  r   r  r  z,Refresh failed. {error}: {error_description}error_descriptionr  r=  )r   r   r  r  r  r   r   lenitemsri   r  r   r4  ACQUIRE_TOKEN_SILENT_IDsortedr  rw   r   replaceobtain_token_by_refresh_tokenrv   r   r6   r   r  )r   r   r&  r  r%  r&  r/  r.  r3   r   matchesr|   r   r  r  rW   r  r  r   s   ``                 r   r'  IClientApplication._acquire_token_silent_by_finding_specific_refresh_token  s8   
 t''..++99 /   	/W@
% 4E/E!(+QRR%@
 	
 O&&""ID ' J	 !99(() : J G	E
 LL/0'88:Gyy*++-5__+,44S#>.@)*;;!H3%
 JJvr*C113CEF  !H" ..x8h&LLGNNll7+"*,,/B"C O   x((IH e@
s   1&Hc                     UR                  S5      S:X  aC  UR                  S5      (       d  [        S5      eUR                  S5      (       d  [        S5      eg g )Nr  ssh-certreq_cnfzWhen requesting an SSH certificate, you must include a string parameter named 'req_cnf' containing the public key in JWK format (https://tools.ietf.org/html/rfc7517).r  zWhen requesting an SSH certificate, you must include a string parameter named 'key_id' which identifies the key in the 'req_cnf' argument.)rw   r$   )r   r  s     r   r  /ClientApplication._validate_ssh_cert_input_data  sd    88L!Z/88I&& => >
 88H%% JK K & 0r   c                    U R                  UR                  S0 5      5        U R                  U R                  [        R
                  R                  S9n[        U R                  R                  " U4U R                  U5      UR                  5       S SS S.UD65      nSU;   a  U R                  XPR                  '   UR                  U5        U$ )a  Acquire token(s) based on a refresh token (RT) obtained from elsewhere.

You use this method only when you have old RTs from elsewhere,
and now you want to migrate them into MSAL.
Calling this method results in new tokens automatically storing into MSAL.

You do NOT need to use this method if you are already using MSAL.
MSAL maintains RT automatically inside its token cache,
and an access token can be retrieved
when you call :func:`~acquire_token_silent`.

:param str refresh_token: The old refresh token, as a string.

:param list scopes:
    The scopes associate with this old RT.
    Each scope needs to be in the Microsoft identity platform (v2) format.
    See `Scopes not resources <https://docs.microsoft.com/en-us/azure/active-directory/develop/migrate-python-adal-msal#scopes-not-resources>`_.

:return:
    * A dict contains "error" and some other keys, when error happened.
    * A dict contains no "error" key means migration was successful.
r  r/  c                     U $ r  r   )r  s    r   rY  BClientApplication.acquire_token_by_refresh_token.<locals>.<lambda>  s    r   Fc                     g r  r   r  s    r   rY  rN    r!  r   )rt  r   r<  r`  r_  r*   )r  rw   r4  ACQUIRE_TOKEN_BY_REFRESH_TOKENr0  r1  r	  r~   r  rD  r*  r  r  r  r  )r   refresh_tokenr&  r   r  r  s         r   acquire_token_by_refresh_token0ClientApplication.acquire_token_by_refresh_token  s    . 	**6::fb+AB 99//>>77 : 9 T[[FF&&v.%668# /   X%+/+A+AH''(**84r   c                 D   [        U R                  U5      nU R                  (       a  SSKJn  U" SR                  U R                  R                  U R                  R                  5      U R                  UUUU R                  R                  (       d  U R                  SL a  SOSUUS9n	U R                  XUR                  S0 5      5      $ U(       a  [        U R                  5      eU R!                  U5      nU R#                  U R$                  5      n
U
R'                  5       n[)        UR+                  S0 5      US	9nSn	U R                  R,                  (       dj  U R                  R/                  X[0        R2                  R4                     S
9nUR                  S5      S:X  a!  [7        U R8                  " XU4UUUS.UD65      n	U	c*  [7        U R:                  R<                  " X4UUUS.UD65      n	SU	;   a  U R>                  XR@                  '   U
RC                  U	5        U	$ )a  Gets a token for a given resource via user credentials.

See this page for constraints of Username Password Flow.
https://github.com/AzureAD/microsoft-authentication-library-for-python/wiki/Username-Password-Authentication

:param str username: Typically a UPN in the form of an email address.
:param str password: The password.
:param list[str] scopes:
    Scopes requested to access a protected API (a resource).
:param claims_challenge:
    The claims_challenge parameter requests specific claims requested by the resource provider
    in the form of a claims_challenge directive in the www-authenticate header to be
    returned from the UserInfo Endpoint and/or in the ID Token and/or Access Token.
    It is a string of a JSON object which contains lists of claims being requested from these locations.

:param object auth_scheme:
    You can provide an ``msal.auth_scheme.PopAuthScheme`` object
    so that MSAL will get a Proof-of-Possession (POP) token for you.

    New in version 1.26.0.

:return: A dict representing the json response from Microsoft Entra:

    - A successful response would contain "access_token" key,
    - an error response would contain "error" and usually "error_description".
r   )_signin_silentlyr8  FnoN)MSALRuntime_UsernameMSALRuntime_PasswordvalidateAuthorityrv  r  r  r  r.  account_type	Federated)r&  r  r   r  r*   )"r6   r   r  r   rU  r   r   r:  r;  r   r  r   r  rw   r$   r  r*  r4  %ACQUIRE_TOKEN_BY_USERNAME_PASSWORD_IDr  rv   r   r  user_realm_discoveryr0  r1  CLIENT_REQUEST_IDr~   -_acquire_token_by_username_password_federatedr  r   r  r  r  )r   r   r   r&  r3   r  r   rv  rU  r  r  r   r  user_realm_results                 r   "acquire_token_by_username_password4ClientApplication.acquire_token_by_username_password  s   @ :))+;=0'&&t~~'>'>@U@UV%-%-NN99//58 #'?C'H 006::fVXCYZZT::;;%%f- 99668#446FJJvr*6:~~%% $ C C1Q1Q)R !D !T $$^4C$T%W%W%&/BH#&/ (.&/ 0  !N!N"*0" 	" H
 X%+/+A+AH''(**84r   c                 b  ^ ^ 0 nUR                  S5      (       a'  [        US   T R                  5      nUc  [        S5      e[        R                  SU5        [        TUUR                  SS5      UR                  SUR                  S5      5      UR                  S5      T R                  5      nS	U;   a  S
U;   d  [        SU-  5      eSn[        U[        T R                  R                  [        U[        T R                  R                  0R                  UR                  S
5      5      n	U	(       d  [        SUR                  S
5      5      eT R                  R                  R                  U	T R                  R                   5        T R                  R"                  " US	   U	4UU U4S jS.UD6$ )Nfederation_metadata_urlzUnable to find wstrust endpoint from MEX. This typically happens when attempting MSA accounts. More details available here. https://github.com/AzureAD/microsoft-authentication-library-for-python/wiki/Username-Password-Authenticationzwstrust_endpoint = %scloud_audience_urnzurn:federation:MicrosoftOnlineaddressfederation_active_auth_urlactiontokentypezUnsuccessful RSTR. %sz/urn:ietf:params:oauth:grant-type:saml1_1-bearerz$RSTR returned unknown token type: %sc                 t   > TR                   R                  [        U TR                  R                  TS95      $ )N)rT  r   )r   rV  rv   r   r:  )rX  r   r   s    r   rY  QClientApplication._acquire_token_by_username_password_federated.<locals>.<lambda>u  s1    d.>.>.B.B4 NN33!D /r   )rt  r^  )rw   mex_send_requestr   r$   r   r   wst_send_requestr  SAML_TOKEN_TYPE_V1SAML_TOKEN_TYPE_V2r  GRANT_TYPE_SAML2WSS_SAML_TOKEN_PROFILE_V1_1WSS_SAML_TOKEN_PROFILE_V2grant_assertion_encodersr/   encode_saml_assertionobtain_token_by_assertion)
r   ra  r   r   r&  r   wstrust_endpointwstrust_resultGRANT_TYPE_SAML1_1r  s
   ` `       r   r`  ?ClientApplication._acquire_token_by_username_password_federatedQ  s     !:;;/!";<   "  '  "C D D 	,.>?)h!!"68XY  !%%&BCE   *D,<,<> >)f.F6GHHN 2 < <');%t{{'C'C	
 c.$$V,- 	 68J8J68RT T,,7799	;{{447#Z7=!  	r   )r   r  r   r   r   r  r  r  r  r   r   r   r  r  r   r   r   r   r   )NNTNNTNNNNNNNNNNNNN)NN)F)NNNNNNNN)NNNr  NNNNr  NNN)NFNN)FNNNN):r   r   r   r   __doc__rA  rP  r]  ACQUIRE_TOKEN_ON_BEHALF_OF_IDACQUIRE_TOKEN_BY_DEVICE_FLOW_IDACQUIRE_TOKEN_FOR_CLIENT_IDr  ACQUIRE_TOKEN_INTERACTIVEGET_ACCOUNTS_IDREMOVE_ACCOUNT_IDr9  DISABLE_MSAL_FORCE_REGIONr  r  r  r  r  r  r  r   r  r   r*  r4  r   r
   r?  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r'  r  rR  rb  r`  r   r   r   r   r   r      s    #%)",1)$)!&+#"'-2* %O# %"M+!#N	P  HL/3;? $  ##g T%@N# %%LM0 ?CJ HY<O  Dj/^ !dR  !Pf 9=CR  !HT$L/21!+</"* !DF !3Sr !<F  ! m'^#$#LK -Ct;zK&R @D 	K\ AE)r   r   c                      ^  \ rS rSrSr\" 5       r SSSS.U 4S jjjr           SS jr   SS jr	SS jr
SS	 jrS
rU =r$ )r   i}  _correlation_idN)enable_broker_on_windowsenable_broker_on_macc                   > Ub  [        S5      e[        U=(       a    [        R                  S:H  =(       d    U=(       a    [        R                  S:H  5      U l        [
        [        U ]  " U4SS0UD6  g)a  Same as :func:`ClientApplication.__init__`,
except that ``client_credential`` parameter shall remain ``None``.

.. note::

    You may set enable_broker_on_windows and/or enable_broker_on_mac to True.

    **What is a broker, and why use it?**

    A broker is a component installed on your device.
    Broker implicitly gives your device an identity. By using a broker,
    your device becomes a factor that can satisfy MFA (Multi-factor authentication).
    This factor would become mandatory
    if a tenant's admin enables a corresponding Conditional Access (CA) policy.
    The broker's presence allows Microsoft identity platform
    to have higher confidence that the tokens are being issued to your device,
    and that is more secure.

    An additional benefit of broker is,
    it runs as a long-lived process with your device's OS,
    and maintains its own cache,
    so that your broker-enabled apps (even a CLI)
    could automatically SSO from a previously established signed-in session.

    **You shall only enable broker when your app:**

    1. is running on supported platforms,
       and already registered their corresponding redirect_uri

       * ``ms-appx-web://Microsoft.AAD.BrokerPlugin/your_client_id``
         if your app is expected to run on Windows 10+
       * ``msauth.com.msauth.unsignedapp://auth``
         if your app is expected to run on Mac

    2. installed broker dependency,
       e.g. ``pip install msal[broker]>=1.31,<2``.

    3. tested with ``acquire_token_interactive()`` and ``acquire_token_silent()``.

    **The fallback behaviors of MSAL Python's broker support**

    MSAL will either error out, or silently fallback to non-broker flows.

    1. MSAL will ignore the `enable_broker_...` and bypass broker
       on those auth flows that are known to be NOT supported by broker.
       This includes ADFS, B2C, etc..
       For other "could-use-broker" scenarios, please see below.
    2. MSAL errors out when app developer opted-in to use broker
       but a direct dependency "mid-tier" package is not installed.
       Error message guides app developer to declare the correct dependency
       ``msal[broker]``.
       We error out here because the error is actionable to app developers.
    3. MSAL silently "deactivates" the broker and fallback to non-broker,
       when opted-in, dependency installed yet failed to initialize.
       We anticipate this would happen on a device whose OS is too old
       or the underlying broker component is somehow unavailable.
       There is not much an app developer or the end user can do here.
       Eventually, the conditional access policy shall
       force the user to switch to a different device.
    4. MSAL errors out when broker is opted in, installed, initialized,
       but subsequent token request(s) failed.

:param boolean enable_broker_on_windows:
    This setting is only effective if your app is running on Windows 10+.
    This parameter defaults to None, which means MSAL will not utilize a broker.

    New in MSAL Python 1.25.0.

:param boolean enable_broker_on_mac:
    This setting is only effective if your app is running on Mac.
    This parameter defaults to None, which means MSAL will not utilize a broker.

    New in MSAL Python 1.31.0.
Nz,Public Client should not possess credentialsr  darwinr   )r$   boolr   r   r  r   r   r  )r   r   r   r  r  r   r   s         r   r   PublicClientApplication.__init__  ss    ` (KLL"$@)@ A#@(@B 	%t5	9)-	917	9r   c                    UR                  S0 5      nUR                  SS5      =(       a    UR                  S5      S:g  nU R                  U5        U(       d  S n[        5       (       a  US:X  a  U R	                  XS9$ [        U R                  U5      nU R                  (       aT  U
c  [        S
5      eU(       a  [        R                  S5        U R                  UU
UUUUUUUU	S9
nU R                  UX5      $ U(       a  [        U R                  5      eU" SS9  U R                  U R                  5      n[!        U R"                  R$                  " SU(       a  U R'                  U5      OS	USR)                  U=(       d    SS9UUU	UUUS.[+        UUS9UR-                  5       [/        5       S.UD65      nSU;   a  U R0                  UU R2                  '   UR5                  U5        U$ )a^  Acquire token interactively i.e. via a local browser.

Prerequisite: In Azure Portal, configure the Redirect URI of your
"Mobile and Desktop application" as ``http://localhost``.
If you opts in to use broker during ``PublicClientApplication`` creation,
your app also need this Redirect URI:
``ms-appx-web://Microsoft.AAD.BrokerPlugin/YOUR_CLIENT_ID``

:param list scopes:
    It is a list of case-sensitive strings.
:param str prompt:
    By default, no prompt value will be sent, not even string ``"none"``.
    You will have to specify a value explicitly.
    Its valid values are the constants defined in
    :class:`Prompt <msal.Prompt>`.
:param str login_hint:
    Optional. Identifier of the user. Generally a User Principal Name (UPN).
:param domain_hint:
    Can be one of "consumers" or "organizations" or your tenant domain "contoso.com".
    If included, it will skip the email-based discovery process that user goes
    through on the sign-in page, leading to a slightly more streamlined user experience.
    More information on possible values available in
    `Auth Code Flow doc <https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code>`_ and
    `domain_hint doc <https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-oapx/86fb452d-e34a-494e-ac61-e526e263b6d8>`_.

:param claims_challenge:
    The claims_challenge parameter requests specific claims requested by the resource provider
    in the form of a claims_challenge directive in the www-authenticate header to be
    returned from the UserInfo Endpoint and/or in the ID Token and/or Access Token.
    It is a string of a JSON object which contains lists of claims being requested from these locations.

:param int timeout:
    This method will block the current thread.
    This parameter specifies the timeout value in seconds.
    Default value ``None`` means wait indefinitely.

:param int port:
    The port to be used to listen to an incoming auth response.
    By default we will use a system-allocated port.
    (The rest of the redirect_uri is hard coded as ``http://localhost``.)

:param list extra_scopes_to_consent:
    "Extra scopes to consent" is a concept only available in Microsoft Entra.
    It refers to other resources you might want to prompt to consent for,
    in the same interaction, but for which you won't get back a
    token for in this particular operation.

:param int max_age:
    OPTIONAL. Maximum Authentication Age.
    Specifies the allowable elapsed time in seconds
    since the last time the End-User was actively authenticated.
    If the elapsed time is greater than this value,
    Microsoft identity platform will actively re-authenticate the End-User.

    MSAL Python will also automatically validate the auth_time in ID token.

    New in version 1.15.

:param int parent_window_handle:
    OPTIONAL.

    * If your app does not opt in to use broker,
      you do not need to provide a ``parent_window_handle`` here.

    * If your app opts in to use broker,
      ``parent_window_handle`` is required.

      - If your app is a GUI app running on Windows or Mac system,
        you are required to also provide its window handle,
        so that the sign-in window will pop up on top of your window.
      - If your app is a console app running on Windows or Mac system,
        you can use a placeholder
        ``PublicClientApplication.CONSOLE_WINDOW_HANDLE``.

    Most Python scripts are console apps.

    New in version 1.20.0.

:param function on_before_launching_ui:
    A callback with the form of
    ``lambda ui="xyz", **kwargs: print("A {} will be launched".format(ui))``,
    where ``ui`` will be either "browser" or "broker".
    You can use it to inform your end user to expect a pop-up window.

    New in version 1.20.0.

:param object auth_scheme:
    You can provide an ``msal.auth_scheme.PopAuthScheme`` object
    so that MSAL will get a Proof-of-Possession (POP) token for you.

    New in version 1.26.0.

:return:
    - A dict containing no "error" key,
      and typically contains an "access_token" key.
    - A dict containing an "error" key, when token refresh failed.
r  enable_msa_passthroughFr  rH  c                      g r  r   )r   s    r   rY  CPublicClientApplication.acquire_token_interactive.<locals>.<lambda>X  s    dr   noner  Nzparent_window_handle is required when you opted into using broker. You need to provide the window handle of your GUI application, or use msal.PublicClientApplication.CONSOLE_WINDOW_HANDLE when and only when your application is a console app.zLIgnoring parameter extra_scopes_to_consent, which is not supported by broker)rs  r   rw  browseruizhttp://localhost:{port}r   )port)rv  ru  r  )rt  extra_scope_to_consentrq  rs  r   rw  r   auth_paramsr  r   r   r*   r   )r   rw   r  r   r  r6   r   r  r$   r   r  %_acquire_token_interactive_via_brokerr  r  r4  r  r~   r  obtain_token_by_browserr*  r   rv   r  r   r  r  r  )r   r&  rs  r   ru  r3   r   r  extra_scopes_to_consentrw  parent_window_handleon_before_launching_uir  r   r  r  rv  r  r  s                      r   acquire_token_interactive1PublicClientApplication.acquire_token_interactive  s   ` zz&"%!'$ 
" 
"7 ((<(J6 	 	**40%%:"%''Ff,< 55f5HH9%%'79#+ LM M
 '78 AA$&&% B H 006HHT::;;), 99**,T[[@@ 28$&&v.d#:299YQ :   ! * d6*%668+-!" # $ X%+/+A+AHT''(**84r   c                    SSK JnJnJn  SU;   a  [        R                  US   5        SR                  U R                  R                  U R                  R                  5      nU R                  R                  (       d  U R                  SL a  SOS nU	(       ag  US:w  aa  U R                  U	S9n[        U5      S:X  aC  [        R                  S	5        U" UU R                  US
   S   U4UUS.UD6nU(       a  SU;  a  U$ US:X  d  U(       d  [        R                  S5        U" XR                  U4UUU
UUS.UD6n[        SU;   =(       a-    U	=(       a$    U	UR!                  S0 5      R!                  S5      :g  5      nSnU(       a  [        R                  U5        US:X  a  U(       d  U$ SUS.$ [        U5      SL d   eS
SKJn  ['        UR(                  UR*                  /5      nU(       d  SU;   a  UR!                  S5      U;   a  OU$ [        R                  S5        U" SS9  U" XR                  UX R,                  L a  S OU4UU	UUU
UUS.UD6$ )Nr   )_signin_interactivelyrU  r  welcome_templater8  FrV  select_account)r   z(Calling broker._acquire_token_silently()r   r  )rv  r  r  r  z!Calling broker._signin_silently())rY  rv  rw  enable_msa_ptr  r*   id_token_claimspreferred_usernamez=prompt="none" will not work for login_hint="non-default-user"broker_errorr>  )Response_Status_broker_statusz,Falls back to broker._signin_interactively()r   r  )rY  r   rs  rv  rw  r  r  )r   r  rU  r  r   r   r   r   r:  r;  r  r   r  r?  r   r  rw   pymsalruntimer  r   Status_AccountUnusableStatus_InteractionRequiredCONSOLE_WINDOW_HANDLE)r   r&  r  r  rv  r  r  r  rs  r   rw  r   r  rU  r  r   r   r  r  is_wrong_accountwrong_account_error_messager  recoverable_errorss                          r   r  =PublicClientApplication._acquire_token_interactive_via_broker  s    	]\'LL 234#**NN##T^^%:%:<	 NN11''50 "7; 	 &$44((*(=H8}!GH2NNQK 23	
 " +  x 7#OV6LL<='>>6"44' H  $ (* Ez E(,,%r#++.3/C+DE	 F P (89'7x !/-H> 
 F|u,,,9%.#::#>>0 &" $w(':x||(@*-?@@#OCD(+$~~v(,F,FFD) 1!0#  	r   c                     [         R                  R                  5       nU R                  R                  " SU R                  U=(       d    / 5      [         R                  R                  U0S.UD6nX4U R                  '   U$ )a  Initiate a Device Flow instance,
which will be used in :func:`~acquire_token_by_device_flow`.

:param list[str] scopes:
    Scopes requested to access a protected API (a resource).
:return: A dict representing a newly created Device Flow object.

    - A successful response would contain "user_code" key, among others
    - an error response would contain some other readable key/value pairs.
)rt  r   r   )r0  r1  r  r  initiate_device_flowr*  r_  DEVICE_FLOW_CORRELATION_ID)r   r&  r   r.  ry  s        r   r  ,PublicClientApplication.initiate_device_flow  sr     ??A{{// &&v|4^^55~F  1?T,,-r   c                    U R                  U R                  UR                  U R                  5      S9n[	        U R
                  R                  " U4[        UR                  S0 5      US   [        U R                  U5      S9UR                  5       S.UD65      nSU;   a  U R                  XPR                  '   UR                  U5        U$ )a  Obtain token by a device flow object, with customizable polling effect.

:param dict flow:
    A dict previously generated by :func:`~initiate_device_flow`.
    By default, this method's polling effect  will block current thread.
    You can abort the polling loop at any time,
    by changing the value of the flow's "expires_at" key to 0.
:param claims_challenge:
    The claims_challenge parameter requests specific claims requested by the resource provider
    in the form of a claims_challenge directive in the www-authenticate header to be
    returned from the UserInfo Endpoint and/or in the ID Token and/or Access Token.
    It is a string of a JSON object which contains lists of claims being requested from these locations.

:return: A dict representing the json response from Microsoft Entra:

    - A successful response would contain "access_token" key,
    - an error response would contain "error" and usually "error_description".
rZ  r  device_code)r  rv  )r  r   r*   )r4  r  rw   r  r~   r  obtain_token_by_device_flowrv   r   r6   r   r  r  r  r  )r   ry  r3   r   r  r  s         r   acquire_token_by_device_flow4PublicClientApplication.acquire_token_by_device_flow	  s    & !990088D$C$CD : F T[[DD

62&-( @--/?A &668   X%+/+A+AH''(**84r   r  r  )NNNNNNNNNNNr|  )r   r   r   r   r  objectr  r  r  r  r  r  r   r   r   s   @r   r   r   }  s|    !2"H ,0V9 "&!	V9 V9v !$(!%#'xF Xt&% %r   r   c                   >    \ rS rSrSrS	S jr S	S jrS rS	S jrSr	g)
r  i)	  zjSame as :func:`ClientApplication.__init__`,
except that ``allow_broker`` parameter shall remain ``None``.
Nc                     UR                  S5      (       a  [        S5      e[        U R                  " US4SU0UD65      $ )a  Acquires token for the current confidential client, not for an end user.

Since MSAL Python 1.23, it will automatically look for token from cache,
and only send request to Identity Provider when cache misses.

:param list[str] scopes: (Required)
    Scopes requested to access a protected API (a resource).
:param claims_challenge:
    The claims_challenge parameter requests specific claims requested by the resource provider
    in the form of a claims_challenge directive in the www-authenticate header to be
    returned from the UserInfo Endpoint and/or in the ID Token and/or Access Token.
    It is a string of a JSON object which contains lists of claims being requested from these locations.

:return: A dict representing the json response from Microsoft Entra:

    - A successful response would contain "access_token" key,
    - an error response would contain "error" and usually "error_description".
r  zCHistorically, this method does not support force_refresh behavior. Nr3   )rw   r$   r~   r  )r   r&  r3   r   s       r   acquire_token_for_client6ConfidentialClientApplication.acquire_token_for_client.	  sY    & ::o&&U  >>DG+;G?EG H 	Hr   c                    U R                   R                  R                  5       S;   a  [        R                  " S[
        5        U R                  UR                  S0 5      5        U R                  U R                  US9nU R                  =(       d    U R                  nUR                  " SUUR                  5       [        UR                  S0 5      [!        U R"                  U5      S9S.UD6nUR%                  U5        U$ )N)commonorganizationsz|Using /common or /organizations authority in acquire_token_for_client() is unreliable. Please use a specific tenant instead.r  rL  r  r  r   )r   r;  r  r   r   r  r  rw   r4  r  r  r  obtain_token_for_clientr  rv   r   r6   r   r  )r   r&  r/  r3   r   r  r  r  s           r   r  7ConfidentialClientApplication._acquire_token_for_clientH	  s     >>  &&(,GGMM89KM 	**6::fb+AB 99,,^ : M&&5$++11 %668

62&?--/?AB  	**84r   c           
      b   U R                   R                  /U R                  U R                   R                  5      -    Hn  n[        U R                  R                  [        R                  R                  U R                  USS.S95       H  nU R                  R                  U5        M      Mp     g)zoRemove all tokens that were previously acquired via
:func:`~acquire_token_for_client()` for the current client.N)r   rT  rg   r  )r   r:  r  r   r   r  r   r  r  r   r  )r   envr  s      r   remove_tokens_for_client6ConfidentialClientApplication.remove_tokens_for_clientc	  s     NN++,t/J/J''0) )C4++22))66!^^"#'? 3     **2.)r   c                    U R                  U R                  5      n[        U R                  R                  " UU R                  R
                  4U R                  U5      [        UR                  S0 5      S[        U R                  U5      S9UR                  5       S.UD65      nSU;   a  U R                  X`R                  '   UR                  U5        U$ )a  Acquires token using on-behalf-of (OBO) flow.

The current app is a middle-tier service which was called with a token
representing an end user.
The current app can use such token (a.k.a. a user assertion) to request
another token to access downstream web API, on behalf of that user.
See `detail docs here <https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow>`_ .

The current middle-tier app has no user interaction to obtain consent.
See how to gain consent upfront for your middle-tier app from this article.
https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application

:param str user_assertion: The incoming token already received by this app
:param list[str] scopes: Scopes required by downstream API (a resource).
:param claims_challenge:
    The claims_challenge parameter requests specific claims requested by the resource provider
    in the form of a claims_challenge directive in the www-authenticate header to be
    returned from the UserInfo Endpoint and/or in the ID Token and/or Access Token.
    It is a string of a JSON object which contains lists of claims being requested from these locations.

:return: A dict representing the json response from Microsoft Entra:

    - A successful response would contain "access_token" key,
    - an error response would contain "error" and usually "error_description".
r  on_behalf_of)requested_token_userv  )rt  r  r   r*   )r4  r~  r~   r  rw  GRANT_TYPE_JWTr*  rv   r   r6   r   r  r  r  r  )r   user_assertionr&  r3   r   r  r  s          r   acquire_token_on_behalf_of8ConfidentialClientApplication.acquire_token_on_behalf_ofq	  s    4 !99..0 T[[BBKK&& &&v. 

62&$2?--/?AB
 &668  ! " X%+/+A+AH''(**84r   r   r  )
r   r   r   r   r}  r  r  r  r  r   r   r   r   r  r  )	  s!    H< 	6/1r   r  )=r   r-   rz   loggingr   r   	threadingr   typingr   urllib.parser   r   	oauth2clir   r   oauth2cli.oidcr	   r   r
   r   mexr   rn  wstrust_requestro  wstrust_responser   r   r   r   msal.telemetryr0  regionr   throttled_http_clientr   r  r   skur   r   	getLoggerr   r   r  r   r(   r6   r<   r\   rc   ri   r~   r   r   r   r  r   r   r  r   r   r   <module>r     s        
    ! 	 2 ' , 1 =  F F  " 6 2 ! 
		8	$) !
) #@(
$)X; ;<Ye eP5i/ iXy$5 yr   