🔍 Code Extractor

class AuthenticationContext

Maturity: 48

AuthenticationContext manages authentication for SharePoint Online and OneDrive For Business, supporting multiple authentication methods including certificate-based, interactive, device flow, user credentials, and client credentials.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/auth/authentication_context.py
Lines:
31 - 237
Complexity:
complex

Purpose

This class provides a unified authentication context for SharePoint Online/OneDrive For Business operations. It supports various OAuth 2.0 authentication flows (certificate, interactive browser, device flow) and legacy authentication methods (SAML, NTLM, ACS). The class follows a builder pattern where authentication methods return self for chaining. It caches tokens and applies authentication to HTTP requests through the authenticate_request method.

Source Code

class AuthenticationContext(object):
    """Authentication context for SharePoint Online/OneDrive For Business"""

    def __init__(self, url):
        """
        :param str url: SharePoint absolute web or site Url
        """
        self.url = url.rstrip("/")
        self._authenticate = None
        self._cached_token = None

    def with_client_certificate(
        self,
        tenant,
        client_id,
        thumbprint,
        cert_path=None,
        private_key=None,
        scopes=None,
    ):
        """Initializes a client to acquire a token via certificate credentials

        :param str tenant: Tenant name, for example: contoso.onmicrosoft.com
        :param str client_id: The OAuth client id of the calling application.
        :param str thumbprint: Hex encoded thumbprint of the certificate.
        :param str or None cert_path: Path to A PEM encoded certificate private key.
        :param str or None private_key: A PEM encoded certificate private key.
        :param list[str] or None scopes:  Scopes requested to access a protected API (a resource)
        """
        if scopes is None:
            resource = get_absolute_url(self.url)
            scopes = ["{url}/.default".format(url=resource)]
        if cert_path is None and private_key is None:
            raise ValueError(
                "Private key is missing. Use either 'cert_path' or 'private_key' to pass the value"
            )
        elif cert_path is not None:
            with open(cert_path, "r", encoding="utf8") as f:
                private_key = f.read()

        def _acquire_token():
            authority_url = "https://login.microsoftonline.com/{0}".format(tenant)
            credentials = {"thumbprint": thumbprint, "private_key": private_key}
            import msal

            app = msal.ConfidentialClientApplication(
                client_id,
                authority=authority_url,
                client_credential=credentials,
            )
            result = app.acquire_token_for_client(scopes)
            return TokenResponse.from_json(result)

        self.with_access_token(_acquire_token)
        return self

    def with_interactive(self, tenant, client_id, scopes=None):
        """
        Initializes a client to acquire a 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``.

        :param str tenant: Tenant name, for example: contoso.onmicrosoft.com
        :param str client_id: The OAuth client id of the calling application.
        :param list[str] or None scopes:  Scopes requested to access a protected API (a resource)
        """
        if scopes is None:
            resource = get_absolute_url(self.url)
            scopes = ["{url}/.default".format(url=resource)]

        def _acquire_token():
            import msal

            app = msal.PublicClientApplication(
                client_id,
                authority="https://login.microsoftonline.com/{0}".format(tenant),
                client_credential=None,
            )
            result = app.acquire_token_interactive(scopes=scopes)
            return TokenResponse.from_json(result)

        self.with_access_token(_acquire_token)
        return self

    def with_device_flow(self, tenant, client_id, scopes=None):
        """
        Obtain token by a device flow object, with customizable polling effect.

        :param str tenant: Tenant name, for example: contoso.onmicrosoft.com
        :param str client_id: The OAuth client id of the calling application.
        :param list[str] or None scopes:  Scopes requested to access a protected API (a resource)
        """
        if scopes is None:
            resource = get_absolute_url(self.url)
            scopes = ["{url}/.default".format(url=resource)]

        def _acquire_token():
            import msal

            app = msal.PublicClientApplication(
                client_id,
                authority="https://login.microsoftonline.com/{0}".format(tenant),
                client_credential=None,
            )

            flow = app.initiate_device_flow(scopes=scopes)
            if "user_code" not in flow:
                raise ValueError(
                    "Failed to create device flow: %s" % json.dumps(flow, indent=4)
                )

            print(flow["message"])
            sys.stdout.flush()

            result = app.acquire_token_by_device_flow(flow)
            return TokenResponse.from_json(result)

        self.with_access_token(_acquire_token)
        return self

    def with_access_token(self, token_func):
        # type: (Callable[[], JSONToken]) -> None
        """
        Initializes a client to acquire a token from a callback

        :param () -> dict token_func: A token callback
        """

        def _authenticate(request):
            if self._cached_token is None:
                self._cached_token = token_func()
            request.set_header(
                "Authorization", _get_authorization_header(self._cached_token)
            )

        self._authenticate = _authenticate

    def with_credentials(self, credentials, **kwargs):
        """
        Initializes a client to acquire a token via user or client credentials

        :param UserCredential or ClientCredential credentials:
        """
        if isinstance(credentials, ClientCredential):
            provider = ACSTokenProvider(
                self.url, credentials.clientId, credentials.clientSecret
            )
        elif isinstance(credentials, UserCredential):
            allow_ntlm = kwargs.get("allow_ntlm", False)
            if allow_ntlm:
                from office365.runtime.auth.providers.ntlm_provider import NtlmProvider

                provider = NtlmProvider(credentials.userName, credentials.password)
            else:
                browser_mode = kwargs.get("browser_mode", False)
                provider = SamlTokenProvider(
                    self.url, credentials.userName, credentials.password, browser_mode
                )
        else:
            raise ValueError("Unknown credential type")

        def _authenticate(request):
            provider.authenticate_request(request)

        self._authenticate = _authenticate

    def acquire_token_for_user(self, username, password, browser_mode=False):
        """
        Initializes a client to acquire a token via user credentials
        Status: deprecated!

        :param str password: The user password
        :param str username: Typically a UPN in the form of an email address
        :param bool browser_mode:
        """
        provider = SamlTokenProvider(self.url, username, password, browser_mode)

        def _authenticate(request):
            provider.authenticate_request(request)

        self._authenticate = _authenticate
        return self

    def acquire_token_for_app(self, client_id, client_secret):
        """
        Initializes a client to acquire a token via client credentials (SharePoint App-Only)

        Status: deprecated!

        :param str client_id: The OAuth client id of the calling application.
        :param str client_secret: Secret string that the application uses to prove its identity when requesting a token
        """
        provider = ACSTokenProvider(self.url, client_id, client_secret)

        def _authenticate(request):
            provider.authenticate_request(request)

        self._authenticate = _authenticate
        return self

    def authenticate_request(self, request):
        # type: (RequestOptions) -> None
        """Authenticate request"""
        if self._authenticate is None:
            raise ValueError("Authentication credentials are missing or invalid")
        self._authenticate(request)

Parameters

Name Type Default Kind
bases object -

Parameter Details

url: SharePoint absolute web or site URL (e.g., 'https://contoso.sharepoint.com/sites/mysite'). Trailing slashes are automatically removed. This URL is used to determine the resource scope for authentication.

Return Value

Instantiation returns an AuthenticationContext object. Most configuration methods (with_client_certificate, with_interactive, with_device_flow, with_credentials, acquire_token_for_user, acquire_token_for_app) return self to enable method chaining. The authenticate_request method returns None but modifies the request object in-place by adding authentication headers.

Class Interface

Methods

__init__(self, url: str)

Purpose: Initialize the authentication context with a SharePoint URL

Parameters:

  • url: SharePoint absolute web or site URL, trailing slashes are removed automatically

Returns: None (constructor)

with_client_certificate(self, tenant: str, client_id: str, thumbprint: str, cert_path: str = None, private_key: str = None, scopes: list = None) -> AuthenticationContext

Purpose: Configure certificate-based authentication for acquiring tokens via Azure AD

Parameters:

  • tenant: Tenant name (e.g., 'contoso.onmicrosoft.com')
  • client_id: OAuth client ID of the calling application from Azure AD
  • thumbprint: Hex encoded thumbprint of the certificate
  • cert_path: Path to PEM encoded certificate private key file (mutually exclusive with private_key)
  • private_key: PEM encoded certificate private key as string (mutually exclusive with cert_path)
  • scopes: List of scopes for API access, defaults to ['{url}/.default']

Returns: Self for method chaining

with_interactive(self, tenant: str, client_id: str, scopes: list = None) -> AuthenticationContext

Purpose: Configure interactive browser-based authentication via local browser

Parameters:

  • tenant: Tenant name (e.g., 'contoso.onmicrosoft.com')
  • client_id: OAuth client ID of the calling application
  • scopes: List of scopes for API access, defaults to ['{url}/.default']

Returns: Self for method chaining

with_device_flow(self, tenant: str, client_id: str, scopes: list = None) -> AuthenticationContext

Purpose: Configure device flow authentication where user enters code on another device

Parameters:

  • tenant: Tenant name (e.g., 'contoso.onmicrosoft.com')
  • client_id: OAuth client ID of the calling application
  • scopes: List of scopes for API access, defaults to ['{url}/.default']

Returns: Self for method chaining

with_access_token(self, token_func: Callable[[], dict]) -> None

Purpose: Configure authentication using a custom token callback function

Parameters:

  • token_func: Callback function that returns a token dictionary when called

Returns: None

with_credentials(self, credentials: Union[UserCredential, ClientCredential], **kwargs) -> None

Purpose: Configure authentication using user credentials or client credentials

Parameters:

  • credentials: UserCredential or ClientCredential object containing authentication details
  • allow_ntlm: Keyword argument: if True and using UserCredential, use NTLM authentication instead of SAML
  • browser_mode: Keyword argument: if True and using UserCredential with SAML, use browser-based flow

Returns: None

acquire_token_for_user(self, username: str, password: str, browser_mode: bool = False) -> AuthenticationContext

Purpose: Configure user credential authentication (DEPRECATED - use with_credentials instead)

Parameters:

  • username: User principal name, typically in email format
  • password: User password
  • browser_mode: If True, use browser-based SAML flow

Returns: Self for method chaining

acquire_token_for_app(self, client_id: str, client_secret: str) -> AuthenticationContext

Purpose: Configure SharePoint App-Only authentication (DEPRECATED - use with_credentials instead)

Parameters:

  • client_id: OAuth client ID of the SharePoint app
  • client_secret: Client secret for the SharePoint app

Returns: Self for method chaining

authenticate_request(self, request: RequestOptions) -> None

Purpose: Apply authentication to an HTTP request by adding authorization headers

Parameters:

  • request: RequestOptions object to be authenticated

Returns: None (modifies request in-place)

Attributes

Name Type Description Scope
url str SharePoint site or web URL with trailing slash removed instance
_authenticate Callable[[RequestOptions], None] or None Internal callback function that applies authentication to requests, set by configuration methods instance
_cached_token TokenResponse or None Cached authentication token to avoid repeated token acquisition calls instance

Dependencies

  • msal
  • office365
  • typing
  • typing_extensions

Required Imports

from office365.runtime.auth.authentication_context import AuthenticationContext

Conditional/Optional Imports

These imports are only needed under specific conditions:

import msal

Condition: Required when using with_client_certificate, with_interactive, or with_device_flow methods

Required (conditional)
from office365.runtime.auth.providers.ntlm_provider import NtlmProvider

Condition: Only when using with_credentials with UserCredential and allow_ntlm=True

Optional

Usage Example

# Certificate-based authentication
from office365.runtime.auth.authentication_context import AuthenticationContext

ctx = AuthenticationContext('https://contoso.sharepoint.com/sites/mysite')
ctx.with_client_certificate(
    tenant='contoso.onmicrosoft.com',
    client_id='your-client-id',
    thumbprint='ABC123...',
    cert_path='/path/to/cert.pem'
)

# Interactive browser authentication
ctx = AuthenticationContext('https://contoso.sharepoint.com')
ctx.with_interactive(
    tenant='contoso.onmicrosoft.com',
    client_id='your-client-id'
)

# Device flow authentication
ctx = AuthenticationContext('https://contoso.sharepoint.com')
ctx.with_device_flow(
    tenant='contoso.onmicrosoft.com',
    client_id='your-client-id'
)

# User credentials with SAML
from office365.runtime.auth.user_credential import UserCredential
ctx = AuthenticationContext('https://contoso.sharepoint.com')
ctx.with_credentials(UserCredential('user@contoso.com', 'password'))

# Apply authentication to a request
from office365.runtime.http.request_options import RequestOptions
request = RequestOptions('https://contoso.sharepoint.com/_api/web')
ctx.authenticate_request(request)

Best Practices

  • Always call one of the authentication configuration methods (with_client_certificate, with_interactive, etc.) before calling authenticate_request
  • The class caches tokens internally (_cached_token) to avoid repeated authentication calls
  • Use method chaining for cleaner code: ctx.with_client_certificate(...).authenticate_request(request)
  • For production use, prefer modern OAuth flows (with_client_certificate, with_interactive) over deprecated methods (acquire_token_for_user, acquire_token_for_app)
  • When using certificate authentication, ensure the certificate file is readable and properly formatted as PEM
  • For interactive authentication, ensure the redirect URI 'http://localhost' is configured in Azure Portal
  • Device flow authentication will print instructions to stdout - ensure your application can display this to users
  • The url parameter should be the root SharePoint site or web URL, not an API endpoint
  • Token caching is per-instance, so create one AuthenticationContext per session and reuse it
  • Handle authentication errors by catching exceptions from authenticate_request - it will raise ValueError if no authentication method was configured

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class Authentication 69.0% similar

    A class representing authentication methods in SharePoint, inheriting from Entity to expose relationships for authentication.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/oauth/authentication.py
  • class ClientContext 63.4% similar

    SharePoint client context (SharePoint v1 API)

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/client_context.py
  • class NativeClient 63.3% similar

    A SharePoint OAuth client class that provides endpoints for native client authentication relative to the current request context.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/oauth/native_client.py
  • class RequestUserContext 62.7% similar

    Represents the user context for the current SharePoint request, providing access to user information and context details typically available at the /_api/me endpoint.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/request_user_context.py
  • class SharePointHomeServiceContextBuilder 61.0% similar

    A builder class for creating SharePoint Home Service contexts, inheriting from Entity and providing methods to construct and retrieve service context objects.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/portal/home/service_context_builder.py
← Back to Browse