← Back to Home

Dynamic Conditional Access Policies
with Custom Security Attributes

Enterprise Architecture Guide
A Comprehensive Framework for Identity and Access Management

Version: 1.0  |  Date: October 2025

Prepared For: CISOs, Security Architects, System Engineers, and Identity Architects

By Stephen A. Adebowale — Senior Information Security Architect/vCISO  |  LinkedIn  |  X @SteveInfosec

Executive Summary

In today's rapidly evolving digital landscape, enterprises face an unprecedented challenge: securing access to hundreds or thousands of cloud applications while maintaining agility and operational efficiency. Traditional Conditional Access Policies (CAPs), while powerful, create significant management overhead through policy proliferation—often requiring one policy per application to address unique security requirements. This approach is neither scalable nor sustainable for modern enterprises.

Dynamic Conditional Access Policies with Custom Security Attributes represent a paradigm shift in identity and access management. By leveraging Custom Security Attributes as intelligent metadata tags, enterprises can reduce policy count by 70-80% while simultaneously increasing flexibility and control. Instead of creating individual policies for each application, security teams define reusable attributes that applications "inherit," enabling sophisticated, application-specific security controls through a fraction of the policies.

Key Benefits

Strategic Importance

Dynamic CAPs align with three critical enterprise imperatives:

  1. Zero Trust Architecture: Enable granular, context-aware access controls that verify explicitly and use least privilege access
  2. Cloud Transformation: Provide the agility needed to secure cloud-first and hybrid environments at scale
  3. Risk-Based Security: Apply security controls proportionate to application risk and sensitivity
🚨 CRITICAL REQUIREMENT

Dynamic CAPs are NOT a replacement for baseline persona-based Conditional Access policies. All enterprises MUST first implement comprehensive baseline policies covering ALL RESOURCES for all user personas (all users, guests, administrators, etc.). Dynamic CAPs enhance baseline policies by adding application-specific requirements on top of this foundation. Attempting to use Dynamic CAPs without baseline policies creates significant security gaps.

Table of Contents

1. Introduction to Dynamic Conditional Access Policies
1.1 Executive Overview
1.2 What is a Dynamic Conditional Access Policy?
1.3 Understanding Custom Security Attributes
1.4 The Evolution of Conditional Access
1.5 Technical Architecture Overview
2. Why Dynamic CAPs Are Used
3. How Dynamic CAPs Are Used
4. What Dynamic CAPs Are Used For
5. Where Dynamic CAPs Are Used
6. Who Uses and Maintains Dynamic CAPs
7. Design Best Practices
8. Deployment Best Practices
9. Monitoring and Logging
10. Technical Reference
11. Governance and Compliance
12. Conclusion and Recommendations
Appendices A-E

1. Introduction to Dynamic Conditional Access Policies

1.1 Executive Overview

Modern enterprises face a critical inflection point in identity and access management. The traditional approach of creating individual Conditional Access Policies for each application has become untenable as organizations scale their cloud footprint. A typical Fortune 500 company with 1,000+ cloud applications would need to manage an equivalent number of policies, each with unique security requirements, exceptions, and maintenance overhead.

The challenge of policy sprawl in modern enterprises manifests in several ways:

Dynamic Conditional Access Policies with Custom Security Attributes solve these challenges by introducing a new paradigm: instead of creating policies for applications, we create policies for security requirements and tag applications with those requirements.

1.2 What is a Dynamic Conditional Access Policy?

A Dynamic Conditional Access Policy is a Conditional Access Policy that uses application filters based on Custom Security Attributes to dynamically determine which applications are in scope. Rather than explicitly listing applications in the policy, the policy uses intelligent filtering to automatically include or exclude applications based on their assigned security attributes.

Traditional Static CAP Approach:

Result: 5 policies for 5 applications, all with identical security requirements

Dynamic CAP Approach:

Result: 1 policy covering 5 applications through intelligent attribute matching

AspectStatic CAPsDynamic CAPs
Policy Count1 policy per application1 policy per security requirement
Application TargetingExplicit application selectionAttribute-based filtering
New Application OnboardingCreate new policy or modify existingAssign appropriate attributes
Maintenance OverheadHigh - manage N policiesLow - manage attributes + few policies
ConsistencyManual effort requiredAutomatic through attribute taxonomy
Exception ManagementComplex - requires policy modificationSimple - change attribute assignment
Audit and ComplianceApplication-specific evidenceAttribute-based compliance mapping
Testing RequirementsTest every policy changeTest attribute assignment changes

1.3 Understanding Custom Security Attributes

Custom Security Attributes in Microsoft Entra ID provide a powerful framework for extending directory objects with business-specific metadata. Unlike traditional directory extensions, Custom Security Attributes are designed specifically for security and governance scenarios, offering enhanced access control and audit capabilities.

Key Concepts

Attribute Sets: Logical containers that group related attributes together. Each attribute set can contain up to 500 attributes and can be managed independently.

Attribute Definitions: The schema definition of an attribute, including its name, data type, allowed values, and business description.

Attribute Assignments: The actual values assigned to directory objects (users or service principals).

Data Types and Use Cases

Data TypeDescriptionUse CasesExample Values
BooleanTrue/False valuesFeature flags, compliance requirementstrue, false
IntegerNumeric valuesRisk scores, priority levels1, 2, 3, 100
StringText values (single or multiple)Security levels, geographical regions"Standard", "US", "Finance"

Attribute Properties and Lifecycle

PropertyDescriptionCan Change Later?
Attribute Set NameContainer for related attributesNo
Attribute NameUnique identifier within setNo
Data TypeBoolean, Integer, or StringNo
Allow Multiple ValuesSingle or multi-value assignmentNo
Predefined Values OnlyRestrict to specific valuesYes (No→Yes only)
Predefined Values ListAllowed values when restrictedYes
Attribute Active StatusEnable/disable attributeYes
💡 Service Principal vs Application

In the context of Dynamic CAPs, we assign attributes to service principals (the instance of an application in your tenant) rather than application objects (the global definition of the application). This distinction is important for multi-tenant applications where you want tenant-specific security requirements.

1.4 The Evolution of Conditional Access

The Policy Explosion Problem

YearApplicationsPoliciesManagement OverheadPrimary Challenges
20181010LowLearning curve
20205075MediumPolicy standardization
2022200350HighException management
2024500800+CriticalScalability crisis

The Shift to Dynamic, Attribute-Based Policies

Traditional ModelDynamic ModelImprovement
Reactive policy creationProactive attribute taxonomyPredictable governance
Application-specific securityRisk-based security levelsConsistent protection
Manual policy managementAutomated attribute assignmentOperational efficiency
Siloed security decisionsCentralized security taxonomyStrategic alignment
Point-in-time complianceContinuous compliance monitoringRegulatory readiness

1.5 Technical Architecture Overview

Dynamic CAP Architecture

User
Authentication
Microsoft
Entra ID
CAP Engine
Target
Application
Baseline Policies
(All Users/Apps)
Dynamic Policies
(Attribute-based)
Security Controls
Applied
Attribute
Query
Filter
Evaluation
Policy
Match
Access
Decision

Integration Points

Integration PointPurposeFrequency
Microsoft Graph APIAttribute management and queriesReal-time
Azure MonitorLogging and alertingNear real-time
Microsoft SentinelSecurity monitoring and SIEMNear real-time
PowerShell/CLIAutomation and managementOn-demand
Third-party SIEMSecurity monitoringConfigurable

2. Why Dynamic CAPs Are Used

2.1 Business Drivers

2.2 Challenges with Traditional CAPs

Policy Sprawl: The Mathematical Reality

ApplicationsBase PoliciesException PoliciesCompliance PoliciesTotal PoliciesMgmt Hours/Month
101032155
505015107525
2002006040300100
500500150100750250
100010003002001500500+

2.3 Benefits of Dynamic CAPs

ScenarioTraditional PoliciesDynamic PoliciesReductionTime Savings
Small Enterprise (50 apps)751284%20 hours/month
Mid Enterprise (200 apps)3001894%80 hours/month
Large Enterprise (500 apps)7502597%200 hours/month
Enterprise (1000 apps)15003598%400 hours/month

Application Onboarding Time Comparison

ActivityTraditional ApproachDynamic CAP ApproachTime Savings
Security Assessment2-4 hours30 minutes2-3.5 hours
Policy Creation1-2 hours5 minutes1-2 hours
Testing4-8 hours30 minutes3.5-7.5 hours
Documentation1 hour10 minutes50 minutes
Approval Process24-48 hours2-4 hours20-44 hours
Total32-62 hours3-5 hours27-57 hours

2.4 Enterprise Use Cases

ScenarioIndustryTraditional ApproachDynamic ApproachBenefits
High-Value Financial ApplicationsFinancial Services25 individual policies for trading platforms1 policy targeting SecurityLevel="Maximum"96% policy reduction
Healthcare Data AccessHealthcare40 policies for EMR systems2 policies (HIPAA + Geographic attributes)95% reduction
Executive ProtectionAll Industries15 policies for executive apps1 policy for ExecutiveAccess="Required"93% reduction
PCI-DSS ComplianceRetail25 policies for payment applications1 policy for PCIScope="InScope"96% reduction

2.5 Quantifiable Impact

MetricBefore Dynamic CAPsAfter Dynamic CAPsImprovement
Number of Conditional Access Policies150-500+15-3070-95% reduction
Time to Onboard New Application2-4 hours10-15 minutes85-90% faster
Policy Management Effort (hours/month)80-120 hours20-30 hours70-75% reduction
Configuration Errors per Quarter10-151-380-90% reduction
Time to Implement Security Changes1-2 weeks1-2 days80-90% faster

3. How Dynamic CAPs Are Used

3.1 Technical Architecture Deep Dive

When a user attempts to access an application, the following sequence occurs:

  1. Authentication Request: User initiates sign-in to an application
  2. Service Principal Identification: Entra ID identifies the target service principal
  3. Attribute Retrieval: System loads all custom security attributes assigned to the service principal
  4. Baseline Policy Evaluation: Persona-based baseline policies are evaluated first (ALL RESOURCES scope)
  5. Dynamic Policy Matching: Application filters in dynamic CAPs are evaluated against the service principal's attributes
  6. Policy Aggregation: All matching policies (baseline + dynamic) are combined
  7. Control Application: The strictest required controls are applied
  8. Access Decision: Access is granted or blocked based on whether all controls are satisfied
  9. Session Establishment: If granted, session controls from all matching policies are applied
💡 Policy Evaluation Performance

Attribute-based policy evaluation adds negligible latency to authentication (typically <50ms). Attributes are cached and indexed for fast retrieval, and the application filter evaluation is highly optimized.

3.2 Custom Security Attributes as Metadata Tags

Attribute Assignment Mechanisms

MethodUse CaseAdvantagesConsiderations
Azure Portal (Entra Admin Center)Individual application tagging, initial setupVisual interface, easy to learnManual process, not suitable for bulk operations
Microsoft Graph APIAutomated workflows, integration with CMDBProgrammatic control, integration capabilitiesRequires development expertise
PowerShell (Graph SDK)Bulk operations, scripted managementAutomation, reusable scripts, audit trailsRequires PowerShell expertise
Azure CLICommand-line automation, CI/CD pipelinesCross-platform, simple syntaxLimited compared to PowerShell/Graph API

Graph API Query Examples

// 1. Find all apps with specific security level
GET https://graph.microsoft.com/v1.0/servicePrincipals?$filter=customSecurityAttributes/ContosoSecurity/SecurityLevel eq 'Maximum'

// 2. Find apps with multiple attribute conditions
GET https://graph.microsoft.com/v1.0/servicePrincipals?$filter=customSecurityAttributes/ContosoSecurity/SecurityLevel eq 'Enhanced' and customSecurityAttributes/ContosoCompliance/HIPAAScope eq true

// 3. Select specific attributes in response
GET https://graph.microsoft.com/v1.0/servicePrincipals?$select=displayName,customSecurityAttributes

3.3 Application Filter Mechanism

Supported Operators

OperatorDescriptionExample
-eqEquals (exact match)SecurityLevel -eq "Maximum"
-neNot equalsEnvironment -ne "Production"
-inValue in listRegion -in ["US", "EU", "APAC"]
-containsContains substringDepartment -contains "Finance"
-startsWithStarts with stringAppName -startsWith "Contoso"

Complex Filter Examples

// Single attribute match
application.extension_abc123_SecurityLevel -eq "Enhanced"

// Multiple attributes with AND logic
application.extension_abc123_SecurityLevel -eq "Maximum" -and 
application.extension_abc123_ComplianceFramework -eq "HIPAA"

// Multiple attributes with OR logic
application.extension_abc123_DataClassification -eq "PHI" -or 
application.extension_abc123_DataClassification -eq "PII"

// Combining AND/OR
(application.extension_abc123_SecurityLevel -eq "Enhanced" -or 
 application.extension_abc123_SecurityLevel -eq "Maximum") -and
application.extension_abc123_NetworkRequirement -eq "TrustedOnly"

3.4 Implementation Approach 1: Aggregated Controls

Security LevelAuthenticationDeviceNetworkSession Controls
Level 1: StandardMFA RequiredCompliant or Hybrid JoinedAny locationToken lifetime: 12 hours
Level 2: EnhancedPasskeys or PasswordlessCompliant Device RequiredCorporate network or VPNToken lifetime: 4 hours
Level 3: MaximumPhishing-resistant MFACompliant Device RequiredTrusted locations onlyToken lifetime: 1 hour, No downloads

PowerShell: Create Attribute Set and Assign to Applications

Connect-MgGraph -Scopes "CustomSecAttributeDefinition.ReadWrite.All"

# Create attribute set
$attributeSet = @{
    Id = "ContosoSecurity"
    Description = "Contoso security level attributes for dynamic CAPs"
    MaxAttributesPerSet = 25
}
New-MgDirectoryAttributeSet -BodyParameter $attributeSet

# Create SecurityLevel attribute
$attribute = @{
    AttributeSet = "ContosoSecurity"
    Name = "SecurityLevel"
    Type = "String"
    UsePreDefinedValuesOnly = $true
    AllowedValues = @(
        @{ Id = "Standard"; IsActive = $true }
        @{ Id = "Enhanced"; IsActive = $true }
        @{ Id = "Maximum"; IsActive = $true }
    )
}
New-MgDirectoryCustomSecurityAttributeDefinition -BodyParameter $attribute
✅ Best Practice: Start with Aggregated, Evolve to Fine-Grained

Many successful implementations start with the Aggregated Controls approach to gain experience and demonstrate value, then evolve to Fine-Grained Attributes as requirements become more sophisticated.

3.5 Implementation Approach 2: Fine-Grained Attributes

The Fine-Grained Attributes approach treats each security dimension as a separate attribute, allowing applications to have precisely tailored security controls.

Attribute CategoryAttribute NameData TypePossible Values
AuthenticationAuthenticationStrengthStringMFA, Passwordless, PhishingResistant
AllowSMSMFABooleantrue, false
Device RequirementsDeviceComplianceStringRequired, Preferred, NotRequired
AllowBYODBooleantrue, false
NetworkNetworkRequirementStringAny, Corporate, TrustedOnly
BlockHighRiskCountriesBooleantrue, false
Session ControlsTokenLifetimeString1h, 4h, 8h, 12h, 24h
SessionTypeStringStandard, Restricted, Privileged
Data ProtectionAllowDownloadBooleantrue, false
AllowPrintBooleantrue, false
AllowCopyPasteBooleantrue, false

3.6 Approach Comparison and Selection

Decision FactorChoose AggregatedChoose Fine-Grained
Team ExperienceNew to Dynamic CAPsExperienced with Conditional Access
Application PortfolioMostly standard business appsDiverse with unique requirements
Governance ModelCentralized controlDelegated to application owners
Time to ImplementNeed quick wins (2-4 weeks)Can invest time (6-12 weeks)
Compliance NeedsStandard frameworksMultiple complex frameworks

3.7 Integration with Baseline Persona-Based CAPs

🚨 MANDATORY FOUNDATION

Before implementing Dynamic CAPs, you MUST have baseline persona-based Conditional Access policies that cover ALL RESOURCES for all user types. Dynamic CAPs are an enhancement layer, not a replacement.

Policy Layering Architecture

FOUNDATION: Baseline Policies (ALL RESOURCES)
All Users: MFA Required | Guests: MFA + Compliant Device | Admins: Phishing-resistant MFA + Trusted Network
↑ Enhances
ENHANCEMENT: Dynamic CAPs (Specific Applications)
SecurityLevel=Maximum: 1hr token + No downloads | HIPAAScope=True: Session monitoring | PCIScope=True: Trusted locations only

4. What Dynamic CAPs Are Used For

4.1 Enhanced Security Requirements

Token Lifetime Management

Authentication Strength Requirements

4.2 Real-World Scenarios

Scenario 1: Financial Trading Platform

Attribute Assignment: SecurityLevel = "Maximum", DataClassification = "Financial", ComplianceFramework = "SEC"

Resulting Controls: Phishing-resistant MFA, compliant corporate device, trusted network only, 1-hour token lifetime, no downloads/printing/copy-paste.

Scenario 2: Healthcare EHR System

Attribute Assignment: DataClassification = "PHI", ComplianceFramework = "HIPAA", SecurityLevel = "Enhanced"

Resulting Controls: Passwordless authentication, compliant device, 4-hour token lifetime, session monitoring, access logging for audit.

Scenario 3: Executive Email and Calendar

Attribute Assignment: UserClassification = "Executive", SecurityLevel = "Enhanced"

Resulting Controls: Passwordless authentication, compliant device or trusted location, 4-hour token lifetime, mobile access requires managed device.

Scenario 4: Developer Tools (GitHub, Azure DevOps)

Attribute Assignment: ApplicationType = "Development", SecurityLevel = "Standard"

Resulting Controls: MFA required, compliant device preferred (not required), 12-hour token lifetime, access from any location.

4.3 Compliance and Regulatory Use Cases

RegulationRequirementsAttribute DesignCAP Controls
PCI-DSSProtect cardholder data, restrict accessPCIScope = "InScope"Phishing-resistant MFA, trusted network, audit logging
HIPAAProtect PHI, ensure authorized accessDataClassification = "PHI"Strong authentication, compliant device, session monitoring
SOC 2Access controls, monitoring, loggingSOC2Critical = "true"MFA, device compliance, comprehensive logging
GDPRProtect personal data, access controlsDataClassification = "PII"MFA, geographic restrictions, audit trail

5. Where Dynamic CAPs Are Used

5.1 Microsoft Entra ID Environment

5.2 Supported Objects

Service Principals (Applications): Enterprise applications, multi-tenant applications, Azure AD Application Proxy applications, and custom line-of-business applications registered in your tenant.

5.3 Cloud and Hybrid Environments

6. Who Uses and Maintains Dynamic CAPs

6.1 Role-Based Access Control

RolePermissionsResponsibilities
Attribute Definition AdministratorCreate/manage attribute sets and definitionsDesign attribute taxonomy, create attributes, manage lifecycle
Attribute Assignment AdministratorAssign attributes to objectsTag applications, manage assignments, update values
Conditional Access AdministratorCreate/manage CA policiesCreate policies with application filters, manage policy lifecycle
Security AdministratorRead security configurationMonitor policies, review compliance, investigate incidents
Application OwnerRequest attribute assignmentsIdentify security requirements, submit requests, validate controls
⚠️ Important: Global Administrator Limitation

By default, Global Administrators do NOT have permissions to manage Custom Security Attributes. This is by design for enhanced security. They must be explicitly assigned Attribute Administrator roles.

6.2 Responsibilities Matrix (RACI)

ActivitySecurity TeamApp OwnerIT OpsCompliance
Define attribute taxonomyR, ACIC
Create attribute sets/definitionsR, AIII
Assign attributes to applicationsARII
Create Conditional Access policiesR, ACIC
Monitor policy effectivenessR, ACII
Audit and compliance reportingRIIA, R

R = Responsible, A = Accountable, C = Consulted, I = Informed

7. Design Best Practices

7.1 Architecture Principles

  1. Baseline First, Enhancements Second: Always implement persona-based baseline CAPs for ALL RESOURCES before adding dynamic policies.
  2. Attribute Taxonomy Before Implementation: Design your complete attribute taxonomy before creating attributes. Changes later are difficult and require policy updates.
  3. Start Simple, Iterate: Begin with 3-5 core attributes and expand based on real requirements.
  4. Document Everything: Maintain comprehensive documentation of attributes, their meanings, and appropriate use cases.
  5. Principle of Least Privilege: Apply only the security controls necessary for each application's risk profile.
  6. Consistent Naming Conventions: Use clear, standardized naming. Example: CompanyName_Category_AttributeName
  7. Test Before Production: Always use report-only mode first. Analyze impact before enforcing policies.
  8. Monitor and Measure: Establish KPIs to track policy effectiveness, user impact, and security posture.

7.2 Required Baseline Policies

🚨 NON-NEGOTIABLE REQUIREMENT

You MUST implement comprehensive baseline persona-based Conditional Access policies covering ALL RESOURCES for all user types BEFORE implementing Dynamic CAPs.

Policy NameUsersApplicationsControls
BASE-01: All Users MFAAll UsersAll cloud appsRequire MFA
BASE-02: All Users DeviceAll UsersAll cloud appsCompliant OR Hybrid Joined device
BASE-03: Guests EnhancedAll GuestsAll cloud appsMFA AND Compliant device
BASE-04: Admins MaximumDirectory role membersAll cloud appsPhishing-resistant MFA AND Compliant device AND Trusted locations
BASE-05: Block Legacy AuthAll UsersAll cloud appsBlock access (legacy authentication clients)

7.3 Example Attribute Taxonomy

Attribute Set: CompanyName_SecurityLevels — SecurityLevel: Standard, Enhanced, Maximum

Attribute Set: CompanyName_Compliance — DataClassification: Public, Internal, Confidential, PHI, PCI | ComplianceFramework (multi): HIPAA, PCI-DSS, SOC2, GDPR

Attribute Set: CompanyName_AccessControls — NetworkRequirement: Any, Corporate, TrustedOnly | TokenLifetime: 1h, 4h, 8h, 12h

Naming Conventions

ElementFormatExample
Attribute SetCompanyName_CategoryContoso_Security, Contoso_Compliance
Attribute NamePascalCase, no spacesSecurityLevel, DataClassification
Policy NamePREFIX-##: DescriptionDYN-CAP-01: Enhanced Security Level

8. Deployment Best Practices

8.1 Pre-Deployment Checklist

RequirementStatus CheckOwner
Entra ID P1/P2 licenses assignedVerify in license managementIT Operations
Baseline CAPs implemented and testedReview existing policies covering ALL RESOURCESSecurity Team
Break-glass accounts configured and documentedTest emergency accessSecurity Team
Administrator roles assignedConfirm Attribute Administrator rolesIdentity Team
Attribute taxonomy designed and approvedDocumented and reviewed by stakeholdersSecurity Architecture
Monitoring and logging infrastructure readyLog Analytics workspace configuredIT Operations

8.2 Step-by-Step Deployment

Phase 1: Setup (Week 1) — Create Attribute Sets and Definitions

Connect-MgGraph -Scopes "CustomSecAttributeDefinition.ReadWrite.All"

$attributeSets = @(
    @{ Id = "ContosoSecurity"; Description = "Security level attributes" }
    @{ Id = "ContosoCompliance"; Description = "Compliance and regulatory attributes" }
)
foreach ($set in $attributeSets) {
    New-MgDirectoryAttributeSet -Id $set.Id -Description $set.Description -MaxAttributesPerSet 25
}

# Create SecurityLevel attribute
$params = @{
    AttributeSet = "ContosoSecurity"
    Name = "SecurityLevel"
    Type = "String"
    Status = "Available"
    UsePreDefinedValuesOnly = $true
    AllowedValues = @(
        @{ Id = "Standard"; IsActive = $true }
        @{ Id = "Enhanced"; IsActive = $true }
        @{ Id = "Maximum"; IsActive = $true }
    )
}
New-MgDirectoryCustomSecurityAttributeDefinition -BodyParameter $params

Phase 2: Policy Creation in Report-Only Mode (Week 2)

# Create dynamic CAP — always start in report-only!
$policyParams = @{
    DisplayName = "DYN-CAP-01: Enhanced Security Level"
    State = "enabledForReportingButNotEnforced"
    Conditions = @{
        Applications = @{
            ApplicationFilter = @{
                Mode = "include"
                Rule = "application.extension_ContosoSecurity_SecurityLevel -eq 'Enhanced'"
            }
        }
        Users = @{
            IncludeUsers = @("All")
            ExcludeUsers = @("break-glass-account-id")  # Always exclude break-glass!
        }
    }
}
New-MgIdentityConditionalAccessPolicy -BodyParameter $policyParams

Phase 3: Assign Attributes to Pilot Applications (Weeks 3-4)

$appId = "your-application-app-id"
$servicePrincipal = Get-MgServicePrincipal -Filter "appId eq '$appId'"

$attributes = @{
    "ContosoSecurity" = @{
        "@odata.type" = "#Microsoft.DirectoryServices.CustomSecurityAttributeValue"
        "SecurityLevel" = "Enhanced"
    }
}
Update-MgServicePrincipal -ServicePrincipalId $servicePrincipal.Id -CustomSecurityAttributes $attributes

8.3 Break-Glass Account Protection

🚨 CRITICAL: Always Exclude Break-Glass Accounts

Every Conditional Access policy (baseline and dynamic) must exclude break-glass emergency access accounts. Test these accounts regularly to ensure they work.

8.4 Testing Checklist

Test ScenarioExpected ResultStatus
User accesses app with SecurityLevel=EnhancedPasswordless MFA required
User accesses app without attributesOnly baseline policies apply
Admin accesses any appAdmin baseline + dynamic policies apply
Break-glass accountExcluded from all dynamic policies
Mobile device accessAppropriate controls based on attributes

9. Monitoring and Logging

9.1 Essential KQL Queries

Query 1: Failed Sign-Ins Due to Conditional Access

SigninLogs
| where TimeGenerated > ago(24h)
| where ConditionalAccessStatus == "failure"
| summarize Count=count() by AppDisplayName, ConditionalAccessPolicies
| order by Count desc

Query 2: Applications Matched by Dynamic CAPs

SigninLogs
| where TimeGenerated > ago(7d)
| extend DynamicPolicy = parse_json(ConditionalAccessPolicies)
| where DynamicPolicy contains "DYN-CAP"
| summarize UniqueApps=dcount(AppDisplayName) by tostring(DynamicPolicy)

Query 3: Attribute Assignment Changes

AuditLogs
| where TimeGenerated > ago(7d)
| where OperationName contains "Update service principal"
| where TargetResources contains "customSecurityAttributes"
| project TimeGenerated, Identity, AppDisplayName=TargetResources[0].displayName, Result

9.2 Key Performance Indicators

KPITargetHow to Measure
Attribute Coverage>80% of apps have attributes assignedCount apps with attributes / total apps
Policy Count Reduction70-80% fewer policiesCompare policy count before/after
Failed Sign-Ins Rate<2% of total sign-insMonitor blocked sign-ins in logs
Time to Onboard New App<30 minutesTrack from request to attribute assignment

9.3 Critical Alerts

Alert NameConditionAction
Break-glass account usedAny sign-in from break-glass accountsImmediate notification to security team
High CA failure rate>100 failures in 15 minutesPage on-call engineer
Unauthorized attribute changeAttribute modified by non-approved userAlert security team, audit immediately
Policy modificationAny CAP policy created/modified/deletedNotification to security team

10. Technical Reference

10.1 Attribute Limits and Constraints

ResourceLimitNotes
Attribute definitions per tenant500 (active)Deactivated attributes don't count toward limit
Attribute sets per tenant500Hard limit
Attribute name length32 charactersUnicode, case-sensitive
Attribute value length64 charactersUnicode
Predefined values per attribute100More values = more complex management
Attribute values per object50Total across all attributes on single object

10.2 Microsoft Graph API Quick Reference

OperationHTTP MethodEndpoint
List attribute setsGET/directory/attributeSets
Create attribute setPOST/directory/attributeSets
List attribute definitionsGET/directory/customSecurityAttributeDefinitions
Create attribute definitionPOST/directory/customSecurityAttributeDefinitions
Assign attribute to appPATCH/servicePrincipals/{id}
Get app with attributesGET/servicePrincipals/{id}?$select=customSecurityAttributes
Query apps by attributeGET/servicePrincipals?$filter=customSecurityAttributes/Set/Attribute eq 'Value'

10.3 Troubleshooting Guide

IssuePossible CauseResolution
Attribute not visible in policy filterAttribute status is inactiveActivate attribute definition
Policy not matching expected appsFilter syntax errorVerify attribute set ID and syntax in filter
User blocked unexpectedlyMultiple policies combining controlsReview all policies affecting user/app combination
Cannot assign attributeMissing Attribute Assignment Admin roleVerify role assignment at tenant or attribute set scope
Break-glass account blockedNot excluded from policiesAdd to exclusions in ALL policies immediately

10.4 PowerShell Script: Bulk Attribute Assignment from CSV

# CSV format: AppId,SecurityLevel,DataClassification
Connect-MgGraph -Scopes "Application.ReadWrite.All", "CustomSecAttributeAssignment.ReadWrite.All"

$apps = Import-Csv "applications.csv"
foreach ($app in $apps) {
    $sp = Get-MgServicePrincipal -Filter "appId eq '$($app.AppId)'"
    if ($sp) {
        $attributes = @{
            "ContosoSecurity" = @{ "SecurityLevel" = $app.SecurityLevel }
            "ContosoCompliance" = @{ "DataClassification" = $app.DataClassification }
        }
        Update-MgServicePrincipal -ServicePrincipalId $sp.Id -CustomSecurityAttributes $attributes
        Write-Host "Updated: $($sp.DisplayName)"
    } else {
        Write-Warning "App not found: $($app.AppId)"
    }
}

11. Governance and Compliance

11.1 Compliance Framework Mapping

FrameworkRelevant ControlsHow Dynamic CAPs Help
NIST CSFPR.AC-1: Identity management; PR.AC-4: Access permissions managedGranular access controls based on app risk; clear attribute-based authorization
ISO 27001A.9.2.1: User registration; A.9.4.1: Information access restrictionConsistent access control framework; risk-based access restrictions
SOC 2CC6.1: Logical access controls; CC6.6: Managed system activitiesDocumented attribute taxonomy; comprehensive audit logs
PCI-DSSReq 7: Restrict access by business need; Req 8: Strong authenticationPCIScope attribute for cardholder data apps; enhanced authentication for in-scope apps
HIPAA§164.312(a)(1): Access control; §164.312(d): AuthenticationPHI classification attribute; enhanced controls for PHI applications

11.2 Access Reviews Schedule

Review TypeScopeOwnerFrequency
Administrator Role ReviewAll Attribute Administrator role assignmentsIdentity TeamQuarterly
High-Risk App AttributesApps with SecurityLevel=MaximumSecurity TeamQuarterly
Policy Effectiveness ReviewAll dynamic CAPsSecurity ArchitectureQuarterly
Attribute Taxonomy ReviewIs taxonomy still meeting needs?Governance CommitteeQuarterly

12. Conclusion and Recommendations

12.1 Implementation Roadmap

PhaseTimelineKey ActivitiesSuccess Criteria
Phase 0: FoundationMonths 0-3Implement baseline persona CAPs; configure break-glass accounts; design attribute taxonomyBaseline policies protecting all resources; documented taxonomy approved
Phase 1: PilotMonths 3-6Create attribute sets; create 3-5 dynamic CAPs in report-only; assign attributes to 10-20 pilot appsPilot apps successfully tagged; policies working as expected; no unexpected user impact
Phase 2: ProductionMonths 6-12Enable policies; expand to 100-200 applications; train application owners50% of apps with attributes; <2% failed sign-in rate
Phase 3: MaturityMonths 12+Complete portfolio coverage; optimize; implement automation>80% app coverage; 70-80% policy reduction achieved; new app onboarding <30 min

12.2 Critical Success Factors

  1. Executive Sponsorship: Secure leadership support for the initiative
  2. Baseline First: Non-negotiable — implement comprehensive baseline CAPs before dynamic policies
  3. Start Simple: Begin with 3-5 core attributes, expand based on real needs
  4. Clear Taxonomy: Invest time in designing a clear, logical attribute structure
  5. Report-Only Testing: Always test in report-only mode for at least 1-2 weeks
  6. Strong Governance: Establish clear ownership, processes, and approval workflows
  7. Comprehensive Documentation: Document everything — taxonomy, policies, decisions, procedures
  8. Monitor Continuously: Establish KPIs and dashboards, review regularly
✅ You're Ready to Begin

You now have a comprehensive framework for implementing Dynamic Conditional Access Policies with Custom Security Attributes. Start with baseline policies, design a simple taxonomy, pilot with a few applications, and expand based on learnings. The journey from hundreds of policies to a manageable, scalable identity governance framework begins with a single step.

Appendix A: Glossary of Key Terms

TermDefinition
Application FilterA feature in Conditional Access policies that uses expressions to dynamically select applications based on Custom Security Attributes
Attribute SetA logical container that groups related custom security attributes for organization and delegation
Baseline PolicyA Conditional Access policy that applies to ALL RESOURCES for a specific user persona
Break-Glass AccountEmergency access accounts that bypass all Conditional Access policies
Custom Security AttributeBusiness-specific metadata (key-value pairs) that can be assigned to users and applications in Microsoft Entra ID
Dynamic CAPA Conditional Access policy that uses application filters to dynamically target applications based on their Custom Security Attributes
Phishing-Resistant AuthenticationAuthentication methods resistant to phishing attacks (FIDO2 security keys, Windows Hello for Business)
Policy SprawlThe problem of managing too many Conditional Access policies, typically one per application
Report-Only ModeA CAP state where policies are evaluated but not enforced, allowing impact analysis without affecting users
Service PrincipalThe instance of an application in your Entra ID tenant; the object to which Custom Security Attributes are assigned

Appendix B: Reference Links

Microsoft Official Documentation

Tools and Utilities

Appendix C: Pre/Post Deployment Checklists

Pre-Implementation

TaskComplete
Baseline persona-based CAPs implemented for ALL RESOURCES
Break-glass accounts configured and tested
Entra ID P1/P2 licenses verified
Attribute Administrator roles assigned
Attribute taxonomy designed and documented
Stakeholders identified and engaged
Log Analytics workspace configured

Post-Deployment

TaskComplete
Monitoring dashboards created
Alert rules configured
KPIs established and tracking
Application owners trained
Governance committee established
Quarterly review schedule established