Friday, July 11, 2014

PowerShell Script: Add a Trusted Security Token Issuer and Principal Permissions

Intended Audience:Administrator, Architect, and IT Professional

If you read my recent post on how to use PowerShell to remove a Trusted Security Token Issuer and Principal Permissions, you will love this post in which I show you have to add a Trusted Security Token Issuer as well as a App Principal Permission.

Just save the following into a .PS1 file. You just need to provide the app display name, Issuer ID (or leave it blank for a random GUID), SSL certificate location, SharePoint site URL, the scope for which the app's principal should be registered (Site, SiteCollection, or SiteSubscription), and the permission that the application should have (Read, Write, Manage, or FullControl). Again, 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
$appDisplayName = Read-Host "What is your app's display name?"
$issuerID = Read-Host "What is the Issuer ID? Leave blank to auto generate a GUID. Must be unique to the site.”
if ($issuerID -eq "") { $issuerID = [guid]::NewGuid() }
$publicCertPath = Read-Host "Please type in the .CER path location. For example, C:\mycertificate.cer"
$siteUrl = Read-Host "Please type in the SharePoint site URL. For example,”
$site = Get-SPSite $siteUrl
$appScope = Read-Host "What scope should this application have access too? [Site] [SiteCollection] [SiteSubscription]"
$appPerm = Read-Host "What permission should this application have? [Read] [Write] [Manage] [FullControl]"

# Get our full application identifier
$web = Get-SPWeb $siteUrl
$certificate = Get-PfxCertificate $publicCertPath
$realm = Get-SPAuthenticationRealm -ServiceContext $web.Site
$fullAppIdentifier = $issuerId + '@' + $realm

# Add the trusted root authority, security token issuer, register the app principal, and set app permissions
New-SPTrustedRootAuthority -Name $appDisplayName -Certificate $certificate
New-SPTrustedSecurityTokenIssuer -Name $appDisplayName -Certificate $certificate -RegisteredIssuerName $fullAppIdentifier
Register-SPAppPrincipal -NameIdentifier $fullAppIdentifier -Site $web -DisplayName $appDisplayName
$appPrincipal = Get-SPAppPrincipal -NameIdentifier $fullAppIdentifier -Site $site.RootWeb
Set-SPAppPrincipalPermission -Site $site.RootWeb -AppPrincipal $appPrincipal -Scope $appScope -Right $appPerm