npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
Overview
Identity federation enables users authenticated by one identity provider to access resources managed by another without maintaining separate credentials. This skill covers establishing SAML 2.0 federation between an organization's on-premises Active Directory (via AD FS or third-party IdP) and Microsoft Entra ID (formerly Azure AD), as well as configuring federated SSO for third-party SaaS applications. Federation eliminates password synchronization concerns and keeps authentication authority on-premises while extending SSO to cloud resources.
When to Use
- When deploying or configuring building identity federation with saml azure ad capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation
Prerequisites
- On-premises Active Directory domain
- AD FS 2019+ or third-party SAML IdP (Okta, Ping, etc.)
- Microsoft Entra ID tenant (P1 or P2 license recommended)
- Azure AD Connect (if using hybrid identity with password hash sync as backup)
- Public TLS certificate for federation endpoint
- DNS records for federation service name
Core Concepts
Federation Models
| Model | Authentication Authority | Use Case |
|---|---|---|
| Federated (AD FS) | On-premises AD FS | Regulatory requirement to keep auth on-prem |
| Managed (PHS) | Azure AD with password hash sync | Simplest cloud auth, AD FS not needed |
| Managed (PTA) | On-premises via pass-through agent | Cloud auth validated against on-prem AD |
| Third-Party Federation | External IdP (Okta, Ping) | Multi-IdP environment |
SAML Federation Architecture
User → Cloud App (SP)
│
└── Redirect to Azure AD
│
├── Azure AD checks federated domain
│
└── Redirect to on-premises AD FS
│
├── AD FS authenticates against Active Directory
│
├── AD FS issues SAML token
│
└── Token posted back to Azure AD
│
├── Azure AD validates federation trust
│
├── Azure AD issues its own token
│
└── User receives access token for cloud appFederation Trust Components
| Component | Description |
|---|---|
| Token-Signing Certificate | X.509 certificate used by IdP to sign SAML assertions |
| Federation Metadata | XML document describing IdP endpoints and capabilities |
| Relying Party Trust | Configuration in AD FS for each SP (Azure AD) |
| Claims Rules | Transform AD attributes into SAML claims |
| Issuer URI | Unique identifier for the IdP (entity ID) |
Workflow
Step 1: Prepare AD FS Infrastructure
# Install AD FS role
Install-WindowsFeature ADFS-Federation -IncludeManagementTools
# Configure AD FS farm
Install-AdfsFarm `
-CertificateThumbprint $certThumbprint `
-FederationServiceDisplayName "Corp Federation Service" `
-FederationServiceName "fs.corp.example.com" `
-ServiceAccountCredential $gmsaCredential
# Verify AD FS is operational
Get-AdfsProperties | Select-Object HostName, Identifier, FederationPassiveAddressStep 2: Configure Azure AD Federated Domain
# Install Microsoft Graph PowerShell module
Install-Module Microsoft.Graph -Scope CurrentUser
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Domain.ReadWrite.All"
# Convert managed domain to federated
# Using AD FS federation metadata URL
$domainId = "corp.example.com"
$federationConfig = @{
issuerUri = "http://fs.corp.example.com/adfs/services/trust"
metadataExchangeUri = "https://fs.corp.example.com/adfs/services/trust/mex"
passiveSignInUri = "https://fs.corp.example.com/adfs/ls/"
signOutUri = "https://fs.corp.example.com/adfs/ls/?wa=wsignout1.0"
signingCertificate = $base64Cert
preferredAuthenticationProtocol = "saml"
}
# Apply federation settings to domain
New-MgDomainFederationConfiguration -DomainId $domainId -BodyParameter $federationConfigStep 3: Configure AD FS Claims Rules
# Add Relying Party Trust for Azure AD
Add-AdfsRelyingPartyTrust `
-Name "Microsoft Office 365 Identity Platform" `
-MetadataUrl "https://nexus.microsoftonline-p.com/federationmetadata/2007-06/federationmetadata.xml"
# Configure claim rules
$rules = @"
@RuleTemplate = "LdapClaims"
@RuleName = "Extract AD Attributes"
c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname",
Issuer == "AD AUTHORITY"]
=> issue(store = "Active Directory",
types = ("http://schemas.xmlsoap.org/claims/UPN",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"),
query = ";userPrincipalName,mail,givenName,sn;{0}",
param = c.Value);
@RuleTemplate = "PassThroughClaims"
@RuleName = "Pass Through UPN as NameID"
c:[Type == "http://schemas.xmlsoap.org/claims/UPN"]
=> issue(Type = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
Issuer = c.Issuer, OriginalIssuer = c.OriginalIssuer,
Value = c.Value,
ValueType = c.ValueType,
Properties["http://schemas.xmlsoap.org/ws/2005/05/identity/claimproperties/format"]
= "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
"@
Set-AdfsRelyingPartyTrust `
-TargetName "Microsoft Office 365 Identity Platform" `
-IssuanceTransformRules $rulesStep 4: Configure Third-Party SaaS Federation
For each SaaS application that supports SAML SSO via Azure AD:
- Navigate to Microsoft Entra Admin Center > Enterprise Applications
- Add the application from the gallery (or create custom SAML)
- Configure Single Sign-On > SAML:
- Identifier (Entity ID): Application's entity ID
- Reply URL (ACS): Application's assertion consumer service URL
- Sign-on URL: Application's login URL
- Map user attributes/claims:
- NameID: user.userprincipalname (email format)
- Additional claims as required by the application
- Download the Federation Metadata XML or certificate
- Configure the SaaS app with Azure AD's federation details
Step 5: Certificate Lifecycle Management
AD FS token-signing certificates expire and must be renewed:
# Check current certificate expiration
Get-AdfsCertificate -CertificateType Token-Signing | Select-Object Thumbprint, NotAfter
# AD FS supports auto-rollover (enabled by default)
Get-AdfsProperties | Select-Object AutoCertificateRollover
# If manual rotation is needed:
# 1. Add new certificate as secondary
Set-AdfsCertificate -CertificateType Token-Signing -Thumbprint $newThumbprint -IsPrimary $false
# 2. Update Azure AD with new certificate
# 3. Promote to primary
Set-AdfsCertificate -CertificateType Token-Signing -Thumbprint $newThumbprint -IsPrimary $true
# 4. Remove old certificate
Remove-AdfsCertificate -CertificateType Token-Signing -Thumbprint $oldThumbprintValidation Checklist
- AD FS farm operational with valid TLS and token-signing certificates
- Azure AD domain configured as federated with correct metadata
- Claims rules properly transform AD attributes to SAML assertions
- Test user can authenticate through federation flow end-to-end
- MFA enforced at AD FS or Azure AD conditional access level
- Certificate auto-rollover enabled or manual rotation scheduled
- Federation metadata endpoint publicly accessible
- Smart lockout configured to prevent brute force
- Extranet lockout policies configured on AD FS
- Monitoring configured for AD FS health and certificate expiry
- Disaster recovery: managed authentication fallback documented
References
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 3
api-reference.md1.6 KB
API Reference: SAML Azure AD Federation
Federation Metadata URL
https://login.microsoftonline.com/{tenant-id}/federationmetadata/2007-06/federationmetadata.xmlSAML 2.0 Endpoints
| Endpoint | URL |
|---|---|
| SSO (POST) | https://login.microsoftonline.com/{tenant}/saml2 |
| SSO (Redirect) | https://login.microsoftonline.com/{tenant}/saml2 |
| Logout | https://login.microsoftonline.com/{tenant}/saml2 |
SP Metadata Required Fields
| Field | Description |
|---|---|
entityID |
SP unique identifier |
AssertionConsumerService |
ACS URL (POST binding) |
NameIDFormat |
emailAddress or persistent |
SingleLogoutService |
SLO URL (optional) |
XML Namespaces
ns = {
"md": "urn:oasis:names:tc:SAML:2.0:metadata",
"ds": "http://www.w3.org/2000/09/xmldsig#",
"saml": "urn:oasis:names:tc:SAML:2.0:assertion",
}SAML Bindings
| Binding | URI |
|---|---|
| HTTP-POST | urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST |
| HTTP-Redirect | urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect |
| SOAP | urn:oasis:names:tc:SAML:2.0:bindings:SOAP |
Azure AD Graph API (App Registration)
POST https://graph.microsoft.com/v1.0/servicePrincipals
Authorization: Bearer TOKEN
{
"appId": "app-id",
"preferredSingleSignOnMode": "saml",
"loginUrl": "https://app.example.com/login"
}Validation Checks
| Check | Severity |
|---|---|
| HTTPS on ACS URL | High |
| Certificate present | Critical |
| HTTP-POST binding available | Medium |
| NameID format configured | Medium |
standards.md1.7 KB
Identity Federation with SAML Azure AD - Standards Reference
Federation Protocols
SAML 2.0 (OASIS)
- Security Assertion Markup Language version 2.0
- XML-based framework for exchanging authentication/authorization data
- Profiles: Web Browser SSO, Enhanced Client or Proxy, Single Logout
- Bindings: HTTP Redirect, HTTP POST, HTTP Artifact, SOAP
WS-Federation (OASIS)
- Web Services Federation Language
- Used by AD FS for passive federation (browser-based)
- Token types: SAML 1.1, SAML 2.0
OpenID Connect
- Built on OAuth 2.0
- JSON/REST-based (vs. SAML XML)
- Used by Azure AD as primary protocol for modern applications
- JWT tokens instead of SAML assertions
Microsoft Entra ID Federation Requirements
Supported Federation Protocols
| Protocol | Use Case | Token Format |
|---|---|---|
| SAML 2.0 | Enterprise SSO, third-party apps | SAML assertion (XML) |
| WS-Federation | Legacy applications, AD FS | SAML token |
| OpenID Connect | Modern web/mobile apps | JWT |
Domain Federation Requirements
- Domain must be verified in Azure AD
- Only one federation configuration per domain
- Password hash sync recommended as backup
- Azure AD Connect for hybrid identity sync
Compliance Mapping
NIST SP 800-63C - Federation and Assertions
- FAL1: Bearer assertion, direct presentation
- FAL2: Bearer assertion with additional security
- FAL3: Holder-of-key assertion
FedRAMP
- IA-2: Identification and Authentication
- IA-5: Authenticator Management
- IA-8: Identification and Authentication (Non-Organizational Users)
- Federation required for cross-organization access
ISO 27001:2022
- A.5.16: Identity management
- A.5.17: Authentication information
- A.8.5: Secure authentication
workflows.md4.3 KB
Identity Federation with SAML Azure AD - Workflows
Federation Setup Workflow
Phase 1: PREREQUISITES
├── Verify domain ownership in Azure AD
├── Install and configure Azure AD Connect for user sync
├── Deploy AD FS farm (if using on-premises federation)
├── Obtain public TLS certificate for federation endpoint
└── Configure DNS for federation service name
Phase 2: FEDERATION CONFIGURATION
├── Configure AD FS relying party trust for Azure AD
├── Set up claims issuance rules (UPN, ImmutableID)
├── Convert Azure AD domain from managed to federated
├── Verify federation with Test-MgDomainFederationConfiguration
└── Test user sign-in through federation flow
Phase 3: APPLICATION SSO
├── Add SaaS applications to Azure AD enterprise apps
├── Configure SAML SSO for each application
├── Map user attributes and claims
├── Test SSO for each application
└── Assign users/groups to applications
Phase 4: SECURITY HARDENING
├── Enable conditional access policies
├── Configure MFA at AD FS or Azure AD level
├── Enable smart lockout and extranet lockout
├── Set up certificate auto-rollover
└── Forward AD FS audit logs to SIEMSAML Authentication Flow (Federated Domain)
User accesses cloud application
│
├── Application redirects to Azure AD
│ (Azure AD acts as IdP for the application)
│
├── Azure AD identifies user's domain as federated
│
├── Azure AD redirects user to on-premises AD FS
│ (AD FS is the IdP for the federated domain)
│
├── AD FS authenticates user against Active Directory:
│ ├── Kerberos (if on corporate network)
│ ├── Forms-based authentication (if external)
│ └── MFA challenge (if configured)
│
├── AD FS issues SAML assertion with claims:
│ ├── UPN (user principal name)
│ ├── ImmutableID (objectGUID base64-encoded)
│ ├── Email, display name, groups
│ └── Signed with token-signing certificate
│
├── SAML assertion posted to Azure AD
│
├── Azure AD validates assertion:
│ ├── Verify signature against known AD FS certificate
│ ├── Match ImmutableID to synced user
│ ├── Apply conditional access policies
│ └── Issue Azure AD token for the application
│
└── User accesses the cloud applicationFailover Workflow (AD FS Outage)
AD FS becomes unavailable
│
├── Users cannot authenticate through federation
│
├── OPTION 1: Staged Rollout to Managed Authentication
│ ├── Enable password hash sync as backup (should already be active)
│ ├── Use Azure AD staged rollout to move groups to managed auth
│ └── Users authenticate directly with Azure AD (password hash)
│
├── OPTION 2: Convert Domain to Managed
│ ├── Run: Convert-MgDomainToManaged (emergency procedure)
│ ├── All users switch to Azure AD authentication
│ └── Requires password hash sync to be active
│
└── After AD FS restored:
├── Re-establish federation trust
├── Convert domain back to federated
└── Verify authentication flowCertificate Rotation Workflow
AD FS token-signing certificate approaching expiry
│
├── Auto-Rollover Enabled (recommended):
│ ├── AD FS generates new certificate 20 days before expiry
│ ├── New cert is added as secondary
│ ├── Azure AD automatically picks up via metadata refresh
│ ├── New cert promoted to primary at expiry
│ └── Old cert removed after grace period
│
└── Manual Rotation:
├── Generate new signing certificate in AD FS
├── Add as secondary: Set-AdfsCertificate ... -IsPrimary $false
├── Update Azure AD: Update-MgDomainFederationConfiguration
├── Wait for replication (allow 24-48 hours)
├── Promote to primary: Set-AdfsCertificate ... -IsPrimary $true
└── Remove old certificateScripts 2
agent.py4.4 KB
#!/usr/bin/env python3
"""SAML Azure AD Federation Agent - Configures and validates SAML SSO with Azure AD."""
import json
import logging
import argparse
import xml.etree.ElementTree as ET
from datetime import datetime
import requests
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
def fetch_federation_metadata(tenant_id):
"""Fetch Azure AD SAML federation metadata."""
url = f"https://login.microsoftonline.com/{tenant_id}/federationmetadata/2007-06/federationmetadata.xml"
resp = requests.get(url, timeout=15)
resp.raise_for_status()
logger.info("Fetched federation metadata for tenant %s", tenant_id)
return resp.text
def parse_metadata(xml_text):
"""Parse SAML federation metadata XML."""
ns = {"md": "urn:oasis:names:tc:SAML:2.0:metadata", "ds": "http://www.w3.org/2000/09/xmldsig#"}
root = ET.fromstring(xml_text)
idp_desc = root.find(".//md:IDPSSODescriptor", ns)
sso_services = []
if idp_desc is not None:
for sso in idp_desc.findall("md:SingleSignOnService", ns):
sso_services.append({"binding": sso.get("Binding"), "location": sso.get("Location")})
certs = []
for cert_elem in root.findall(".//ds:X509Certificate", ns):
if cert_elem.text:
certs.append(cert_elem.text.strip()[:100] + "...")
entity_id = root.get("entityID", "")
return {"entity_id": entity_id, "sso_services": sso_services, "certificates": certs}
def generate_sp_metadata(entity_id, acs_url, slo_url=None):
"""Generate Service Provider SAML metadata."""
metadata = {
"entityID": entity_id,
"assertionConsumerService": {"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST", "location": acs_url},
"nameIDFormat": "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress",
}
if slo_url:
metadata["singleLogoutService"] = {"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect", "location": slo_url}
return metadata
def validate_configuration(idp_metadata, sp_config):
"""Validate SAML federation configuration."""
findings = []
if not idp_metadata.get("sso_services"):
findings.append({"issue": "No SSO services in IdP metadata", "severity": "critical"})
if not idp_metadata.get("certificates"):
findings.append({"issue": "No signing certificates in metadata", "severity": "critical"})
if not sp_config.get("assertionConsumerService", {}).get("location", "").startswith("https://"):
findings.append({"issue": "ACS URL not using HTTPS", "severity": "high"})
http_redirect = any("HTTP-Redirect" in s.get("binding", "") for s in idp_metadata.get("sso_services", []))
http_post = any("HTTP-POST" in s.get("binding", "") for s in idp_metadata.get("sso_services", []))
if not http_post:
findings.append({"issue": "HTTP-POST binding not available", "severity": "medium"})
return {"valid": len([f for f in findings if f["severity"] == "critical"]) == 0, "findings": findings}
def generate_report(idp_metadata, sp_config, validation):
"""Generate SAML federation report."""
report = {
"timestamp": datetime.utcnow().isoformat(),
"idp_metadata": idp_metadata,
"sp_configuration": sp_config,
"validation": validation,
}
status = "VALID" if validation["valid"] else "INVALID"
print(f"SAML REPORT: {status}, {len(validation['findings'])} findings")
return report
def main():
parser = argparse.ArgumentParser(description="SAML Azure AD Federation Agent")
parser.add_argument("--tenant-id", required=True, help="Azure AD tenant ID")
parser.add_argument("--sp-entity-id", required=True, help="Service Provider entity ID")
parser.add_argument("--acs-url", required=True, help="Assertion Consumer Service URL")
parser.add_argument("--slo-url", help="Single Logout URL")
parser.add_argument("--output", default="saml_report.json")
args = parser.parse_args()
xml_text = fetch_federation_metadata(args.tenant_id)
idp_metadata = parse_metadata(xml_text)
sp_config = generate_sp_metadata(args.sp_entity_id, args.acs_url, args.slo_url)
validation = validate_configuration(idp_metadata, sp_config)
report = generate_report(idp_metadata, sp_config, validation)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
logger.info("Report saved to %s", args.output)
if __name__ == "__main__":
main()
process.py8.2 KB
#!/usr/bin/env python3
"""
Azure AD Federation Configuration Auditor
Validates federation configuration between on-premises AD FS and Azure AD,
checks certificate health, and monitors federation authentication events.
Requirements:
pip install msal requests cryptography
"""
import json
import sys
from datetime import datetime, timezone
try:
import requests
import msal
from cryptography import x509
except ImportError:
print("[ERROR] Required: pip install msal requests cryptography")
sys.exit(1)
class FederationAuditor:
"""Audit Azure AD federation configuration and health."""
def __init__(self, tenant_id, client_id, client_secret):
self.tenant_id = tenant_id
self.token = self._get_token(tenant_id, client_id, client_secret)
def _get_token(self, tenant_id, client_id, client_secret):
app = msal.ConfidentialClientApplication(
client_id,
authority=f"https://login.microsoftonline.com/{tenant_id}",
client_credential=client_secret,
)
result = app.acquire_token_for_client(
scopes=["https://graph.microsoft.com/.default"]
)
if "access_token" in result:
return result["access_token"]
raise Exception(f"Auth failed: {result.get('error_description')}")
def _graph_get(self, endpoint):
headers = {"Authorization": f"Bearer {self.token}"}
resp = requests.get(
f"https://graph.microsoft.com/v1.0{endpoint}",
headers=headers,
)
resp.raise_for_status()
return resp.json()
def get_domains(self):
"""List all domains and their authentication type."""
result = self._graph_get("/domains")
domains = []
for domain in result.get("value", []):
domains.append({
"id": domain["id"],
"isVerified": domain.get("isVerified", False),
"authenticationType": domain.get("authenticationType", "Unknown"),
"isDefault": domain.get("isDefault", False),
"isRoot": domain.get("isRoot", False),
})
return domains
def get_federation_config(self, domain_id):
"""Get federation configuration for a specific domain."""
try:
result = self._graph_get(
f"/domains/{domain_id}/federationConfiguration"
)
configs = result.get("value", [])
return configs[0] if configs else None
except requests.HTTPError as e:
if e.response.status_code == 404:
return None
raise
def validate_adfs_metadata(self, metadata_url):
"""Fetch and validate AD FS federation metadata endpoint."""
try:
resp = requests.get(metadata_url, timeout=15)
resp.raise_for_status()
from lxml import etree
root = etree.fromstring(resp.content)
ns = {"md": "urn:oasis:names:tc:SAML:2.0:metadata"}
entity_id = root.get("entityID")
certs = root.findall(
".//md:IDPSSODescriptor/md:KeyDescriptor/ds:KeyInfo"
"/ds:X509Data/ds:X509Certificate",
{**ns, "ds": "http://www.w3.org/2000/09/xmldsig#"},
)
return {
"reachable": True,
"entity_id": entity_id,
"certificate_count": len(certs),
"metadata_size": len(resp.content),
}
except requests.RequestException as e:
return {"reachable": False, "error": str(e)}
except Exception as e:
return {"reachable": True, "parse_error": str(e)}
def check_certificate_expiry(self, cert_base64):
"""Check federation signing certificate expiration."""
try:
import base64
cert_der = base64.b64decode(cert_base64)
cert = x509.load_der_x509_certificate(cert_der)
now = datetime.now(timezone.utc)
days_left = (cert.not_valid_after_utc - now).days
return {
"subject": cert.subject.rfc4514_string(),
"not_after": cert.not_valid_after_utc.isoformat(),
"days_until_expiry": days_left,
"is_expired": days_left < 0,
"needs_renewal": days_left < 30,
}
except Exception as e:
return {"error": str(e)}
def get_signin_logs(self, federated_domain, top=50):
"""Get recent sign-in logs for federated users."""
try:
result = self._graph_get(
f"/auditLogs/signIns?"
f"$filter=userPrincipalName endswith '{federated_domain}'"
f"&$top={top}&$orderby=createdDateTime desc"
)
logs = []
for log in result.get("value", []):
logs.append({
"user": log.get("userPrincipalName"),
"createdDateTime": log.get("createdDateTime"),
"status": log.get("status", {}).get("errorCode", 0),
"statusDetail": log.get("status", {}).get("failureReason", "Success"),
"appDisplayName": log.get("appDisplayName"),
"authenticationProtocol": log.get("authenticationProtocol"),
"ipAddress": log.get("ipAddress"),
})
return logs
except requests.HTTPError:
return []
def generate_federation_audit_report(self):
"""Generate comprehensive federation health report."""
domains = self.get_domains()
federated_domains = [d for d in domains if d["authenticationType"] == "Federated"]
report = {
"report_title": "Azure AD Federation Audit Report",
"tenant_id": self.tenant_id,
"generated_at": datetime.now(timezone.utc).isoformat(),
"total_domains": len(domains),
"federated_domains": len(federated_domains),
"domain_details": [],
"findings": [],
}
for domain in federated_domains:
domain_id = domain["id"]
fed_config = self.get_federation_config(domain_id)
domain_detail = {
"domain": domain_id,
"is_verified": domain["isVerified"],
"federation_config": fed_config is not None,
}
if fed_config:
issuer = fed_config.get("issuerUri", "")
sign_in_url = fed_config.get("passiveSignInUri", "")
domain_detail["issuer_uri"] = issuer
domain_detail["sign_in_url"] = sign_in_url
signing_cert = fed_config.get("signingCertificate", "")
if signing_cert:
cert_health = self.check_certificate_expiry(signing_cert)
domain_detail["certificate_health"] = cert_health
if cert_health.get("is_expired"):
report["findings"].append({
"severity": "Critical",
"domain": domain_id,
"finding": "Federation signing certificate is EXPIRED",
"action": "Immediately rotate certificate in AD FS and update Azure AD",
})
elif cert_health.get("needs_renewal"):
report["findings"].append({
"severity": "High",
"domain": domain_id,
"finding": f"Federation certificate expires in {cert_health['days_until_expiry']} days",
"action": "Schedule certificate rotation before expiry",
})
report["domain_details"].append(domain_detail)
return report
if __name__ == "__main__":
print("=" * 60)
print("Azure AD Federation Configuration Auditor")
print("=" * 60)
print()
print("Usage:")
print(" auditor = FederationAuditor(tenant_id, client_id, secret)")
print(" report = auditor.generate_federation_audit_report()")
print(" print(json.dumps(report, indent=2))")
print()
print("Required Microsoft Graph permissions:")
print(" - Domain.Read.All")
print(" - AuditLog.Read.All")
print(" - Directory.Read.All")