🔍 Code Extractor

class Application

Maturity: 55

Represents an Azure Active Directory (Azure AD) application registration, providing methods to manage application credentials, certificates, passwords, and publisher verification.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/applications/application.py
Lines:
24 - 328
Complexity:
complex

Purpose

This class encapsulates an Azure AD application object and provides comprehensive functionality for managing application registrations. It handles certificate and password credential management, verified publisher settings, key rotation, and access to related directory objects like owners and extension properties. The class is part of the Microsoft Graph API integration for managing Azure AD applications programmatically.

Source Code

class Application(DirectoryObject):
    """
    Represents an application. Any application that outsources authentication to Azure Active Directory (Azure AD)
    must be registered in a directory. Application registration involves telling Azure AD about your application,
    including the URL where it's located, the URL to send replies after authentication,
    the URI to identify your application, and more. For more information, see Basics of Registering
    an Application in Azure AD
    """

    def __repr__(self):
        return self.id or self.app_id or self.entity_type_name

    def __str__(self):
        if self.display_name:
            return "Name: {0}".format(self.display_name)
        elif self.app_id:
            return "App Id: {0}".format(self.app_id)
        else:
            return self.entity_type_name

    def add_certificate(
        self, cert_data, display_name, start_datetime=None, end_datetime=None
    ):
        """Adds a certificate to an application.

        :param str display_name: Friendly name for the key.
        :param bytes cert_data: The certificate's raw data or path.
        :param datetime.datetime start_datetime: The date and time at which the credential becomes valid. Default: now
        :param datetime.datetime end_datetime: The date and time at which the credential expires. Default: now + 180days
        """
        if start_datetime is None:
            start_datetime = datetime.datetime.utcnow()
        if end_datetime is None:
            end_datetime = start_datetime + datetime.timedelta(days=180)

        params = KeyCredential(
            usage="Verify",
            key_type="AsymmetricX509Cert",
            start_datetime=start_datetime.isoformat(),
            end_datetime=end_datetime.isoformat(),
            key=base64.b64encode(cert_data).decode("utf-8"),
            display_name="CN={0}".format(display_name),
        )
        self.key_credentials.add(params)
        self.update()
        return self

    def remove_certificate(self, thumbprint):
        """
        Remove a certificate from an application.
        :param str thumbprint: The unique identifier for the password.
        """
        raise NotImplementedError("remove_certificate")

    def add_password(self, display_name):
        """Adds a strong password to an application.

        :param str display_name: App display name
        """
        params = PasswordCredential(display_name=display_name)
        result = ClientResult(self.context, params)
        qry = ServiceOperationQuery(self, "addPassword", None, params, None, result)
        self.context.add_query(qry)
        return result

    def remove_password(self, key_id):
        """Remove a password from an application.

        :param str key_id: The unique identifier for the password.
        """
        qry = ServiceOperationQuery(self, "removePassword", None, {"keyId": key_id})
        self.context.add_query(qry)
        return self

    def delete_object(self, permanent_delete=False):
        """
        :param permanent_delete: Permanently deletes the application from directory
        :type permanent_delete: bool

        """
        super(Application, self).delete_object()
        if permanent_delete:
            deleted_item = self.context.directory.deleted_applications[self.id]
            deleted_item.delete_object()
        return self

    def set_verified_publisher(self, verified_publisher_id):
        """Set the verifiedPublisher on an application.
        For more information, including prerequisites to setting a verified publisher, see Publisher verification.

        :param str verified_publisher_id: The Microsoft Partner Network ID (MPNID) of the verified publisher
        to be set on the application, from the publisher's Partner Center account.
        """
        qry = ServiceOperationQuery(
            self,
            "setVerifiedPublisher",
            None,
            {"verifiedPublisherId": verified_publisher_id},
        )
        self.context.add_query(qry)
        return self

    def unset_verified_publisher(self):
        """Unset the verifiedPublisher previously set on an application, removing all verified publisher properties.
        For more information, see Publisher verification.
        """
        qry = ServiceOperationQuery(self, "unsetVerifiedPublisher")
        self.context.add_query(qry)
        return self

    def add_key(self, key_credential, password_credential, proof):
        """
        Add a key credential to an application. This method, along with removeKey can be used by an application
        to automate rolling its expiring keys.

        :param KeyCredential key_credential: The new application key credential to add.
            The type, usage and key are required properties for this usage. Supported key types are:
                AsymmetricX509Cert: The usage must be Verify.
                X509CertAndPassword: The usage must be Sign
        :param PasswordCredential password_credential: Only secretText is required to be set which should contain
             the password for the key. This property is required only for keys of type X509CertAndPassword.
             Set it to null otherwise.
        :param str proof: A self-signed JWT token used as a proof of possession of the existing keys
        """
        payload = {
            "keyCredential": key_credential,
            "passwordCredential": password_credential,
            "proof": proof,
        }
        return_type = ClientResult(self.context, KeyCredential())
        qry = ServiceOperationQuery(self, "addKey", None, payload, None, return_type)
        self.context.add_query(qry)
        return return_type

    def remove_key(self, key_id, proof):
        """
        Remove a key credential from an application.
        This method along with addKey can be used by an application to automate rolling its expiring keys.

        :param str key_id: The unique identifier for the password.
        :param str proof: A self-signed JWT token used as a proof of possession of the existing keys.
             This JWT token must be signed using the private key of one of the application's existing
             valid certificates. The token should contain the following claims:
                 aud - Audience needs to be 00000002-0000-0000-c000-000000000000.
                 iss - Issuer needs to be the id of the application that is making the call.
                 nbf - Not before time.
                 exp - Expiration time should be "nbf" + 10 mins.
        """
        qry = ServiceOperationQuery(
            self, "removeKey", None, {"keyId": key_id, "proof": proof}
        )
        self.context.add_query(qry)
        return self

    @property
    def app_id(self):
        # type: () -> Optional[str]
        """The unique identifier for the application that is assigned to an application by Azure AD. Not nullable."""
        return self.properties.get("appId", None)

    @property
    def application_template_id(self):
        # type: () -> Optional[str]
        """Unique identifier of the applicationTemplate"""
        return self.properties.get("applicationTemplateId", None)

    @property
    def app_roles(self):
        # type: () -> ClientValueCollection[AppRole]
        """
        The collection of roles defined for the application. With app role assignments, these roles can be assigned to
        users, groups, or service principals associated with other applications
        """
        return self.properties.get("appRoles", ClientValueCollection(AppRole))

    @property
    def api(self):
        """Specifies settings for an application that implements a web API."""
        return self.properties.get("api", ApiApplication())

    @property
    def certification(self):
        """Specifies the certification status of the application."""
        return self.properties.get("certification", Certification())

    @property
    def created_datetime(self):
        """The date and time the application was registered."""
        return self.properties.get("createdDateTime", datetime.datetime.min)

    @property
    def default_redirect_uri(self):
        # type: () -> Optional[str]
        """ """
        return self.properties.get("defaultRedirectUri", None)

    @property
    def spa(self):
        """
        Specifies settings for a single-page application, including sign out URLs and redirect URIs for
        authorization codes and access tokens."""
        return self.properties.get("spa", SpaApplication())

    @property
    def key_credentials(self):
        """The collection of key credentials associated with the application. Not nullable."""
        self._ser_property_names.append("keyCredentials")
        return self.properties.setdefault(
            "keyCredentials", ClientValueCollection(KeyCredential)
        )

    @property
    def display_name(self):
        # type: () -> Optional[str]
        """
        The display name for the application.
        Supports $filter (eq, ne, NOT, ge, le, in, startsWith), $search, and $orderBy.
        """
        return self.properties.get("displayName", None)

    @property
    def identifier_uris(self):
        """
        The URIs that identify the application within its Azure AD tenant, or within a verified custom domain
        if the application is multi-tenant. For more information see Application Objects and Service Principal Objects.
        The any operator is required for filter expressions on multi-valued properties.
        """
        return self.properties.get("identifierUris", StringCollection())

    @property
    def public_client(self):
        """
        Specifies settings for installed clients such as desktop or mobile devices.
        """
        return self.properties.get("publicClient", PublicClientApplication())

    @property
    def signin_audience(self):
        # type: () -> Optional[str]
        """
        Specifies the Microsoft accounts that are supported for the current application.
        Supported values are: AzureADMyOrg, AzureADMultipleOrgs, AzureADandPersonalMicrosoftAccount,
        PersonalMicrosoftAccount
        """
        return self.properties.get("signInAudience", None)

    @property
    def created_on_behalf_of(self):
        """"""
        return self.properties.get(
            "createdOnBehalfOf",
            DirectoryObject(
                self.context, ResourcePath("createdOnBehalfOf", self.resource_path)
            ),
        )

    @property
    def owners(self):
        """Directory objects that are owners of the application."""
        return self.properties.get(
            "owners",
            DirectoryObjectCollection(
                self.context, ResourcePath("owners", self.resource_path)
            ),
        )

    @property
    def extension_properties(self):
        # type: () -> EntityCollection[ExtensionProperty]
        """List extension properties on an application object."""
        return self.properties.get(
            "extensionProperties",
            EntityCollection(
                self.context,
                ExtensionProperty,
                ResourcePath("extensionProperties", self.resource_path),
            ),
        )

    @property
    def token_issuance_policies(self):
        # type: () -> EntityCollection[TokenIssuancePolicy]
        """Get all tokenIssuancePolicies assigned to this object."""
        return self.properties.get(
            "tokenIssuancePolicies",
            EntityCollection(
                self.context,
                TokenIssuancePolicy,
                ResourcePath("tokenIssuancePolicies", self.resource_path),
            ),
        )

    def get_property(self, name, default_value=None):
        if default_value is None:
            property_mapping = {
                "appRoles": self.app_roles,
                "createdDateTime": self.created_datetime,
                "createdOnBehalfOf": self.created_on_behalf_of,
                "extensionProperties": self.extension_properties,
                "keyCredentials": self.key_credentials,
                "publicClient": self.public_client,
                "tokenIssuancePolicies": self.token_issuance_policies,
            }
            default_value = property_mapping.get(name, None)
        return super(Application, self).get_property(name, default_value)

Parameters

Name Type Default Kind
bases DirectoryObject -

Parameter Details

DirectoryObject: Inherits from DirectoryObject base class which provides common directory entity functionality including context, resource_path, and entity_type_name. The constructor parameters are inherited from DirectoryObject and typically include context (client context for API calls) and resource_path (the API endpoint path for this application).

Return Value

Instantiation returns an Application object representing an Azure AD application. Most methods return 'self' for method chaining, except: add_password() returns ClientResult containing PasswordCredential, add_key() returns ClientResult containing KeyCredential, and property accessors return their respective types (strings, collections, or complex objects).

Class Interface

Methods

__repr__(self) -> str

Purpose: Returns a string representation of the application using id, app_id, or entity_type_name

Returns: String identifier for the application object

__str__(self) -> str

Purpose: Returns a human-readable string representation with display name or app ID

Returns: Formatted string with application name or ID

add_certificate(self, cert_data: bytes, display_name: str, start_datetime: datetime.datetime = None, end_datetime: datetime.datetime = None) -> Application

Purpose: Adds a certificate credential to the application for authentication

Parameters:

  • cert_data: The certificate's raw binary data or path to certificate file
  • display_name: Friendly name for the certificate key
  • start_datetime: Optional datetime when credential becomes valid (defaults to now)
  • end_datetime: Optional datetime when credential expires (defaults to now + 180 days)

Returns: Self (Application instance) for method chaining

remove_certificate(self, thumbprint: str)

Purpose: Remove a certificate from the application (NOT IMPLEMENTED)

Parameters:

  • thumbprint: The unique identifier/thumbprint for the certificate

Returns: Raises NotImplementedError

add_password(self, display_name: str) -> ClientResult

Purpose: Adds a strong password credential to the application

Parameters:

  • display_name: Display name for the password credential

Returns: ClientResult containing PasswordCredential with the generated password (access via result.value after execute_query)

remove_password(self, key_id: str) -> Application

Purpose: Removes a password credential from the application

Parameters:

  • key_id: The unique identifier (GUID) for the password credential to remove

Returns: Self (Application instance) for method chaining

delete_object(self, permanent_delete: bool = False) -> Application

Purpose: Deletes the application from the directory, optionally permanently

Parameters:

  • permanent_delete: If True, permanently deletes the application; if False, soft deletes (can be restored)

Returns: Self (Application instance) for method chaining

set_verified_publisher(self, verified_publisher_id: str) -> Application

Purpose: Sets the verified publisher on the application using Microsoft Partner Network ID

Parameters:

  • verified_publisher_id: The Microsoft Partner Network ID (MPNID) from Partner Center account

Returns: Self (Application instance) for method chaining

unset_verified_publisher(self) -> Application

Purpose: Removes the verified publisher from the application

Returns: Self (Application instance) for method chaining

add_key(self, key_credential: KeyCredential, password_credential: PasswordCredential, proof: str) -> ClientResult

Purpose: Adds a key credential to the application with proof of possession for automated key rolling

Parameters:

  • key_credential: KeyCredential object with type, usage, and key properties (AsymmetricX509Cert or X509CertAndPassword)
  • password_credential: PasswordCredential with secretText for X509CertAndPassword type, null otherwise
  • proof: Self-signed JWT token proving possession of existing keys

Returns: ClientResult containing the added KeyCredential

remove_key(self, key_id: str, proof: str) -> Application

Purpose: Removes a key credential from the application with proof of possession

Parameters:

  • key_id: The unique identifier for the key credential to remove
  • proof: Self-signed JWT token proving possession of existing keys (aud: 00000002-0000-0000-c000-000000000000, iss: app id)

Returns: Self (Application instance) for method chaining

get_property(self, name: str, default_value=None)

Purpose: Gets a property value with custom mapping for complex properties

Parameters:

  • name: Property name to retrieve
  • default_value: Default value if property not found

Returns: Property value or default_value

@property app_id(self) -> Optional[str] property

Purpose: Gets the unique application ID assigned by Azure AD

Returns: Application ID (GUID) or None

@property application_template_id(self) -> Optional[str] property

Purpose: Gets the unique identifier of the application template

Returns: Application template ID or None

@property app_roles(self) -> ClientValueCollection[AppRole] property

Purpose: Gets the collection of app roles defined for the application

Returns: ClientValueCollection of AppRole objects that can be assigned to users, groups, or service principals

@property api(self) -> ApiApplication property

Purpose: Gets settings for an application that implements a web API

Returns: ApiApplication object with web API settings

@property certification(self) -> Certification property

Purpose: Gets the certification status of the application

Returns: Certification object with certification details

@property created_datetime(self) -> datetime.datetime property

Purpose: Gets the date and time when the application was registered

Returns: datetime object representing creation time, or datetime.min if not set

@property default_redirect_uri(self) -> Optional[str] property

Purpose: Gets the default redirect URI for the application

Returns: Default redirect URI string or None

@property spa(self) -> SpaApplication property

Purpose: Gets settings for single-page application including sign out URLs and redirect URIs

Returns: SpaApplication object with SPA-specific settings

@property key_credentials(self) -> ClientValueCollection[KeyCredential] property

Purpose: Gets the collection of key credentials (certificates) associated with the application

Returns: ClientValueCollection of KeyCredential objects

@property display_name(self) -> Optional[str] property

Purpose: Gets the display name for the application

Returns: Application display name string or None

@property identifier_uris(self) -> StringCollection property

Purpose: Gets the URIs that identify the application within its Azure AD tenant

Returns: StringCollection of identifier URIs

@property public_client(self) -> PublicClientApplication property

Purpose: Gets settings for installed clients such as desktop or mobile devices

Returns: PublicClientApplication object with public client settings

@property signin_audience(self) -> Optional[str] property

Purpose: Gets the Microsoft accounts supported for the application

Returns: String value: AzureADMyOrg, AzureADMultipleOrgs, AzureADandPersonalMicrosoftAccount, or PersonalMicrosoftAccount

@property created_on_behalf_of(self) -> DirectoryObject property

Purpose: Gets the directory object on whose behalf the application was created

Returns: DirectoryObject representing the creator

@property owners(self) -> DirectoryObjectCollection property

Purpose: Gets the directory objects that are owners of the application

Returns: DirectoryObjectCollection of owner objects

@property extension_properties(self) -> EntityCollection[ExtensionProperty] property

Purpose: Gets the list of extension properties defined on the application object

Returns: EntityCollection of ExtensionProperty objects

@property token_issuance_policies(self) -> EntityCollection[TokenIssuancePolicy] property

Purpose: Gets all token issuance policies assigned to this application

Returns: EntityCollection of TokenIssuancePolicy objects

Attributes

Name Type Description Scope
context ClientContext Inherited from DirectoryObject - the client context for making API calls to Microsoft Graph instance
resource_path ResourcePath Inherited from DirectoryObject - the API endpoint path for this application resource instance
properties dict Inherited from DirectoryObject - dictionary storing all application properties and their values instance
_ser_property_names list Internal list tracking property names that need serialization during updates instance

Dependencies

  • base64
  • datetime
  • typing
  • office365

Required Imports

import base64
import datetime
from typing import Optional
from office365.directory.applications.api import ApiApplication
from office365.directory.applications.public_client import PublicClientApplication
from office365.directory.applications.roles.role import AppRole
from office365.directory.applications.spa import SpaApplication
from office365.directory.certificates.certification import Certification
from office365.directory.extensions.extension_property import ExtensionProperty
from office365.directory.key_credential import KeyCredential
from office365.directory.object import DirectoryObject
from office365.directory.object_collection import DirectoryObjectCollection
from office365.directory.password_credential import PasswordCredential
from office365.directory.policies.token_issuance import TokenIssuancePolicy
from office365.entity_collection import EntityCollection
from office365.runtime.client_result import ClientResult
from office365.runtime.client_value_collection import ClientValueCollection
from office365.runtime.paths.resource_path import ResourcePath
from office365.runtime.queries.service_operation import ServiceOperationQuery
from office365.runtime.types.collections import StringCollection

Usage Example

# Assuming you have an authenticated GraphClient context
from office365.graph_client import GraphClient

# Get an application by ID
client = GraphClient(credentials)
app = client.applications.get_by_id('app-id-here')

# Add a certificate to the application
with open('certificate.cer', 'rb') as cert_file:
    cert_data = cert_file.read()
app.add_certificate(
    cert_data=cert_data,
    display_name='MyCertificate',
    start_datetime=datetime.datetime.utcnow(),
    end_datetime=datetime.datetime.utcnow() + datetime.timedelta(days=365)
)

# Add a password credential
password_result = app.add_password(display_name='MyAppPassword')
client.execute_query()
print(f'Password: {password_result.value.secret_text}')

# Set verified publisher
app.set_verified_publisher(verified_publisher_id='12345')
client.execute_query()

# Access application properties
print(f'App ID: {app.app_id}')
print(f'Display Name: {app.display_name}')
print(f'Sign-in Audience: {app.signin_audience}')

# Get owners
owners = app.owners
client.load(owners)
client.execute_query()
for owner in owners:
    print(f'Owner: {owner.display_name}')

Best Practices

  • Always call context.execute_query() after making changes to persist them to Azure AD
  • Use method chaining for multiple operations before executing the query batch
  • Store certificate and password credentials securely; passwords are only returned once during creation
  • Set appropriate start_datetime and end_datetime for certificates to manage credential lifecycle
  • Use permanent_delete=True cautiously as it permanently removes the application from the directory
  • When using add_key/remove_key for key rotation, ensure you have valid proof JWT tokens signed with existing keys
  • Access properties lazily - they are loaded on-demand and may require execute_query() to populate
  • Handle ClientResult objects properly by executing queries before accessing their value property
  • Use the owners collection to manage application ownership and permissions
  • The remove_certificate method is not implemented and will raise NotImplementedError

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class ApplicationTemplate 70.8% similar

    Represents an application template in the Azure AD application gallery, providing methods to instantiate applications and access their metadata.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/applications/template.py
  • class ApplicationServicePrincipal 68.4% similar

    Represents the concatenation of an Azure AD application and servicePrincipal object created when an application instance is added from the Azure AD application gallery.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/applications/service_principal.py
  • class ApiApplication 67.0% similar

    A data class representing configuration settings for an application that implements a web API, specifically for Azure AD application registration.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/applications/api.py
  • class ServicePrincipal 67.0% similar

    Represents an instance of an application in a directory, providing methods to manage service principal credentials, permissions, and role assignments in Azure Active Directory.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/serviceprincipals/service_principal.py
  • class ApplicationCollection 63.9% similar

    A collection class for managing Application objects in a directory, providing methods to retrieve and manage applications with delta query support.

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