MicrosoftGraphApplications
Use the Entra ID Applications integration (formerly Azure Active Directory Applications) to manage authorized applications.
IT Services · Microsoft Graph Applications
Details
| ID | MicrosoftGraphApplications |
|---|---|
| Provider | Microsoft |
| Category | IT Services |
| From Version | 5.0.0 |
| Docker Image | demisto/crypto:1.0.0.8187750 |
| Supported Modules | Agentix Cloud Runtime Security Cloud Posture Security XSIAM EDR Cortex Cloud |
README
Use the Entra ID Applications integration (formerly Azure Active Directory Applications) to manage authorized applications.
This integration was integrated and tested with version v1.0 of Microsoft Graph Services API.
Configure Entra ID Applications in Cortex
| Parameter | Description | Required |
|---|---|---|
| Application ID | False | |
| Azure AD endpoint | Azure AD endpoint associated with a national cloud. | False |
| Trust any certificate (not secure) | False | |
| Use system proxy settings | False | |
| Authentication Type | Type of authentication - could be Client Credentials Authorization Flow (recommended) or Device Flow | False |
| Tenant ID (for Client Credentials mode) | False | |
| Client Secret (for Client Credentials mode) | False | |
| Azure Managed Identities Client ID | The Managed Identities client ID for authentication - relevant only if the integration is running on Azure VM. | False |
Commands
You can execute these commands from the CLI, as part of an automation, or in a playbook.
After you successfully execute a command, a DBot message appears in the War Room with the command details.
msgraph-apps-auth-start
Run this command to start the authorization process and follow the instructions in the command results.
msgraph-apps-auth-complete
Run this command to complete the authorization process. Should be used after running the msgraph-apps-auth-start command.
msgraph-apps-auth-reset
Run this command if for some reason you need to rerun the authentication process.
msgraph-apps-auth-test
Tests connectivity to Microsoft.
msgraph-apps-service-principal-list
Retrieves a list of applications.
Base Command
msgraph-apps-service-principal-list
Input
| Argument Name | Description | Required |
|---|---|---|
| limit | Maximum results to fetch. A value of 0 fetches all results. Default is 10. | Optional |
Context Output
| Path | Type | Description |
|---|---|---|
| MSGraphApplication.keyCredentials.keyId | String | The unique identifier (GUID) for the key. |
| MSGraphApplication.keyCredentials.customKeyIdentifier | String | Custom key identifier. |
| MSGraphApplication.keyCredentials.displayName | String | Friendly name for the key. Optional. |
| MSGraphApplication.keyCredentials.type | String | The type of key credential; for example, “Symmetric”. |
| MSGraphApplication.keyCredentials.key | String | The certificate’s raw data in byte array converted to Base64 string. |
| MSGraphApplication.keyCredentials.usage | String | A string that describes the purpose for which the key can be used; for example, “Verify”. |
| MSGraphApplication.keyCredentials.startDateTime | Date | The date and time at which the credential expires.The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: ‘2014-01-01T00:00:00Z’ |
| MSGraphApplication.keyCredentials.endDateTime | Date | The date and time at which the credential becomes valid.The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: ‘2014-01-01T00:00:00Z’ |
| MSGraphApplication.accountEnabled | Boolean | true if the application account is enabled; otherwise, false. |
| MSGraphApplication.appDescription | String | A brief description of the application. |
| MSGraphApplication.appDisplayName | String | The display name exposed by the associated application. |
| MSGraphApplication.appId | String | The unique identifier for the associated application (its appId property). |
| MSGraphApplication.appOwnerOrganizationId | String | Contains the tenant ID where the application is registered. This is applicable only to service principals backed by applications. |
| MSGraphApplication.appRoleAssignmentRequired | Boolean | Whether users or other service principals need to be granted an application role assignment for this service principal before users can sign in or apps can get tokens. Default is false. |
| MSGraphApplication.applicationTemplateId | String | Unique identifier of the application template that the service principal was created from. |
| MSGraphApplication.createdDateTime | Date | Time the application was created. |
| MSGraphApplication.deletedDateTime | Date | Time the application was deleted. |
| MSGraphApplication.description | String | A brief description of the application. |
| MSGraphApplication.displayName | String | The display name for the application. |
| MSGraphApplication.homepage | String | Home page or landing page of the application. |
| MSGraphApplication.id | String | The unique identifier for the application. |
| MSGraphApplication.info.logoUrl | String | Content delivery network (CDN) URL to the application’s logo. |
| MSGraphApplication.info.marketingUrl | String | Link to the application’s marketing page. |
| MSGraphApplication.info.privacyStatementUrl | String | Link to the application’s privacy statement. |
| MSGraphApplication.info.supportUrl | String | Link to the application’s support page. |
| MSGraphApplication.info.termsOfServiceUrl | String | Link to the application’s terms of service statement. |
| MSGraphApplication.loginUrl | String | The URL where the service provider redirects the user to Microsoft Entra ID to authenticate. Microsoft Entra ID uses the URL to launch the application from Microsoft 365 or the Microsoft Entra My Apps. |
| MSGraphApplication.logoutUrl | String | Specifies the URL that will be used by Microsoft’s authorization service to log out an user. |
| MSGraphApplication.notes | String | The application’s notes. |
| MSGraphApplication.oauth2PermissionScopes.adminConsentDescription | String | A description of the delegated permissions, intended to be read by an administrator granting the permission on behalf of all users. This text appears in tenant-wide admin consent experiences. |
| MSGraphApplication.oauth2PermissionScopes.adminConsentDisplayName | String | The permission’s title, intended to be read by an administrator granting the permission on behalf of all users. |
| MSGraphApplication.oauth2PermissionScopes.id | String | Unique delegated permission identifier inside the collection of delegated permissions defined for a resource application. |
| MSGraphApplication.oauth2PermissionScopes.isEnabled | Boolean | Whether OAuth 2.0 permission scopes are enabled. |
| MSGraphApplication.oauth2PermissionScopes.type | String | Whether this delegated permission should be considered safe for non-admin users to consent to on behalf of themselves, or whether an administrator should be required for consent to the permissions. |
| MSGraphApplication.oauth2PermissionScopes.userConsentDescription | String | A description of the delegated permissions, intended to be read by a user granting the permission on their own behalf. This text appears in consent experiences where the user is consenting only on behalf of themselves. |
| MSGraphApplication.oauth2PermissionScopes.userConsentDisplayName | String | A title for the permission. |
| MSGraphApplication.oauth2PermissionScopes.value | String | The value to include in the scope claim in access tokens. |
| MSGraphApplication.preferredSingleSignOnMode | String | The single sign-on mode configured for this application. Microsoft Entra ID uses the preferred single sign-on mode to launch the application from Microsoft 365 or the Microsoft Entra My Apps. The supported values are password, SAML, external, and OIDC. |
| MSGraphApplication.preferredTokenSigningKeyThumbprint | String | Thumbprint of preferred certificate to sign the token. |
| MSGraphApplication.replyUrls | String | The URLs that user tokens are sent to for signing in with the associated application, or the redirect URIs that OAuth 2.0 authorization codes and access tokens are sent to for the associated application. |
| MSGraphApplication.samlSingleSignOnSettings | String | The collection for settings related to SAML single sign-on. |
| MSGraphApplication.servicePrincipalNames | String | The list of identifier URIs. |
| MSGraphApplication.servicePrincipalType | String | Identifies if the service principal represents an application or a managed identity. |
| MSGraphApplication.signInAudience | String | The audience that can sign in. |
| MSGraphApplication.tokenEncryptionKeyId | String | The key ID of a public key from the key credentials. |
| MSGraphApplication.verifiedPublisher.addedDateTime | Date | The timestamp when the verified publisher was first added or most recently updated. |
| MSGraphApplication.verifiedPublisher.displayName | String | The verified publisher name from the application publisher’s Partner Center account. |
| MSGraphApplication.verifiedPublisher.verifiedPublisherId | String | The ID of the verified publisher from the application publisher’s Partner Center account. |
Command Example
!msgraph-apps-service-principal-list limit=1
Context Example
{
"MSGraphApplication": {
"accountEnabled": true,
"addIns": [],
"alternativeNames": [],
"appDescription": null,
"appDisplayName": "Common Data Service",
"appId": "00000007-0000-0000-c000-000000000000",
"appOwnerOrganizationId": ":app-owner-organization-id:",
"appRoleAssignmentRequired": false,
"appRoles": [],
"applicationTemplateId": null,
"createdDateTime": "2019-12-11T11:35:03Z",
"deletedDateTime": null,
"description": null,
"displayName": "Common Data Service",
"homepage": null,
"id": ":id:",
"info": {
"logoUrl": null,
"marketingUrl": null,
"privacyStatementUrl": null,
"supportUrl": null,
"termsOfServiceUrl": null
},
"keyCredentials": [],
"loginUrl": null,
"logoutUrl": null,
"notes": null,
"notificationEmailAddresses": [],
"oauth2PermissionScopes": [
{
"adminConsentDescription": "Allows the application to access Common Data Service acting as users in the organization.",
"adminConsentDisplayName": "Access Common Data Service as organization users",
"id": ":id:",
"isEnabled": true,
"type": "User",
"userConsentDescription": "Allows the application to access Common Data Service as you.",
"userConsentDisplayName": "Access Common Data Service as you",
"value": "user_impersonation"
}
],
"passwordCredentials": [],
"preferredSingleSignOnMode": null,
"preferredTokenSigningKeyThumbprint": null,
"replyUrls": [
"https://admin.example.com/",
"https://port.example..com/",
"https://cloudredirector.example.com/"
],
"resourceSpecificApplicationPermissions": [],
"samlSingleSignOnSettings": null,
"servicePrincipalNames": [
"https://admin.example.com/",
"https://port.example.com/",
"https://cloudredirector.example.com/"
],
"servicePrincipalType": "Application",
"signInAudience": "AzureADMultipleOrgs",
"tags": [],
"tokenEncryptionKeyId": null,
"verifiedPublisher": {
"addedDateTime": null,
"displayName": null,
"verifiedPublisherId": null
}
}
}
Human Readable Output
Available services (applications)
id appId appDisplayName accountEnabled :id: 00000007-0000-0000-c000-000000000000 Common Data Service true
msgraph-apps-service-principal-remove
Removes an application from the directory.
Base Command
msgraph-apps-service-principal-remove
Input
| Argument Name | Description | Required |
|---|---|---|
| id | The application id to remove. Can be retrieved via the msgraph-apps-service-principal-list command. | Optional |
| app_id | The application client id to remove. Can be retrieved via the msgraph-apps-service-principal-list command. | Optional |
Context Output
There is no context output for this command.
Command Example
!msgraph-apps-service-principal-remove id=ID_TEST
Human Readable Output
Service ID_TEST was deleted.
msgraph-apps-service-principal-get
Retrieve the properties and relationships of a servicePrincipal object.
Base Command
msgraph-apps-service-principal-get
Input
| Argument Name | Description | Required |
|---|---|---|
| id | The application id to get. Can be retrieved via the msgraph-apps-service-principal-list command. | Optional |
| app_id | The application client id to get. Can be retrieved via the msgraph-apps-service-principal-list command. | Optional |
Context Output
| Path | Type | Description |
|---|---|---|
| MSGraphApplication.keyCredentials.keyId | String | The unique identifier (GUID) for the key. |
| MSGraphApplication.keyCredentials.customKeyIdentifier | String | Custom key identifier. |
| MSGraphApplication.keyCredentials.displayName | String | Friendly name for the key. Optional. |
| MSGraphApplication.keyCredentials.type | String | The type of key credential; for example, “Symmetric”. |
| MSGraphApplication.keyCredentials.key | String | The certificate’s raw data in byte array converted to Base64 string. |
| MSGraphApplication.keyCredentials.usage | String | A string that describes the purpose for which the key can be used; for example, “Verify”. |
| MSGraphApplication.keyCredentials.startDateTime | Date | The date and time at which the credential expires.The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: ‘2014-01-01T00:00:00Z’. |
| MSGraphApplication.keyCredentials.endDateTime | Date | The date and time at which the credential becomes valid.The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: ‘2014-01-01T00:00:00Z’. |
| MSGraphApplication.accountEnabled | Boolean | true if the application account is enabled; otherwise, false. |
| MSGraphApplication.appDescription | String | A brief description of the application. |
| MSGraphApplication.appDisplayName | String | The display name exposed by the associated application. |
| MSGraphApplication.appId | String | The unique identifier for the associated application (its appId property). |
| MSGraphApplication.appOwnerOrganizationId | String | Contains the tenant ID where the application is registered. This is applicable only to service principals backed by applications. |
| MSGraphApplication.appRoleAssignmentRequired | Boolean | Whether users or other service principals need to be granted an application role assignment for this service principal before users can sign in or apps can get tokens. Default is false. |
| MSGraphApplication.applicationTemplateId | String | Unique identifier of the application template that the service principal was created from. |
| MSGraphApplication.createdDateTime | Date | Time the application was created. |
| MSGraphApplication.deletedDateTime | Date | Time the application was deleted. |
| MSGraphApplication.description | String | A brief description of the application. |
| MSGraphApplication.displayName | String | The display name for the application. |
| MSGraphApplication.homepage | String | Home page or landing page of the application. |
| MSGraphApplication.id | String | The unique identifier for the application. |
| MSGraphApplication.info.logoUrl | String | Content delivery network (CDN) URL to the application’s logo. |
| MSGraphApplication.info.marketingUrl | String | Link to the application’s marketing page. |
| MSGraphApplication.info.privacyStatementUrl | String | Link to the application’s privacy statement. |
| MSGraphApplication.info.supportUrl | String | Link to the application’s support page. |
| MSGraphApplication.info.termsOfServiceUrl | String | Link to the application’s terms of service statement. |
| MSGraphApplication.loginUrl | String | The URL where the service provider redirects the user to Microsoft Entra ID to authenticate. Microsoft Entra ID uses the URL to launch the application from Microsoft 365 or the Microsoft Entra My Apps. |
| MSGraphApplication.logoutUrl | String | Specifies the URL that will be used by Microsoft’s authorization service to log out an user. |
| MSGraphApplication.notes | String | The application’s notes. |
| MSGraphApplication.oauth2PermissionScopes.adminConsentDescription | String | A description of the delegated permissions, intended to be read by an administrator granting the permission on behalf of all users. This text appears in tenant-wide admin consent experiences. |
| MSGraphApplication.oauth2PermissionScopes.adminConsentDisplayName | String | The permission’s title, intended to be read by an administrator granting the permission on behalf of all users. |
| MSGraphApplication.oauth2PermissionScopes.id | String | Unique delegated permission identifier inside the collection of delegated permissions defined for a resource application. |
| MSGraphApplication.oauth2PermissionScopes.isEnabled | Boolean | Whether OAuth 2.0 permission scopes are enabled. |
| MSGraphApplication.oauth2PermissionScopes.type | String | Whether this delegated permission should be considered safe for non-admin users to consent to on behalf of themselves, or whether an administrator should be required for consent to the permissions. |
| MSGraphApplication.oauth2PermissionScopes.userConsentDescription | String | A description of the delegated permissions, intended to be read by a user granting the permission on their own behalf. This text appears in consent experiences where the user is consenting only on behalf of themselves. |
| MSGraphApplication.oauth2PermissionScopes.userConsentDisplayName | String | A title for the permission. |
| MSGraphApplication.oauth2PermissionScopes.value | String | The value to include in the scope claim in access tokens. |
| MSGraphApplication.preferredSingleSignOnMode | String | The single sign-on mode configured for this application. Microsoft Entra ID uses the preferred single sign-on mode to launch the application from Microsoft 365 or the Microsoft Entra My Apps. The supported values are password, SAML, external, and OIDC. |
| MSGraphApplication.preferredTokenSigningKeyThumbprint | String | Thumbprint of preferred certificate to sign the token. |
| MSGraphApplication.replyUrls | String | The URLs that user tokens are sent to for signing in with the associated application, or the redirect URIs that OAuth 2.0 authorization codes and access tokens are sent to for the associated application. |
| MSGraphApplication.samlSingleSignOnSettings | String | The collection for settings related to SAML single sign-on. |
| MSGraphApplication.servicePrincipalNames | String | The list of identifier URIs. |
| MSGraphApplication.servicePrincipalType | String | Identifies if the service principal represents an application or a managed identity. |
| MSGraphApplication.signInAudience | String | The audience that can sign in. |
| MSGraphApplication.tokenEncryptionKeyId | String | The key ID of a public key from the key credentials. |
| MSGraphApplication.verifiedPublisher.addedDateTime | Date | The timestamp when the verified publisher was first added or most recently updated. |
| MSGraphApplication.verifiedPublisher.displayName | String | The verified publisher name from the application publisher’s Partner Center account. |
| MSGraphApplication.verifiedPublisher.verifiedPublisherId | String | The ID of the verified publisher from the application publisher’s Partner Center account. |
Command Example
!msgraph-apps-service-principal-get id=TEST
Context Example
{'@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#servicePrincipals/$entity',
'id': 'XXXX', 'deletedDateTime': None, 'accountEnabled': True, 'alternativeNames': [],
'appDisplayName': 'Test', 'appDescription': None,
'appId': 'XXXX', 'applicationTemplateId': None, 'appOwnerOrganizationId': 'XXXX',
'appRoleAssignmentRequired': False, 'createdDateTime': '', 'description': None,
'disabledByMicrosoftStatus': None, 'displayName': 'Test', 'homepage': None, 'loginUrl': None,
'logoutUrl': None, 'notes': None, 'notificationEmailAddresses': [],
'preferredSingleSignOnMode': None, 'preferredTokenSigningKeyThumbprint': None, 'replyUrls': [],
'servicePrincipalNames': ['XXXX'], 'servicePrincipalType': 'Application',
'signInAudience': 'AzureADMyOrg',
'tags': ['HideApp', 'WindowsAzureActiveDirectoryIntegratedApp'], 'tokenEncryptionKeyId': None,
'samlSingleSignOnSettings': None, 'addIns': [], 'appRoles': [],
'info': {'logoUrl': None, 'marketingUrl': None, 'privacyStatementUrl': None, 'supportUrl': None,
'termsOfServiceUrl': None}, 'keyCredentials': [], 'oauth2PermissionScopes': [],
'passwordCredentials': [], 'resourceSpecificApplicationPermissions': [],
'verifiedPublisher': {'displayName': None, 'verifiedPublisherId': None, 'addedDateTime': None}}
msgraph-apps-service-principal-update
Update the properties of servicePrincipal object.
Base Command
msgraph-apps-service-principal-update
Input
| Argument Name | Description | Required |
|---|---|---|
| id | The application id to update. Can be retrieved via the msgraph-apps-service-principal-list command. | Optional |
| app_id | The application client id to update. Can be retrieved via the msgraph-apps-service-principal-list command. | Optional |
| account_enabled | true if the service principal account is enabled; otherwise, false. Possible values are: true, false. | Optional |
| app_role_assignment_required | Specifies whether an appRoleAssignment to a user or group is required before Microsoft Entra ID will issue a user or access token to the application. Possible values are: true, false. | Optional |
| display_name | The display name for the service principal. | Optional |
| preferred_single_sign_on_mode | Specifies the single sign-on mode configured for this application. Microsoft Entra ID uses the preferred single sign-on mode to launch the application from Microsoft 365 or the Microsoft Entra My Apps. The supported values are password, saml, and oidc. Possible values are: password, saml, oidc. | Optional |
| reply_urls | A comma-separated list of the URLs that user tokens are sent to for sign in with the associated application, or the redirect URIs that OAuth 2.0 authorization codes and access tokens are sent to for the associated application. | Optional |
Context Output
There is no context output for this command.
Command Example
!msgraph-apps-service-principal-update id=TEST account_enabled=true
Human Readable Output
Service TEST was updated successfully.
msgraph-apps-service-principal-password-add
Add a strong password or secret to a service principal.
Base Command
msgraph-apps-service-principal-password-add
Input
| Argument Name | Description | Required |
|---|---|---|
| id | The application id to add password. Can be retrieved via the msgraph-apps-service-principal-list command. | Optional |
| app_id | The application client id to add password. Can be retrieved via the msgraph-apps-service-principal-list command. | Optional |
| display_name | Friendly name for the password. Optional. | Optional |
| end_date_time | The date and time at which the password expires represented using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. Optional. The default value is “startDateTime + 2 years”. | Optional |
| start_date_time | The date and time at which the password becomes valid. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. Optional. The default value is “now”. | Optional |
Context Output
| Path | Type | Description |
|---|---|---|
| MSGraphApplication.keyCredentials.customKeyIdentifier | String | Custom key identifier. |
| MSGraphApplication.keyCredentials.endDateTime | Date | The date and time at which the credential becomes valid.The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: ‘2014-01-01T00:00:00Z’. |
| MSGraphApplication.keyCredentials.keyId | String | The unique identifier (GUID) for the key. |
| MSGraphApplication.keyCredentials.startDateTime | Date | The date and time at which the credential expires.The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: ‘2014-01-01T00:00:00Z’. |
| MSGraphApplication.keyCredentials.displayName | String | Friendly name for the key. Optional. |
| MSGraphApplication.keyCredentials.secretText | String | The strong passwords generated by Entra ID that are 16-64 characters in length. There is no way to retrieve this password in the future. |
| MSGraphApplication.keyCredentials.hint | String | The secretText prefix. |
Command Example
!msgraph-apps-service-principal-password-add id=TEST display_name='TEST'
Context Example
{'@odata.context': '',
'customKeyIdentifier': None,
'displayName': 'TEST',
'endDateTime': '',
'hint': '',
'keyId': '',
'secretText': '',
'startDateTime': ''}
Human Readable Output
A password was added to application TEST successfully.
msgraph-apps-service-principal-password-remove
Remove a password from a service principal.
Base Command
msgraph-apps-service-principal-password-remove
Input
| Argument Name | Description | Required |
|---|---|---|
| id | The application id to remove password. Can be retrieved via the msgraph-apps-service-principal-list command. | Optional |
| app_id | The application client id to remove password. Can be retrieved via the msgraph-apps-service-principal-list command. | Optional |
| key_id | The unique identifier for the password. | Required |
Context Output
There is no context output for this command.
Command Example
!msgraph-apps-service-principal-password-remove id=TEST key_id=KEY_TEST
Human Readable Output
The password of the unique identifier KEY_TEST was removed successfully.
msgraph-apps-service-principal-unlock-configuration
Unlock configuration of a service principal.
Base Command
msgraph-apps-service-principal-unlock-configuration
Input
| Argument Name | Description | Required |
|---|---|---|
| id | The application object id (not the app id). | Required |
Context Output
There is no context output for this command.
Command Example
!msgraph-apps-service-principal-unlock-configuration id=TEST
Human Readable Output
The configuration of TEST was unlocked successfully.
msgraph-apps-service-principal-lock-configuration
Lock configuration of a service principal.
Base Command
msgraph-apps-service-principal-lock-configuration
Input
| Argument Name | Description | Required |
|---|---|---|
| id | The application object id (not the app id). | Required |
Context Output
There is no context output for this command.
Command Example
!msgraph-apps-service-principal-lock-configuration id=TEST
Human Readable Output
The configuration of TEST was locked successfully.
Configuration parameters
app_id— Application IDazure_ad_endpoint— Azure AD endpointinsecure— Trust any certificate (not secure)proxy— Use system proxy settingsauthentication_type— Authentication Typetenant_id— Tenant ID (for Client Credentials mode)credentials— Client Secret (for Client Credentials mode)managed_identities_client_id—
Commands (12)
-
msgraph-apps-auth-completeRun this command to complete the authorization process. Should be used after running the msgraph-apps-auth-start command.
-
msgraph-apps-auth-resetRun this command if for some reason you need to rerun the authentication process.
-
msgraph-apps-auth-startRun this command to start the authorization process and follow the instructions in the command results.
-
msgraph-apps-auth-testTests connectivity to Microsoft.
-
msgraph-apps-service-principal-getRetrieve the properties and relationships of a servicePrincipal object.
-
msgraph-apps-service-principal-listRetrieves a list of applications.
-
msgraph-apps-service-principal-lock-configurationLock configuration of a service principal.
-
msgraph-apps-service-principal-password-addAdd a strong password or secret to a service principal. To allow this command, use msgraph-apps-service-principal-unlock-configuration. The password will be expired in 1 hour by default.
-
msgraph-apps-service-principal-password-removeRemove a password from a service principal. To allow this command, use msgraph-apps-service-principal-unlock-configuration.
-
msgraph-apps-service-principal-removeRemoves an application from the directory.
-
msgraph-apps-service-principal-unlock-configurationUnlock configuration of a service principal.
-
msgraph-apps-service-principal-updateUpdate the properties of servicePrincipal object.
""" An integration to MS Graph Service Principals endpoint. https://docs.microsoft.com/en-us/graph/api/resources/serviceprincipal?view=graph-rest-1.0 """ import urllib3 from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import from MicrosoftApiModule import * # noqa: E402 from CommonServerUserPython import * # noqa # Disable insecure warnings urllib3.disable_warnings() GRANT_BY_CONNECTION = {"Device Code": DEVICE_CODE, "Client Credentials": CLIENT_CREDENTIALS} SCOPE_BY_CONNECTION = { "Device Code": "offline_access Application.ReadWrite.All", "Client Credentials": "https://graph.microsoft.com/.default", } class Client: def __init__( self, app_id: str, verify: bool, proxy: bool, connection_type: str, tenant_id: str, enc_key: str, azure_ad_endpoint: str = "https://login.microsoftonline.com", managed_identities_client_id: Optional[str] = None, ): if app_id and "@" in app_id: app_id, refresh_token = app_id.split("@") integration_context = get_integration_context() integration_context.update(current_refresh_token=refresh_token) set_integration_context(integration_context) token_retrieval_url = ( "https://login.microsoftonline.com/organizations/oauth2/v2.0/token" if "Client" not in connection_type else None ) client_args = assign_params( self_deployed=True, auth_id=app_id, token_retrieval_url=token_retrieval_url, grant_type=GRANT_BY_CONNECTION.get(connection_type), base_url="https://graph.microsoft.com", verify=verify, proxy=proxy, scope=SCOPE_BY_CONNECTION.get(connection_type), azure_ad_endpoint=azure_ad_endpoint, tenant_id=tenant_id, enc_key=enc_key, managed_identities_client_id=managed_identities_client_id, managed_identities_resource_uri=Resources.graph, command_prefix="msgraph-apps", ) self.ms_client = MicrosoftClient(**client_args) self.connection_type = connection_type def get_service_principals(self, limit: int) -> list: """Get all service principals. Arguments: limit: Maximum of services to get. Returns: All given service principals Docs: https://docs.microsoft.com/en-us/graph/api/serviceprincipal-list?view=graph-rest-1.0&tabs=http """ suffix = "v1.0/servicePrincipals" if limit > 0: res = self.ms_client.http_request("GET", suffix + f"?$top={limit}") return res["value"] else: # unlimited, should page results = [] res = self.ms_client.http_request("GET", suffix) results.extend(res.get("value")) while next_link := res.get("@odata.nextLink"): res = self.ms_client.http_request("GET", "", next_link) results.extend(res.get("value")) return results def get_single_service_principal(self, service_id: str): """ Arguments: service_id: object id or application id of the service. Returns: Retrieve the properties and relationships of a servicePrincipal object. Docs: https://learn.microsoft.com/en-us/graph/api/serviceprincipal-get?view=graph-rest-1.0&tabs=http """ suffix = f"v1.0/servicePrincipals{service_id}" return self.ms_client.http_request(method="GET", url_suffix=suffix) def update_single_service_principal(self, service_id: str, data: dict): """ Arguments: service_id: object id or application id of the service. data: Fields to update. Returns: Update the properties of servicePrincipal object. Docs: https://learn.microsoft.com/en-us/graph/api/serviceprincipal-update?view=graph-rest-1.0&tabs=http """ suffix = f"v1.0/servicePrincipals{service_id}" return self.ms_client.http_request(method="PATCH", url_suffix=suffix, json_data=data, return_empty_response=True) def delete_service_principals(self, service_id: str): """Deletes a given id from authorized apps. Arguments: service_id: the service to remove Returns: True if removed successfully Raises: DemistoException if no app exists or any other requests error. Docs: https://docs.microsoft.com/en-us/graph/api/serviceprincipal-delete?view=graph-rest-1.0&tabs=http """ self.ms_client.http_request(method="DELETE", url_suffix=f"v1.0/servicePrincipals{service_id}", return_empty_response=True) def add_password_service_principal(self, service_id: str, data: dict): """ Arguments: service_id: object id or application id of the service. data: the body request. As you can see in the documentation, it may have displayName, endDateTime, and startDateTime. Returns: Adds a strong password or secret to an application. Docs: https://learn.microsoft.com/en-us/graph/api/application-addpassword?view=graph-rest-1.0&tabs=http """ suffix = f"v1.0/servicePrincipals{service_id}/addPassword" json_data = {"passwordCredential": data} return self.ms_client.http_request(method="POST", url_suffix=suffix, json_data=json_data) def remove_password_service_principal(self, service_id: str, data: dict): """ Arguments: service_id: object id or application id of the service. data: the body request. As you can see in the documentation, it should contain the keyId, the unique identifier for the password. Returns: Remove a password from an application. Docs: https://learn.microsoft.com/en-us/graph/api/application-removepassword?view=graph-rest-1.0&tabs=http """ suffix = f"v1.0/servicePrincipals{service_id}/removePassword" return self.ms_client.http_request(method="POST", url_suffix=suffix, json_data=data, return_empty_response=True) def unlock_configuration_service_principal(self, service_id: str, lock: bool): """ Arguments: lock: Whether to lock or unlock. True to lock, False to unlock. service_id: object id or application id of the service. Returns: Remove a password from an application. Docs: https://learn.microsoft.com/en-us/graph/api/application-removepassword?view=graph-rest-1.0&tabs=http """ data = { "servicePrincipalLockConfiguration": { "isEnabled": lock, "credentialsWithUsageSign": True, "credentialsWithUsageVerify": True, } } suffix = f"/beta/applications/{service_id}" return self.ms_client.http_request(method="PATCH", url_suffix=suffix, json_data=data, return_empty_response=True) """ COMMAND FUNCTIONS """ def start_auth(client: Client) -> CommandResults: result = client.ms_client.start_auth("!msgraph-apps-auth-complete") return CommandResults(readable_output=result) def complete_auth(client: Client) -> str: client.ms_client.get_access_token() return "✅ Authorization completed successfully." def test_connection(client: Client) -> str: client.ms_client.get_access_token() return "✅ Success!" def list_service_principals_command(ms_client: Client, args: dict) -> CommandResults: """Lists all service principals Arguments: ms_client: The Client args: demisto.args() Returns: Results to post in demisto """ limit_str = args.get("limit", "") try: limit = int(limit_str) except ValueError: raise DemistoException(f'Limit must be an integer, not "{limit_str}"') results = ms_client.get_service_principals(limit) return CommandResults( "MSGraphApplication", "id", outputs=results, readable_output=tableToMarkdown( "Available services (applications):", results, headers=["id", "appId", "appDisplayName", "accountEnabled", "deletedDateTime"], removeNull=True, ), ) def validate_service_principal_input(args: dict) -> tuple[str, Optional[Any]]: """ Ensure at least one argument (object) id or app id is given. Args: args: The arguments were passed with the command. Returns: If the two arguments are missing, raise an exception, otherwise return the (object) id. This validation returns tuple, the first element will be sent to the api call, the second is the given id/app id as is. """ object_id = args.get("id") app_client_id = args.get("app_id") if not (object_id or app_client_id): raise DemistoException("Either the (object's) `id` or the `application_id` arguments must be provided.") # if both are provided, pass the object_id if object_id: return f"/{object_id}", object_id return f"(appId='{app_client_id}')", app_client_id def get_service_principal_command(ms_client: Client, args: dict) -> CommandResults: """ Args: ms_client: The Client args: demisto.args() Returns: Results to post in demisto """ id_for_request, service_id = validate_service_principal_input(args=args) results = ms_client.get_single_service_principal(id_for_request) return CommandResults( "MSGraphApplication", "id", outputs=results, readable_output=tableToMarkdown( "Service Principal (application):", results, headers=["id", "appId", "appDisplayName", "accountEnabled", "deletedDateTime"], removeNull=True, ), ) def update_service_principal_command(ms_client: Client, args: dict) -> CommandResults: """ Update the properties of servicePrincipal object. Args: ms_client: The Client args: demisto.args() Returns: an informative message. """ id_for_request, service_id = validate_service_principal_input(args=args) fields_to_update = { "app_role_assignment_required": "appRoleAssignmentRequired", "display_name": "displayName", "preferred_single_sign_on_mode": "preferredSingleSignOnMode", "reply_urls": "replyUrls", } boolean_fields_to_update = {"account_enabled": "accountEnabled", "app_role_assignment_required": "appRoleAssignmentRequired"} data = {fields_to_update[field]: args[field] for field in fields_to_update if field in args} for field in boolean_fields_to_update: if field in args: data[boolean_fields_to_update[field]] = argToBoolean(args[field]) if "replyUrls" in data: data["replyUrls"] = argToList(data["replyUrls"]) ms_client.update_single_service_principal(id_for_request, data=data) return CommandResults(readable_output=f"Service {service_id} was updated successfully.") def remove_service_principals_command(ms_client: Client, args: dict) -> CommandResults: """Remove an authorized app. Arguments: ms_client: The Client args: demisto.args() Returns: Results to post in demisto """ id_for_request, service_id = validate_service_principal_input(args=args) ms_client.delete_service_principals(id_for_request) return CommandResults(readable_output=f"Service {service_id} was deleted.") def add_password_service_principal_command(ms_client: Client, args: dict) -> CommandResults: """ Adds a strong password or secret to the service principal. Arguments: ms_client: The Client args: demisto.args() Returns: Results to post in demisto """ id_for_request, service_id = validate_service_principal_input(args=args) fields_for_body_request = {"display_name": "displayName", "end_date_time": "endDateTime", "start_date_time": "startDateTime"} data = {fields_for_body_request[field]: args[field] for field in fields_for_body_request if field in args} # If the user didn't pass the expiration time, we set it to 1 hour when the API set it to +2 years. if "endDateTime" not in data: data["endDateTime"] = str(datetime.now() + timedelta(hours=1)) results = ms_client.add_password_service_principal(id_for_request, data=data) return CommandResults( "MSGraphApplication", "id", outputs=results, readable_output=f"A password was added to application {service_id} successfully.", ) def remove_password_service_principal_command(ms_client: Client, args: dict) -> CommandResults: """ Remove a password from the service principal. Arguments: ms_client: The Client args: demisto.args() Returns: Results to post in demisto """ id_for_request, service_id = validate_service_principal_input(args=args) data = {"keyId": args["key_id"]} ms_client.remove_password_service_principal(id_for_request, data=data) return CommandResults(readable_output=f'The password of the unique identifier {args["key_id"]} was removed successfully.') def change_configuration_service_principal_lock_status(ms_client: Client, args: dict, lock: bool) -> CommandResults: """ Unlock / Lock configuration of a service principal. Arguments: lock: in the case of locking back the configuration. ms_client: The Client args: demisto.args() Returns: Results to post in demisto """ object_id = args["id"] ms_client.unlock_configuration_service_principal(service_id=object_id, lock=lock) return CommandResults( readable_output=f'The configuration of {object_id} was {"locked" if lock else "unlocked"} successfully.' ) def test_module(client: Client) -> str: """Tests API connectivity and authentication for client credentials only. Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. Raises exceptions if something goes wrong. :type client: ``Client`` :param Client: client to use :return: 'ok' if test passed. :rtype: ``str`` """ # This should validate all the inputs given in the integration configuration panel, # either manually or by using an API that uses them. if client.connection_type == "Device Code": raise DemistoException( "Test module is available for Client Credentials or Azure Managed Identities only," " for other authentication types use the msgraph-apps-auth-start command" ) test_connection(client) return "ok" def main(): # pragma: no cover handle_proxy() demisto.debug(f"Command being called is {demisto.command()}") try: command = demisto.command() params = demisto.params() args = demisto.args() client = Client( app_id=params.get("app_id", ""), verify=not params.get("insecure", False), proxy=params.get("proxy", False), azure_ad_endpoint=params.get("azure_ad_endpoint", "https://login.microsoftonline.com") or "https://login.microsoftonline.com", enc_key=(params.get("credentials", {})).get("password"), tenant_id=params.get("tenant_id"), connection_type=params.get("authentication_type", "Device Code"), managed_identities_client_id=get_azure_managed_identities_client_id(params), ) if command == "test-module": # This is the call made when pressing the integration Test button. return_results(test_module(client)) elif command == "msgraph-apps-auth-start": return_results(start_auth(client)) elif command == "msgraph-apps-auth-complete": return_results(complete_auth(client)) elif command == "msgraph-apps-auth-test": return_results(test_connection(client)) elif command == "msgraph-apps-auth-reset": return_results(reset_auth()) elif command == "msgraph-apps-service-principal-list": return_results(list_service_principals_command(client, args)) elif command == "msgraph-apps-service-principal-remove": return_results(remove_service_principals_command(client, args)) elif command == "msgraph-apps-service-principal-get": return_results(get_service_principal_command(client, args)) elif command == "msgraph-apps-service-principal-update": return_results(update_service_principal_command(client, args)) elif command == "msgraph-apps-service-principal-password-add": return_results(add_password_service_principal_command(client, args)) elif command == "msgraph-apps-service-principal-password-remove": return_results(remove_password_service_principal_command(client, args)) elif command == "msgraph-apps-service-principal-unlock-configuration": return_results(change_configuration_service_principal_lock_status(client, args, lock=False)) elif command == "msgraph-apps-service-principal-lock-configuration": return_results(change_configuration_service_principal_lock_status(client, args, lock=True)) else: raise NotImplementedError(f"Command '{command}' not found.") # Log exceptions and return errors except Exception as e: return_error(f"Failed to execute {demisto.command()} command.\nError:\n{e!s}") """ ENTRY POINT """ if __name__ in ("__main__", "__builtin__", "builtins"): main()