Friday, July 11, 2014

PowerShell Script: Remove Trusted Security Token Issuer and Principal Permissions

Intended Audience:
Administrator, Architect, and IT Professional

I recently wrote a PowerShell script that can be used to easily remove a Trusted Security Token Issuer as well as any App Principal Permission that has been setup for the SharePoint 2013 on-premise (AKA Provider-Hosted) App. Just save the following into a .PS1 file. You just need to provide the SharePoint site URL, app name, and the scope for which the app's principal was originally registered (Site, SiteCollection, or SiteSubscription). It is that easy.

if((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
    Add-PsSnapin Microsoft.SharePoint.PowerShell

# Stop if there is a problem with this cmdlet
$ErrorActionPreference = "Stop"

# Set our required variables
$siteUrl = Read-Host "Please type in the SharePoint site URL. For example,”
$site = Get-SPSite $siteUrl
Write-Host ""
Write-Host "SharePoint Apps:"
Get-SPTrustedSecurityTokenIssuer | select Name | fl
$issuerID = Read-Host "What is the app's name?"
$realm = Get-SPAuthenticationRealm
$fullIssuerID = $issuerID + '@' + $realm
$tokenIssuer = Get-SPTrustedSecurityTokenIssuer | Where-Object { $_.RegisteredIssuerName -eq $issuerID }
$appScope = Read-Host "What is the app's registered scope? [Site] [SiteCollection] [SiteSubscription]"
$appPrincipal = Get-SPAppPrincipal -NameIdentifier $fullIssuerID -Site $site.RootWeb

#Remove the security token issuer and the app principal permission
Remove-SPTrustedSecurityTokenIssuer -Identity $issuerID -Confirm
Remove-SPAppPrincipalPermission -AppPrincipal $appPrincipal -Site $site.RootWeb -scope $appScope -Confirm

# Show confirmation that the issuer has been removed
Get-SPTrustedSecurityTokenIssuer | select Name,RegisteredIssuerName | fl