🔍 Code Extractor

class ACSTokenProvider

Maturity: 22

A class named ACSTokenProvider

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/auth/providers/acs_token_provider.py
Lines:
12 - 113
Complexity:
moderate

Purpose

No detailed description available

Source Code

class ACSTokenProvider(AuthenticationProvider, office365.logger.LoggerContext):
    def __init__(self, url, client_id, client_secret):
        """
        Provider to acquire the access token from a Microsoft Azure Access Control Service (ACS)

        :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
        :param str url: SharePoint web or site url
        """
        self.url = url
        self.redirect_url = None
        self.error = None
        self.SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"
        self._client_id = client_id
        self._client_secret = client_secret
        self._cached_token = None

    def authenticate_request(self, request):
        # type: (RequestOptions) -> None
        self.ensure_app_only_access_token()
        request.set_header("Authorization", self._get_authorization_header())

    def ensure_app_only_access_token(self):
        if self._cached_token is None:
            self._cached_token = self.get_app_only_access_token()
        return self._cached_token and self._cached_token.is_valid

    def get_app_only_access_token(self):
        """Retrieves an app-only access token from ACS"""
        try:
            realm = self._get_realm_from_target_url()
            url_info = urlparse(self.url)
            return self._get_app_only_access_token(url_info.hostname, realm)
        except requests.exceptions.RequestException as e:
            self.error = (
                e.response.text
                if e.response is not None
                else "Acquire app-only access token failed."
            )
            raise ValueError(self.error)

    def _get_app_only_access_token(self, target_host, target_realm):
        """
        Retrieves an app-only access token from ACS to call the specified principal
        at the specified targetHost. The targetHost must be registered for target principal.

        :param str target_host: Url authority of the target principal
        :param str target_realm: Realm to use for the access token's nameid and audience
        """
        resource = self.get_formatted_principal(
            self.SharePointPrincipal, target_host, target_realm
        )
        principal_id = self.get_formatted_principal(self._client_id, None, target_realm)
        sts_url = self.get_security_token_service_url(target_realm)
        oauth2_request = {
            "grant_type": "client_credentials",
            "client_id": principal_id,
            "client_secret": self._client_secret,
            "scope": resource,
            "resource": resource,
        }
        response = requests.post(
            url=sts_url,
            headers={"Content-Type": "application/x-www-form-urlencoded"},
            data=oauth2_request,
        )
        response.raise_for_status()
        return TokenResponse.from_json(response.json())

    def _get_realm_from_target_url(self):
        """Get the realm for the URL"""
        response = requests.head(url=self.url, headers={"Authorization": "Bearer"})
        return self.process_realm_response(response)

    @staticmethod
    def process_realm_response(response):
        # type: (requests.Response) -> Optional[str]
        header_key = "WWW-Authenticate"
        if header_key in response.headers:
            auth_values = response.headers[header_key].split(",")
            bearer = auth_values[0].split("=")
            return bearer[1].replace('"', "")
        return None

    @staticmethod
    def get_formatted_principal(principal_name, host_name, realm):
        # type: (str, Optional[str], str) -> str
        if host_name:
            return "{0}/{1}@{2}".format(principal_name, host_name, realm)
        return "{0}@{1}".format(principal_name, realm)

    @staticmethod
    def get_security_token_service_url(realm):
        return "https://accounts.accesscontrol.windows.net/{0}/tokens/OAuth/2".format(
            realm
        )

    def _get_authorization_header(self):
        return "Bearer {0}".format(self._cached_token.accessToken)

    def get_last_error(self):
        return self.error

Parameters

Name Type Default Kind
bases AuthenticationProvider, office365.logger.LoggerContext -

Parameter Details

bases: Parameter of type AuthenticationProvider, office365.logger.LoggerContext

Return Value

Returns unspecified type

Class Interface

Methods

__init__(self, url, client_id, client_secret)

Purpose: Provider to acquire the access token from a Microsoft Azure Access Control Service (ACS) :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 :param str url: SharePoint web or site url

Parameters:

  • url: Parameter
  • client_id: Parameter
  • client_secret: Parameter

Returns: None

authenticate_request(self, request)

Purpose: Performs authenticate request

Parameters:

  • request: Parameter

Returns: None

ensure_app_only_access_token(self)

Purpose: Performs ensure app only access token

Returns: None

get_app_only_access_token(self)

Purpose: Retrieves an app-only access token from ACS

Returns: None

_get_app_only_access_token(self, target_host, target_realm)

Purpose: Retrieves an app-only access token from ACS to call the specified principal at the specified targetHost. The targetHost must be registered for target principal. :param str target_host: Url authority of the target principal :param str target_realm: Realm to use for the access token's nameid and audience

Parameters:

  • target_host: Parameter
  • target_realm: Parameter

Returns: None

_get_realm_from_target_url(self)

Purpose: Get the realm for the URL

Returns: None

process_realm_response(response) static

Purpose: Performs process realm response

Parameters:

  • response: Parameter

Returns: None

get_formatted_principal(principal_name, host_name, realm) static

Purpose: Retrieves formatted principal

Parameters:

  • principal_name: Parameter
  • host_name: Parameter
  • realm: Parameter

Returns: None

get_security_token_service_url(realm) static

Purpose: Retrieves security token service url

Parameters:

  • realm: Parameter

Returns: None

_get_authorization_header(self)

Purpose: Internal method: get authorization header

Returns: None

get_last_error(self)

Purpose: Retrieves last error

Returns: None

Required Imports

from typing import Optional
import requests
import office365.logger
from office365.runtime.auth.authentication_provider import AuthenticationProvider
from office365.runtime.auth.token_response import TokenResponse

Usage Example

# Example usage:
# result = ACSTokenProvider(bases)

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class AuthenticationProvider 51.3% similar

    Abstract base class that defines the interface for authentication providers in the Office365 runtime library.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/auth/authentication_provider.py
  • class SamlTokenProvider 48.0% similar

    Provides SAML-based claims authentication for Office 365 SharePoint Online, handling security token acquisition and cookie-based authentication.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/auth/providers/saml_token_provider.py
  • class SocialIdentityProvider 46.3% similar

    A class representing social identity providers for Azure Active Directory (Azure AD) and Azure AD B2C tenants, providing access to OAuth client credentials and provider type information.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/identities/providers/social_identity.py
  • class STSProfile 45.8% similar

    STSProfile is a configuration class that manages Security Token Service (STS) profile settings for Microsoft Online authentication, including URLs, timestamps, and service endpoints.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/auth/sts_profile.py
  • class IdentityProvider 45.6% similar

    Represents an Azure Active Directory (Azure AD) identity provider entity with client credentials for OAuth authentication.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/identities/provider.py
← Back to Browse