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: 1.0.1.3
        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 = "RDWeb",
    [Parameter(Mandatory=$false)][ValidateSet('RDWeb','None')][string]$SampleRP='RDWeb',
    [Parameter(Mandatory=$false)][Switch]$Force    
)
    
    #Variables
    $RP_Name = "SecureMFA_" + $RP_Name;
    $ADFS_ISSUER = (Get-ADFSEndpoint  | where{$_.Protocol -eq "SAML 2.0/WS-Federation"}).FullUrl.OriginalString
    $ADFS_Identifier = (Get-AdfsProperties).Identifier.AbsoluteUri
    $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        
        }
        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 TokenSigning Thumbprint: $ADFS_TokenSigning_Thumbprint" -ForegroundColor Cyan
        
    }
    catch
    {
        Write-Host "$($MyInvocation.InvocationName): $_" -ForegroundColor red
    }    


}