Add-ADFS_RelyingPartyTrust.ps1

#Requires -RunAsAdministrator
#Requires -Version 5.0

<#
     .SYNOPSIS
        Create ADFS Relying Party Trust configuration .
    .DESCRIPTION
        Create ADFS Relying Party Trust configuration samples.
 
        Dependencies:
        None.
 
    .NOTES
        Version: 2.0.0.5
        Author: SecureMfa.com
        Creation Date: 15/02/2021
        Purpose/Change: Release
   
    .EXAMPLE
        Add-ADFS_RelyingPartyTrust -RP_WEBSITE_URL 'https://ardswebl01.adatum.labnet/RDWeb/Pages/Default.aspx' -SampleRP RDWeb
 
        This command will create ADFS RelyingPartyTrust configuration for Microsoft RD Web Servers deployment with SSO configuration.
    
#>


Function Add-ADFS_RelyingPartyTrust {
Param
(  
    [Parameter(Mandatory=$false)][string]$RP_WEBSITE_URL = "https://ardswebl01.adatum.labnet/RDWeb/Pages/Default.aspx",
    [Parameter(Mandatory=$false)][string]$RP_Name,
    [Parameter(Mandatory=$false)][ValidateSet('RDWeb','SpringSample','None')][string]$SampleRP='RDWeb',
    [Parameter(Mandatory=$false)][Switch]$Force    
)
    
    #Variables
    if($SampleRP -eq 'RDWeb') {$RP_Name = "SecureMFA_RDWeb"}
    elseif($SampleRP -eq 'SpringSample') {$RP_Name = "SecureMFA_SpringSample"}
    else {if($RP_Name){$RP_Name = "SecureMFA_" + $RP_Name} else {$RP_Name = "SecureMFA_RDWeb"};}
    
    $ADFS_ISSUER = (Get-ADFSEndpoint  | where{$_.Protocol -eq "SAML 2.0/WS-Federation"}).FullUrl.OriginalString
    $ADFS_Identifier = (Get-AdfsProperties).Identifier.AbsoluteUri
    $ADFS_FederationMetadata = (Get-ADFSEndpoint  | where{$_.Protocol -eq "Federation Metadata"}).FullUrl.OriginalString
    $ADFS_TokenSigning_Thumbprint = (Get-AdfsCertificate -CertificateType Token-Signing).Thumbprint
       
    if (!$Force) {
    $message  = "Do you want to overwrite existing ADFS RelyingPartyTrust " + $RP_Name + " ?";            
    $question = 'Please confirm?'
    $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
    $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
    $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))
    
    if(Get-AdfsRelyingPartyTrust -Name $RP_Name) {
        $decision_Validation = $Host.UI.PromptForChoice($message, $question, $choices, 0)
        if ($decision_Validation -eq 1 ) {Write-Host "ADFS RelyingPartyTrust configuration has been cancelled, exiting!" -ForegroundColor Yellow ; break} else {Remove-AdfsRelyingPartyTrust -TargetName $RP_Name}
        }
    }
    else {if(Get-AdfsRelyingPartyTrust -Name $RP_Name) {Remove-AdfsRelyingPartyTrust -TargetName $RP_Name}}
            
    try
    {
        $Error.Clear()
        #Validate if Identifier is not dublicated
        if(Get-ADFSRelyingPartyTrust -Identifier $RP_WEBSITE_URL) {throw "RelyingPartyTrust Identifier exist: $RP_WEBSITE_URL . Please fix the duplicate Identifier issue for RP: " + (Get-ADFSRelyingPartyTrust -Identifier $RP_WEBSITE_URL).Name  + " and try again. " ; break}
                                   
        #Start RP creation
        
#-------
#Default authorization rules
$IssuanceAuthorizationRules=@'
@RuleTemplate = "AllowAllAuthzRule"
 => issue(Type = "http://schemas.microsoft.com/authorization/claims/permit",
Value = "true");
'@


#Stores Issuance Transformation Rules
$IssuanceTransformRules=@'
 @RuleTemplate = "LdapClaims"
 @RuleName = "Active Directory"
c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"]
 => issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"), query = ";userPrincipalName;{0}", param = c.Value);
'@

#-------
                
        if($SampleRP -eq 'RDWeb') {        
        
        #Validate if RDWeb Identifier is not dublicated
        if(Get-ADFSRelyingPartyTrust -Identifier "urn:microsoft:rdweb") {throw "RelyingPartyTrust Identifier exist: 'urn:microsoft:rdweb' . Please fix the duplicate Identifier issue for RP: " + (Get-ADFSRelyingPartyTrust -Identifier "urn:microsoft:rdweb").Name  + " and try again. " ; break}
                
        #Creates Relying Party Trust
        Add-ADFSRelyingPartyTrust -Name $RP_Name `
                          -Enabled $true `
                          -Notes "This is a trust for $RP_WEBSITE_URL" `
                          -WSFedEndpoint $RP_WEBSITE_URL `
                          -Identifier $RP_WEBSITE_URL,"urn:microsoft:rdweb" `
                          -IssuanceTransformRules $IssuanceTransformRules `
                          -IssuanceAuthorizationRules $IssuanceAuthorizationRules        
        }
        elseif($SampleRP -eq 'SpringSample') {
        
        #Validate if SpringSample Identifier is not dublicated
        if(Get-ADFSRelyingPartyTrust -Identifier "com:securemfa:domain:springsample:test:sp") {throw "RelyingPartyTrust Identifier exist: 'com:securemfa:domain:springsample:test:sp' . Please fix the duplicate Identifier issue for RP: " + (Get-ADFSRelyingPartyTrust -Identifier "com:securemfa:domain:springsample:test:sp").Name  + " and try again. " ; break}
        
        $ClaimSet1 = New-ADFSClaimRuleSet -ClaimRule '@RuleTemplate = "LdapClaims" @RuleName = "Email" c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"] => issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"), query = ";mail,displayName;{0}", param = c.Value);'
        $ClaimSet2 = New-ADFSClaimRuleSet -ClaimRule '@RuleName = "Transform Email to NameID" c:[Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"] => 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:1.1:nameid-format:emailAddress", Properties["http://schemas.xmlsoap.org/ws/2005/05/identity/claimproperties/spnamequalifier"] = "springsample-saml");'
        $ClaimRulesAll = New-AdfsClaimRuleSet -ClaimRule  ($ClaimSet1.ClaimRules + $ClaimSet2.ClaimRules)

        #SAMLAssertionConsumer
        $samlEndpoint1 = New-ADFSSamlEndpoint -Protocol 'SAMLAssertionConsumer' -Uri $RP_WEBSITE_URL -Binding 'POST' -IsDefault $true -Index 0
        #SAMLLogout
        $xRP_WEBSITE_URL = $RP_WEBSITE_URL;
        if ($xRP_WEBSITE_URL -notmatch '/$') {$xRP_WEBSITE_URL += '/'}
        $SAMLLogoutURL = $xRP_WEBSITE_URL + "saml/sp/logout"
        $samlEndpoint2 = New-ADFSSamlEndpoint -Protocol 'SAMLLogout' -Uri $SAMLLogoutURL -Binding 'POST'
                
        #Creates Relying Party Trust
        Add-ADFSRelyingPartyTrust -Name $RP_Name `
                          -Enabled $true `
                          -Notes "This is a trust for $RP_WEBSITE_URL" `
                          -SamlEndpoint @($samlEndpoint1,$samlEndpoint2) `
                          -Identifier "com:securemfa:domain:springsample:test:sp" `
                          -IssuanceTransformRules $IssuanceTransformRules `
                          -IssuanceAuthorizationRules $IssuanceAuthorizationRules  
        
        #Apply Claim rules
        Set-AdfsRelyingPartyTrust -TargetName $RP_Name -IssuanceTransformRules $ClaimRulesAll.ClaimRulesString      
        }
        else 
        {        
        Add-ADFSRelyingPartyTrust -Name $RP_Name `
                          -Enabled $true `
                          -Notes "This is a trust for $RP_WEBSITE_URL" `
                          -WSFedEndpoint $RP_WEBSITE_URL `
                          -Identifier $RP_WEBSITE_URL `
                          -IssuanceTransformRules $IssuanceTransformRules `
                          -IssuanceAuthorizationRules $IssuanceAuthorizationRules
        }

        Set-AdfsRelyingPartyTrust -TargetName $RP_Name -AccessControlPolicyName "Permit everyone and require MFA"

        # Complete
        write-host "ADFS RelyingPartyTrust $RP_Name has been configured for: $RP_WEBSITE_URL" -ForegroundColor Green
        write-host "ADFS Issuer: $ADFS_ISSUER" -ForegroundColor Cyan
        write-host "ADFS Identifier: $ADFS_Identifier" -ForegroundColor Cyan
        write-host "ADFS Federation Metadata Endpoint: $ADFS_FederationMetadata" -ForegroundColor Cyan        
        write-host "ADFS TokenSigning Thumbprint: $ADFS_TokenSigning_Thumbprint" -ForegroundColor Cyan
        
    }
    catch
    {
        Write-Host "$($MyInvocation.InvocationName): $_" -ForegroundColor red
    }    


}