
Building Identity Federation With Saml Azure Ad
- 139 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with ai & agent building tasks.
About
building-identity-federation-with-saml-azure-ad is a Claude Code skill in the AI & Agent Building category.
- building-identity-federation-with-saml-azure-ad
- AI & Agent Building
- AI-coding skill
Building Identity Federation With Saml Azure Ad by the numbers
- 139 all-time installs (skills.sh)
- +7 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #3,496 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill building-identity-federation-with-saml-azure-adAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 139 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Building Identity Federation with SAML Azure AD
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:
1. Navigate to Microsoft Entra Admin Center > Enterprise Applications 2. Add the application from the gallery (or create custom SAML) 3. 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
4. Map user attributes/claims:
- NameID: user.userprincipalname (email format)
- Additional claims as required by the application
5. Download the Federation Metadata XML or certificate 6. 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
Identity Federation Implementation Template
Federation Details
| Setting | Value |
|---|---|
| Azure AD Tenant ID | |
| Federated Domain | |
| AD FS Farm Name | |
| AD FS Service URL | https://fs.___/adfs/ls/ |
| Federation Protocol | SAML 2.0 / WS-Federation |
| Backup Auth | Password Hash Sync / Pass-Through Auth |
AD FS Configuration
| Setting | Value |
|---|---|
| AD FS Version | |
| Service Account | gMSA recommended |
| Token-Signing Cert Expiry | |
| Auto-Rollover Enabled | Yes / No |
| WAP Deployed | Yes / No |
Claims Rules
| Rule Name | Source Attribute | Claim Type | Description |
|---|---|---|---|
| UPN | userPrincipalName | NameID | Primary identifier |
| ImmutableID | objectGUID (base64) | ImmutableID | Azure AD anchor |
| emailaddress | User email |
Validation Results
| Test | Status | Notes |
|---|---|---|
| AD FS metadata reachable | Pass/Fail | |
| Token-signing certificate valid | Pass/Fail | |
| Domain federation configured in Azure AD | Pass/Fail | |
| SP-initiated SSO flow | Pass/Fail | |
| IdP-initiated SSO flow | Pass/Fail | |
| MFA enforcement | Pass/Fail | |
| Smart lockout configured | Pass/Fail | |
| Sign-in logs showing federated auth | Pass/Fail |
Disaster Recovery
- [ ] Password hash sync enabled as backup
- [ ] Staged rollout to managed auth tested
- [ ] Break-glass cloud-only admin accounts created
- [ ] AD FS farm disaster recovery plan documented
- [ ] Secondary AD FS farm in DR site (if applicable)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
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 |
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
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 certificate#!/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()
#!/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")