Viser opslag med etiketten SharePoint. Vis alle opslag
Viser opslag med etiketten SharePoint. Vis alle opslag

lørdag den 23. februar 2013

SharePoint/CRM/Exchange and other Claims based websites with Social Sign in

The last week I have been working on a project, regarding combining Claims based authentication and login using Social Providers. In the cloud control panel that I normal work on, I have implemented support for signing in using Office 365, Azure AD, pass-through using Azure ACS, and the mandatory Open ID, Google ID, Windows Live ID, LinkedIn, Facebook, and Twitter. But for reasons I don’t want go into, a need came up, to create a simple STS (Secure Token Service), than would “tie” together one or more identities from social network, and offer those to websites and applications supporting WIF/Claims based authentication.

Why a new STS
If you implemented Social Network, either directly, or indirectly though ACS you probably noticed that if a user sign in using Google ID they will not be the same user, if they later decide to sign in using Facebook. That is relatively easy to “handle” if you wrote the application your self, and Microsoft did a decent job, tying it all up, using the membership provider together with DotNetOpenAuth in MVC 4, but if you don’t want to mess with wrapping up your own customer member ship provider, or if your facilitating WIF in Exchange/CRM/SharePoint/Navision or what ever, wouldn’t it just be awesome if you could just get it all “out of the box” some where. And what if that Service would also allow you to setup your own Identity Providers, so you could implement sign in using Office 365/Azure AD, your own ADFS server, or any other Secure Token Service you might have. You can now

The basic setup
We are still figuring out license models and such, but for now were thinking either a hosted solution, and one where you get the website to run for your self, lets image a hosted setup, and after that you get billed a small amount for each 100k users or something like that. So let’s imaging you want to implement this with Microsoft CRM 2011.

  • First signup for an account, you then get access to a Manage menu. But before you go there, head to CRM and start the “Configure Claims-Based Authentication” wizard
    image
    Type in the URL of the Secure Token Service
    image
    Select a certificate to use, when signing the Claims inside the tokens (this certificate needs to exists on all your CRM servers if you got more than one. It can be a self signed, from your internal CA, or one you bought from a third party
    image
    Go though the rest. Go though the “Configure Internet-Facing Deployment” if you haven't don’t so already, and at the end note the URL to the CRM servers metadata.xml file
  • Go to the STS, click Relays, past in the URL from the “Create new relying part” field, and press Create. By default all Social connectors will be allowed, but if you only want for instance Live ID, select that under Identity Providers, and hit Save.

And that is that. SharePoint how ever doesn’t have these cool metadata.xml files, so configuring that, will take a tiny bit more work, but not to worry, that is why we got PowerShell.

  • Open a PowerShell prompt locally on any of the servers in your farm. And run the following PowerShell Script . ( there is a link on the Relaying Party page too ) Make sure you modify the variables at the top to fit your installation
  • Head to the STS, click management, type a meaningful name into “Create new relying part” field, and press Create
    If you went with the defaults in the script, SharePoint should be sending a reply URL, so we can leave PassiveRequestorURI blank.
    SharePoint (default) doesn’t want the claims to be encrypted so we don’t need to add a certificate.
    Under “Audience Uris” add each of the URN’s that was mapped for each of the websites, show in the end of the script.

And you are all done.

Adding Azure AD, office 365, Azure ACS or an ADFS server
That’s all nice, but what about all your local users, or all your Office 365 users ?
Not a problem, head to the “Providers” page, and type in the URL to the metadata file.

If you are using Office 365 or Azure AD the URL will look something like this
https://accounts.accesscontrol.windows.net/<tenant>.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml

If your using Microsoft ACS, your URL will look something like this
https://<yourname>.accesscontrol.windows.net/FederationMetadata/2007-06/FederationMetadata.xml
(note, someone at Microsoft fucked this up, so it doesn’t sent a Signing Certificate, but it does doing Office 365 … it’s the same certificate thou, so is easy to grab )

If your using ADFS, the URL will look something like
https://adfs.wingu.dk/FederationMetadata/2007-06/federationmetadata.xml

If your using ACS or ADFS, you don’t need to do anything else than going to the ADFS Server/Azure ACS/Azure AD website and add https://STS/FederationMetadata.xml and it will all configure it self. If how ever your using Office 365, you need to add a ServicePrincipal representing the STS. At the top of the Provider screen is a link to a powershell scrip that will set this up. Once the script is run, past in the “spn:<guid>” from the output of the script into the Target Realm field of the new Provider.

Lastly, go back to your Relying Party, and you can now also select your new Office 365 or what ever Provider you added, and let your users sign in using that

SharePoint 2010 and claims based authentication made a little bit easier

updated 05/03-2013: Added support for extracting root cert from signing certificate
So you have ADFS 2.0 installed. Or your reading some guide about how to configure SharePoint to allow login in using Office 365 or Azure AD or any other kind of Secure Token Service. And 99,9% of them will tell you to copy 1 or more certificates, and run a lot of weird PowerShell command, and it all ends up with you being able to setup some awesome new login page here

image

Well, fear not. If your STS support generating a FederationMetadata.xml URL, you can now use this PowerShell Script to quickly setup your SPTrustedIdentityTokenIssuer . The script can also setup Uri mappings and configure the websites, but I do not recommend using that part in other than development/test environments. Make sure to modify the variables at the top.

I’ve updated the script. If your STS was using a self issued certificate, or a certificate from an internal CA, it wouldn’t be trusted by SharePoint, so added a bit of code to traverse the certificate chain, and then add the root certificate to the Trusted store and also add the root to the list of trusted certificates inside SharePoint

# URL for ADFS / ACS / Office 365 / SimpleSTS / Wingu Cloud ControlPanel / what ever

# $metadataurl = 'https://adfs.wingu.dk/FederationMetadata/2007-06/federationmetadata.xml' # ADFS
# $metadataurl = 'https://accounts.accesscontrol.windows.net/skadefro.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml' # Azure AD
# $metadataurl = 'https://skadefro.accesscontrol.windows.net/FederationMetadata/2007-06/FederationMetadata.xml' # Azure ACS - Wont work, apperently the guy who made this, forgot to add the signing certificat .. :-(
# $metadataurl = 'https://simplests.wingu.dk/FederationMetadata.xml' # Simple STS
# $metadataurl = 'http://admin.wingu.dk/sts2/FederationMetadata/2007-06/federationmetadata.xml' # Wingu Cloud Control Panel
$metadataurl = 'https://simplests.wingu.dk/FederationMetadata.xml'


# This should really be NameID, but often people will use emails or UPN. choose what fits your needs
$IdentifierClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
# What claims do you want mapped. All will be exposed in the ClaimsToken, but what will show up in the people picker ?
$mapClaims = @('UPN', 'Role')

# Default realm. If you only have 1 website, you can add that here, but more correctly would be adding
# Each URI accessible on your farm, mapping it to a URN
# If your using Wingu Cloud Control Panal or SimpleSTS, urn:sps will automaticly be converte to a SharePoint signin URI
# urn:sps:http://spfarm01.cloudapp.net becomes http://spfarm01.cloudapp.net/_trust/
# if not, just use the full uri, like http://spfarm01.cloudapp.net/_trust/
# if you want several sharepoint sites to allow the user access without prompting for login each time,
# use one shared urn (not URI) for all those sites. There are certain restrictions, on how/where you can do that
$defaultrealm = 'urn:sps:https://sharepoint.domain.com'

# Be carefull with this. Not all STS' understand/support's this, and often the above is a simpler solution
# set this to true, will go though the list of sites in the farm and add an "urn:sps:URI" entry for each site
$autoGenerateProviderRealms = $false

# Dont, Dont, DONT ... D-O-N-T, use this
# This will add Windows and ALL identityProviders to all WebApplication's (except Central Admin) for the "default" zone.
$autoAddSTS = $false

$stsname = 'SimpleSTS'
$name = $stsname
$realm = $null
$stsd = $null
$asd = $null

$snapin = Get-PSSnapin | where {$_.name -eq 'Microsoft.SharePoint.PowerShell'}
if($snapin -eq $null){ Add-PSSnapin Microsoft.SharePoint.PowerShell }


function Get-medadata ($metadataurl) {
[void] [Reflection.Assembly]::LoadWithPartialName("Microsoft.IdentityModel")
$STSReader = New-Object Microsoft.IdentityModel.Protocols.WSFederation.Metadata.MetadataSerializer
$req = [System.Net.WebRequest]::Create($metadataurl)
$xmlreader = [System.Xml.XmlReader]::Create($req.GetResponse().GetResponseStream())
$metadata = $STSReader.ReadMetadata([System.Xml.XmlReader]$xmlreader)
$metadata
}

function Get-STS ($metadata) {
foreach($RoleDescriptor in $metadata.RoleDescriptors){
if($RoleDescriptor.GetType().FullName -eq 'Microsoft.IdentityModel.Protocols.WSFederation.Metadata.SecurityTokenServiceDescriptor'){
# metadata have a STS
$stsd = $RoleDescriptor
} elseif($RoleDescriptor.GetType().FullName -eq 'Microsoft.IdentityModel.Protocols.WSFederation.Metadata.ApplicationServiceDescriptor'){
# metadata have a Relying Party
$asd = $RoleDescriptor
}
}
$stsd
}
function Get-RelyingParty ($metadata) {
foreach($RoleDescriptor in $metadata.RoleDescriptors){
if($RoleDescriptor.GetType().FullName -eq 'Microsoft.IdentityModel.Protocols.WSFederation.Metadata.SecurityTokenServiceDescriptor'){
# metadata have a STS
$stsd = $RoleDescriptor
} elseif($RoleDescriptor.GetType().FullName -eq 'Microsoft.IdentityModel.Protocols.WSFederation.Metadata.ApplicationServiceDescriptor'){
# metadata have a Relying Party
$asd = $RoleDescriptor
}
}
$asd
}

function Get-GetCertificate ($stsd, $certificatetype) {
if( ($certificatetype -ne 'Signing') -and ($certificatetype -ne 'Encryption')){
Write-Error "CertificateType should be 'Signing' or 'Encryption'"
return
}
$has40 = [Reflection.Assembly]::LoadWithPartialName("System.IdentityModel")

$SigningCertificate = $null
foreach($key in $stsd.Keys){
if($key.Use -eq $certificatetype){
if($has40.GetName().Version.Major -eq 4){
#if .net 4.0 is install we can just do this, when System.IdentityModel v4.0.30319 is loaded
$bytes = $key.Keyinfo.GetX509RawData()
} else {
#but default, sharepoint 2010 only have version v2 loaded so, lets do it, the ugly way
$str = $key.Keyinfo.ToString()
$str = $str.Substring( $str.IndexOf('RawData = ') + 10)
$str = $str.Substring(0, $str.IndexOf(')'))

$bytes = ([system.Text.Encoding]::UTF8).GetBytes($str)
}
$SigningCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]([byte[]]$bytes)
}
}
$SigningCertificate
}

Function Ensure-SPProvider($name, $defaultrealm, $SigningCertificate, $SigninURL, $claims, $IdentifierClaim, $mapClaims){
$certificatename = "$($name) Signing Certificate"
$cert = get-SPTrustedRootAuthority | ?{($_.Certificate.Thumbprint -eq $SigningCertificate.Thumbprint) -or ($_.Name -eq $certificatename)}
if(!$cert){
Write-Host "Adding $($SigningCertificate.Thumbprint) as a Trust Certificate"
$cert = New-SPTrustedRootAuthority -name $certificatename -Certificate $SigningCertificate
} else {
$cert | Set-SPTrustedRootAuthority -Certificate $SigningCertificate
}
$chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
$chain.Build($SigningCertificate)
$SigningCertificateRoot = $chain.ChainElements[$chain.ChainElements.Count -1].Certificate

# Ensure Root Cert has been added to Trusted Store
$store = get-item cert:\LocalMachine\Root
$store.Open("ReadWrite")
$store.Add($SigningCertificateRoot )
$store.Close()

# And now, add it to SharePoint too
$rootcert = get-SPTrustedRootAuthority | ?{($_.Certificate.Thumbprint -eq $SigningCertificateRoot.Thumbprint)}
if(!$rootcert){
Write-Host "Adding $($SigningCertificateRoot.Thumbprint) as a Trust Certificate"
$rootcert = New-SPTrustedRootAuthority -name $SigningCertificateRoot.Subject -Certificate $SigningCertificateRoot
}

$IDClaim = $null
$claimsmappings = @()
foreach($claim in $claims) {
# http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name is reserved inside SharePoint (??? Why ?... really, WTF !!!!)
# http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid is only used in SharePoint 2013 ( not tested yet )
# its SharePoints internal STS job to handle the requiered fields
# http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod
# http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant

if($claim.ClaimType -eq 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'){
$claimsmappings += New-SPClaimTypeMapping $claim.ClaimType -IncomingClaimTypeDisplayName $claim.DisplayTag -LocalClaimType 'http://simplests.wingu.dk/identity/claims/name'
} elseif($claim.ClaimType -eq 'http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod'){
# Skip
} elseif($claim.ClaimType -eq 'http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant'){
# Skip
} elseif($claim.ClaimType -eq 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier'){
$claimsmappings += New-SPClaimTypeMapping $claim.ClaimType -IncomingClaimTypeDisplayName $claim.DisplayTag -LocalClaimType 'http://simplests.wingu.dk/identity/claims/nameidentifier'
} else {
$claimsmappings += New-SPClaimTypeMapping -IncomingClaimType $claim.ClaimType -IncomingClaimTypeDisplayName $claim.DisplayTag -SameAsIncoming
}
if($IdentifierClaim -eq $claim.ClaimType){
$IDClaim = $claim.ClaimType
}
}

$ap = Get-SPTrustedIdentityTokenIssuer | ?{$_.name -eq $name}
if(!$ap){
$ap = New-SPTrustedIdentityTokenIssuer -Name $name -Description $name -Realm $defaultrealm -ImportTrustCertificate $SigningCertificate -ClaimsMappings $claimsmappings -SignInUrl $SigninURL -IdentifierClaim $IDClaim
}
# Ensure all claim mappins are there
#foreach($claim in $claims) {
# $hasClaim = $ap.ClaimTypes | ?{$_ -eq $claim.ClaimType}
# if(!$hasClaim) {
# Write-Host "adding ClaimType $($claim.DisplayTag) to $name"
# $ap.ClaimTypes.Add($claim.ClaimType)
# }
#}

#$ap.Update()
#Add-SPClaimTypeMapping -Identity $claim -TrustedIdentityTokenIssuer $ap
#$ap = Get-SPTrustedIdentityTokenIssuer | ?{$_.name -eq $name}

# if you only have 1 sharepoint site, and dont want to "bother" setting up
# Reply URL on your STS ( adfs - AD FS 2.0 Management -> Trust Releationships ->
# Relying Party Trusts -> Properties on RP Go to "Endpoints" tab -> WS-Federation Passive Endpoint
# Or SimpleSTS -> Management -> Relying Party -> Manage -> PassiveRequestorURI
# you can just override the $ap.DefaultProviderRealm
# but the correct way would be to list each unique URI with an associated URN in $ap.ProviderRealms
$ap.DefaultProviderRealm = $defaultrealm

$ap.ProviderUri = $SigninURL
#$ap.Name = $name
#$ap.DisplayName = $name


# If WReply is not set, sharepoint will not add return URL when sending user to login page
# if DefaultProviderRealm/$ap.ProviderRealms URN is not listed with a Return URL in the STS
# the STS will not know where to send the user. What's "correct" ? dont know.
# if your paranoid, leacing WReply $false, using URN's all the places, and keeping Passive Federation
# URL's in you STS would proberly be best, but let's ensure we can have both unique URI's, prober return URI's
# and unique'nes by using $ap.ProviderRealms
$ap.UseWReplyParameter = $true

# HomeRealm tells the STS how the user want to to login instead of prompting.
# ADFS will ask and save a cookie, for 3 months, most custom solutions, will prompt each time
# for instance SimpleSTS will allow you to choose each time from a list of all allowed providers
# Sharepoint will NEVER know what those homerealms could be.
# SharePoint's internet STS will normaly "strip" off HomeRealm ( WHR= ) but with the Juni RU this new
# parameter was added to allow adding HomeRealm in custom code (modules or custom login page) without loosing the WHR parameter
# http://blogs.msdn.com/b/chriskeyser/archive/2011/10/02/sharepoint-2010-claims-and-home-realm-discover-passing-whr-on-the-url-to-sharepoint.aspx
try {
$ap.UseWHomeRealmParameter = $true
} catch {
Write-Warning "SharePoint is not update, and wont allow setting UseWHomeRealmParameter, make sure you use uri:sp: as realms/AudienceURIs, or set PassiveRequestorURI to [SharePointURI]/_trust/"
$Error.Clear()
}
$ap.Update()

}
$metadata = Get-medadata $metadataurl
$stsrealm = $metadata.EntityId.Id
$stsd = Get-STS $metadata
#$asd = Get-RelyingParty $metadata
$SigningCertificate = Get-GetCertificate $stsd 'Signing'
#$encryptionCertificate = Get-GetCertificate $asd 'Encryption'
$claims = $stsd.ClaimTypesOffered

foreach($PassiveRequestorEndpoint in $stsd.PassiveRequestorEndpoints){
$SigninURL = $PassiveRequestorEndpoint.Uri.AbsoluteUri
}

Ensure-SPProvider $stsname $defaultrealm $SigningCertificate $SigninURL $claims $IdentifierClaim $mapClaims

if($autoGenerateProviderRealms -eq $true){
# We could use Get-SPWebApplication, and then Get-SPAlternateURL on each site
# we could also filter out only "external" sites, etc ....

$ap = Get-SPTrustedIdentityTokenIssuer | ?{$_.name -eq $stsname}
#$ap.ProviderRealms.Clear()
foreach($wa in Get-SPWebApplication){
$pr = $ap.ProviderRealms.keys | where {$_.AbsoluteUri -eq $wa.Url}
if(!$pr){ $pr = $ap.ProviderRealms.Add([uri]($wa.Url), "urn:sps:$($wa.Url)") }
}
$ap.Update()
}
if($autoAddSTS -eq $true){
$windowsap = New-SPAuthenticationProvider
#$aps = Get-SPAuthenticationProvider -Zone "Default" -WebApplication $wa
$aps = @()
$aps += $windowsap
foreach($ap in Get-SPTrustedIdentityTokenIssuer){
$aps += $ap
}
foreach($wa in Get-SPWebApplication){
Set-SPWebApplication -Identity $wa -Zone "Default" -AuthenticationProvider $aps # -Force
}
}

$ap = Get-SPTrustedIdentityTokenIssuer | ?{$_.name -eq $stsname}
Write-Host "ensure '$($defaultrealm) and each 'Value' is added to the Relying Party in the STS"
$ap.ProviderRealms

tirsdag den 5. februar 2013

Fully automated deployment of SharePoint farms in Microsoft Azure

There a plenty of blogs out there about scripting SharePoint, so I wont fill up more space about all the troubles and joys regarding that. I will how ever point you in the direction of AutoSpInstaller who have an awesome script for slip streaming SharePoint installations and better yet. Automating the deployment of SharePoint 2010 and 2013.

I’ve seen a few blog post about installing SharePoint in Microsoft Azure, and I wanted to add my two cent about that. I just finished up doing a Proof of Concept showing a FULLY automated installation of multiple both single and multiple server, SharePoint farm, inside Microsoft Azure. This is how I did it.

I’m developing a Provisioning Engine that supports running in many sites and distribute servers and services across these sites seamlessly. I order to start facilitating Azure we need a subscription and some Persistent VMs deployed inside that subscription. I originally wanted to do everything “offsite” from each subscription, so a new customer could start from scratch, but after a while it became clear I needed some more granulated control doing deployment and needed to deploy my provisioning engine inside the subscription. Microsoft does not have an API for creating subscriptions (that I know off) so we manually sign up for a new Azure Subscription. Next we sign up for a Trial Account in our Provisioning Site. Create a certificate and upload it to Azure and Add Subscription ID and certificate to my Provisioning API in order to make the provisioning engine able to facilitate Azure for that subscription.

We do that by adding a Provisioning Site,

image

Next, we need to make sure all servers can see each other. We can install everything on one server. We can add all servers to the same Azure Hosted Service. We can “link” different roles to a Azure Hosted Service (I have not tested this) or we can create a Virtual Network. The latter is most appealing, so we add a Workspace

image

( at the time of writing, I have not automated the creating of the Virtual Network inside Azure, so we need to add it manually inside Azure and fill out the values in the Workspace plan )

image

Once this is done, manually Add a server to Azure, and deploy our provisioning engine. (this could later be a custom image, or pushed from another site, but for proof of concept, doing this manually  is ok). We link the server to the provisioning site, so the new server have access to all services, and we are now ready to automated everything else.

Next we add an Microsoft SQL server. This can also be done while adding the SharePoint Farm
image

Let customize the SharePoint installation so we control Server names etc. Create a Hosted Service for our new SharePoint Farm

image

image

Next add 1 or more servers depending on how big you want the farm to be

image

Make sure to update relation to point to your new Azure Hosted Service if you got more than one. Lastly we need to add a SharePoint farm on top of the Hosted Service.
image
Fill out desired SMTP/Email settings if needed, and hit deploy. This will automatically add a new Hosted Service and add an SQL Server inside that Service. It will add a Plan for each of the (up to) 22 (default is 16) databases  needed to run the farm, once all have been setup it will deploy SharePoint to each of the servers you added in the above steps, it will create a new Farm, a default SharePoint site and My Site. Configure most of the normal features of a SharePoint farm ( but any features supported by AutoSpInstaller is supported here too)

So what happens behind the scene? Well, AutoSpInstaller supports deploying SharePoint remotely on one or more servers, but it uses PS Exec from PS Tools to do it. ( if you look in the PowerShell scripts it looks like the author also tried making it work using WSMan ( invoke-computer / new-pssession )) but a new blank server doesn’t allow connect with either, so we need a way to get in contact with the server in the first place. If you deploy the standard Windows 2003 image, it allows you to talk with it, using WMI but not WSMan, so you could fire off a WMI command to run the command to configure WSMan ( winrm quickconfig ) but if you deploy a Windows 2012 server, your just out of luck, neither WMI or WSMan will work. You can how ever, tell Windows Azure to automatically join new servers to a domain, and when we are talking about SharePoint you need the servers to be domain joined. Once a Windows server 2012 is part of a domain, you can connect using WSMan and execute PowerShell on the machine (but not WMI, hence PS Exec will not work )

Sure, you could just fire up all servers to be part of a domain, create a group policy to configure the firewall (and maybe there is a Policy for doing something like a winrm quickconfig  too?) but I wanted something generic. Granted, I never figured out a way to “cheat” a fresh Windows 2012 that is not a domain member, I guess I will need to create a custom Image for those later, but for now, having them domain joined was good enough.

On all servers I deploy, I automatically I push out a small windows service. It handles certificates, joining/disjoining domains, installing software, remote management and is also used on Remote Desktop and Citrix XenApp servers to manage user sessions. Its perfect for handling the SharePoint installation and with above I can now push out this service though WMI and/or WSMan and kick of the installation. So the service handles installing an SQL server. well tested and Known technology and easy to automate, next we can now kick off the SharePoint installation.

AutoSpInstaller uses Start-Transcript doing installation, and I haven't figured out how to “support” that in a custom hosted PowerShell host, so first I had to strip that out. Next it does an insane amount of “am waiting lets do a write a “.” dot each second” thing, and is annoying as hell in the console logs, so had to strip those out too. Lastly you need patience … A LOT of it … So now when looking at the Provisioning Request Log is more clean.

imageimage

For some reason the first server you install, that will also handle setting up the farm, and configuring services, will take from 2½ to 4 hours depending on the amount of services you choose. The following servers can take up to 30 minutes to install binaries, and 20 to 40 minutes joining the farm and configuring services. Not sure why really (both CPU/memory and Disk queue length is way below any warning signs on all servers doing the installation)

Once AutoSpInstaller is done, its easy and well documented how to connect to one of the servers and configuring new SharePoint sites/Site Collections and adding/removing users and groups, as part of my provisioning engine.

When using AutoSpInstaller it worth taking 2 minute extra reading the comments in the AutoSPInstallerInput.xml file. Stuff like how database prefix's, limits on characters' in password, or knowing that what worked on your “single” server install will not work in farms ( using the default http://localhost as WebApp name’s or not limiting the QueryServer to a single server will take a lot longer to troubleshoot that just reading the damn documentation Winking smile )

lørdag den 26. maj 2012

SetSPN slow

This one was kind of obvious, but took me a while to see though.

Ever had issues with setspn being very slow when listing or adding a new SPN ?
Did you notice its only when working with user accounts, but not machine accounts ?

Look at the help text

image

So SetSPN will assume your working with a computer account unless you specify other wise. IT will work yes, but be slow, so if you are working with a User Account remember to add -U

søndag den 23. oktober 2011

Deploy CRM List Component though PowerShell

as always I did a few searches on Google. Most hits just explained how to upload the WSP file and then call the AllowHtcExtn.ps1 script.

On blog did explain you could use Add-SPSolution and Install-SPSolution but that didn’t work for me.

$solution = Get-SPSolution crmlistcomponent.wsp
if(!$solution){ $solution = Add-SPSolution X:\SPS_2010_prov\listekomponent\en\crmlistcomponent.wsp }
Install
-SPSolution -WebApplication "https://$webappurl" $solution -GACDeployment -Force

The solution didn’t show up in Solution Gallery inside SharePoint. And when I tested from CRM 2011 it kept complaining the List Component isn't installed.


I have just been to Microsoft Campus Days in Copenhagen ( kind of a “mini TechEd” ) and one of the session I was attending was about SharePoint Online and how Microsoft only allow Sandbox solutions, and then it hit me. Maybe the CRM list Component is a sandbox solution and needs to be deployed that way. We have a winner!


So we end up with


Write-Host "Starting Sharepoint User Code Service"
stsadm
-o provisionservice -action start -servicetype Microsoft.SharePoint.Administration.SPUserCodeService -servicename SPUserCodeV4

Write
-Host "Install crmlistcomponent if needed"
$solution = Get-SPUserSolution crmlistcomponent.wsp -Site "https://$webappurl" -ea 0
if(!$solution){
$temp = Add-SPUserSolution X:\SPS_2010_prov\listekomponent\en\crmlistcomponent.wsp
$solution = Get-SPUserSolution crmlistcomponent.wsp -Site "https://$webappurl"
}

Write
-Host "Active crmlistcomponent if needed"
if($solution.Status -ne 'Activated'){
$solution = Install-SPUserSolution $solution -Site "https://$webappurl"
}

Write
-Host "Make sure .htc file name extension is an allowed file type"
$app = Get-SPWebApplication -Identity "https://$webappurl"
$app.AllowedInlineDownloadedMimeTypes.Add("text/x-component")
if(!$app.WebFileExtensions.Contains("htc")){
Write
-Host "Adding .htc file name extension to the list of allowed file types."
$app.WebFileExtensions.Add("htc")
$app.Update()
}

lørdag den 8. oktober 2011

SharePoint and WebDAV–part 2

So I was troubleshooting mapping SharePoint though WebDAV and found I had to open the SharePoint site though office in one way or the other, in order to successfully map it. That was true, but for one very specific reason.

Talking about cookies, you need to know there is 2 kinds of cookies. Session Cookies and Persistent cookies. Session cookies only “lives” as long as your browser is open. As soon as you close *ALL* your browser windows they cookie will expire. Persistent cookies will stay on your machine until the expire date on the cookie is hit.

When you setup SharePoint to use Claimsbased authentication SharePoint save a cookie on your machine called the “FedAuth” cookie. This is your what authenticate you every time you hit SharePoint. It gets set when the Identity Provider (STS/ADFS) makes your browser “post” your claims to https://fqdn/_trust/ .It gets removed when you click “sign out” or “Sign in as Different User”.

The WebDAV client, and various Office applications does support working with websites that facilitate Claimsbased authentication, but they cannot authenticate you. It assumes you have a FedAuth cookie on your machine. Some times you will get a browser popup, but there are places this wont happen (like with WebDAV). I had told SharePoint to use Session Cookies, since that would make more sense when working with SharePoint. You login you do your stuff, you might sign out, or you might close your browser. Next time you hit it, it asks you to login. I was happy, everyone else was happy. That is, until someone needed to work with SharePoint from within Outlook and though WebDAV.

SharePoint will standardly run with Persistent Cookies, but you can change this though PowerShell. Set UseSessionCookies to $true or $false. If you need to work with SharePoint though Office or WebDAV you need to set this to $false (default)

$snapin = Get-PSSnapin | where {$_.name -eq 'Microsoft.SharePoint.PowerShell'}
if($snapin -eq $null){ Add-PSSnapin Microsoft.SharePoint.PowerShell }

$sts = Get-SPSecurityTokenServiceConfig
$sts.UseSessionCookies = $false
$sts.Update()
iisreset

As far as I know, you cannot set this per site.


Next you want to make sure Office/Web Client can read the cookie. Referee to “Persistent cookies are not shared between Internet Explorer and Office applications”

fredag den 30. september 2011

SharePoint 2010 and WebDAV

Updated 08-10-2011: Please see update here

I have known for sometime that SharePoint supports WebDAV, and in my experience, you always end up spending a few hours getting it to work. Today was no different.

A collogue of mine sent me an email complaining he couldn’t connect to he's SharePoint 2010 site in explore or use the Explorer View button within the site. "Open with Explorer”

image

I knew I had seen it work in the past but for some reason I couldn’t get it to work for me neither. I tried everything but no matter what I just kept getting an annoying “Your client does not support opening this list with Windows Explorer”

image

And when connecting with “net use * https://blah.blah” I would constantly get

System error 224 has occurred.

Access Denied. Before opening files in this location, you must first add the web site to your trusted sites list, browse to the web site, and select the option to login automatically.

image

there is a billion hits on Google searching for this, but one of the more interesting was a White paper on Microsoft.com - Understanding and Troubleshooting the SharePoint Explorer View but it didn’t really get me any further.

I’m using Claimsbased authentication on all SharePoint sites, so I started thing it had something to do with that. I found this post, that claims you cannot connect to SharePoint if it using Forms based authentication / Claimsbased authentication. But then I test on my local computer where I also SharePoint installed configured to use Claims too, and that works. This was starting to be really annoying

God know how, but then I cam across this post. Note that he writes:

The Open with Explorer and the new Upload Multiple seems to depend on Office 2010 being installed.

So I was clicking around inside SharePoint as a maniac and at one point I hit the “Connect to Office” button, and suddenly it worked.
image

I instantly opened a DOS prompt and tried “net use * https:\\blah” and it worked too.

So while writing this blog post, I created a new SharePoint site with English language instead of Danish to make some better screenshots. And clicking Connect to Office just didn’t seem to be enough, so I started looking at the differences between the Danish site and the English site. 2 things where different. I normally don’t enable Anonymous Access, but I had done that on the Danish site.

image

And I normally don’t enable Basic authentication, but I had here.

image

Still nothing. This was driving me nuts now …. so I started clicking around like a maniac again, and BAM suddenly it all worked again. What the hell ???

Now I was getting mad. I created a new site ( Basic authentication disabled, and Anonymous Access disabled like normal ). View in Explorer fails as expected. I click the “Datasheet View”
image

And after that everything suddenly works. I guess the trick here is making sure Office have “talked” with the SharePoint site in some way or the other.

What a waste of a few good hours I will never get back …

onsdag den 7. september 2011

SharePoint 2010–Set custom sign in page

this one took me several hours. So much crap on Google but no solution anywhere.

If your SharePoint site is using Classic Mode Authentication

$webappurl = 'https://web.site.com'
Set-SPCustomLayoutsPage -Identity Login -RelativePath "/_layouts/something/login.aspx" -WebApplication $webappurl

To remove it again use

$webappurl = 'https://web.site.com'
Set-SPCustomLayoutsPage -Identity Login -reset -WebApplication $webappurl

If how ever your site is using Claims Based Authentication this wont work. Then use

$webappurl = 'https://web.site.com'
Set-SPWebApplication $webappurl -zone Default -SignInRedirectURL "/_layouts/wingu.SharePoint.Authentication/login.aspx"

And to remove it (reset it) again use

$webappurl = 'https://web.site.com'
Set-SPWebApplication $webappurl -zone Default -SignInRedirectURL ""

And a not to my self on how to do it on all websites

get-SPWebApplication | foreach-object {
    $_
    $ap1 = Get-SPTrustedIdentityTokenIssuer
    $ap2 = New-SPAuthenticationProvider -UseWindowsIntegratedAuthentication
    Set-SPWebApplication $_.Url -AuthenticationProvider $ap1, $ap2 -zone Default -SignInRedirectURL "/_layouts/wingu.SharePoint.Authentication/login.aspx"
}

søndag den 3. juli 2011

SharePoint 2010 Managed Client Object Model and Claims based authentication

Update 22-09-2011: There is a more clean way to do this here
What a pain, this was. A client asked if I had some demo code for how to upload a file into SharePoint 2010. I though to my self, how hard can it be ? and went to it.

First thing you’ll run into is knowing how to even talk with SharePoint. there's a few but Google quickly lead me to SharePoint Foundation 2010 Managed Client Object Model And you download it here. That’s all nice and easy when using windows authentication or Forms based authentication. But if your using claims based authentication (like we are and Microsoft Online Services ) you wont find many examples out there.

I was struggling for a long time with this and everything I searched for kept getting me back to ClientOmAuth but its C# and I didn’t have a lot of luck with the initial copy’n’pasting to VB but after trying some other approaches that didn’t lead me anywhere good I went back to the above code and gave it a shot. So here's a VB.NET version supporting both Windows Authentication ( adfs/services/trust/13/windowstransport ) and username/password ( adfs/services/trust/13/usernamemixed ). Windows Authentication require you enable windowstransport  on the STS / ADFS server.

Imports Microsoft.IdentityModel.Protocols.WSTrust
Imports System.Security.Principal

Imports System.ServiceModel
Imports System.ServiceModel.Channels

Imports System.Net.Security
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Xml

Public Class SPAuth

    Private SPSUrl As String
    Private ADFSUrl As String
    Private _SAMLToken As String
    Private _Username As String
    Private _Password As String

    Public ReadOnly Property samlUri() As Uri
        Get
            Return New Uri(SPSUrl)
        End Get
    End Property

    Public ReadOnly Property SAMLToken() As String
        Get
            Return _SAMLToken
        End Get
    End Property

    Public WriteOnly Property username As String
        Set(value As String)
            _Username = value
        End Set
    End Property

    Public WriteOnly Property Password As String
        Set(value As String)
            _Password = value
        End Set
    End Property

    Sub New(SPSUrl As String, ADFSUrl As String, username As String, password As String)
        _Username = username
        _Password = password
        Me.SPSUrl = SPSUrl
        Me.ADFSUrl = ADFSUrl
        _SAMLToken = GetNewSamlToken()
    End Sub

    Sub New(SPSUrl As String, ADFSUrl As String)
        Me.SPSUrl = SPSUrl
        Me.ADFSUrl = ADFSUrl
        _SAMLToken = GetNewSamlToken()
    End Sub

    Private Function GetNewSamlToken() As String
        Dim ret As String = String.Empty

        Try
            Dim samlServer As String = If(SPSUrl.EndsWith("/"), SPSUrl, SPSUrl + "/")

            Dim sharepointSite = New With { _
             Key .Wctx = samlServer & "_layouts/Authenticate.aspx?Source=%2F", _
             Key .Wtrealm = samlServer, _
             Key .Wreply = samlServer & "_trust/" _
            }

            Dim stsServer As String = If(ADFSUrl.EndsWith("/"), ADFSUrl, ADFSUrl + "/")
            Dim stsUrl As String = stsServer & "adfs/services/trust/13/windowstransport"

            'get token from STS
            Dim stsResponse As String = GetResponse(sharepointSite.Wreply)

            'generate response to Sharepoint
            Dim stringData As String = [String].Format("wa=wsignin1.0&wctx={0}&wresult={1}", System.Web.HttpUtility.UrlEncode(sharepointSite.Wctx), System.Web.HttpUtility.UrlEncode(stsResponse))
            Dim sharepointRequest As HttpWebRequest = TryCast(HttpWebRequest.Create(sharepointSite.Wreply), HttpWebRequest)
            sharepointRequest.Method = "POST"
            sharepointRequest.ContentType = "application/x-www-form-urlencoded"
            sharepointRequest.CookieContainer = New CookieContainer()
            sharepointRequest.AllowAutoRedirect = False
            ' This is important
            Dim newStream As Stream = sharepointRequest.GetRequestStream()

            Dim data As Byte() = Encoding.UTF8.GetBytes(stringData)
            newStream.Write(data, 0, data.Length)
            newStream.Close()
            Dim webResponse As HttpWebResponse = TryCast(sharepointRequest.GetResponse(), HttpWebResponse)
            ret = webResponse.Cookies("FedAuth").Value
        Catch ex As Exception
            MessageBox.Show("Error: " + ex.Message)
        End Try

        Return ret
    End Function

    Private Function GetResponse(realm As String) As String

        Dim rst As New RequestSecurityToken()
        rst.RequestType = WSTrust13Constants.RequestTypes.Issue


        'bearer token, no encryption
        rst.AppliesTo = New EndpointAddress(realm)
        'rst.KeyType = WSTrustFeb2005Constants.KeyTypes.Bearer;
        rst.KeyType = WSTrust13Constants.KeyTypes.Bearer

        Dim stsServer As String = If(ADFSUrl.EndsWith("/"), ADFSUrl, ADFSUrl + "/")
        Dim stsUrl As String = stsServer & "adfs/services/trust/13/windowstransport"

        'WSTrustFeb2005RequestSerializer trustSerializer = new WSTrustFeb2005RequestSerializer();
        Dim trustSerializer As New WSTrust13RequestSerializer()
        Dim binding As New WSHttpBinding()
        If _Username <> "" And _Password <> "" Then
            stsUrl = stsServer & "adfs/services/trust/13/usernamemixed"
            binding.Security.Mode = SecurityMode.TransportWithMessageCredential
            binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName
            binding.Security.Message.EstablishSecurityContext = False
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic


        Else
            binding.Security.Mode = SecurityMode.Transport
            binding.Security.Message.ClientCredentialType = MessageCredentialType.None
            binding.Security.Message.EstablishSecurityContext = False
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows
        End If

        Dim address As New EndpointAddress(stsUrl)
        'WSTrustFeb2005ContractClient trustClient = new WSTrustFeb2005ContractClient(binding, address);
        Dim trustClient As New WSTrust13ContractClient(binding, address)
        If _Username <> "" And _Password <> "" Then
            trustClient.ClientCredentials.UserName.UserName = _Username
            trustClient.ClientCredentials.UserName.Password = _Password
        Else
            trustClient.ClientCredentials.Windows.AllowNtlm = True
            trustClient.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation
            trustClient.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials
        End If

        'MessageVersion.Default, WSTrustFeb2005Constants.Actions.Issue,
        Dim response As System.ServiceModel.Channels.Message = trustClient.EndIssue(trustClient.BeginIssue(System.ServiceModel.Channels.Message.CreateMessage(MessageVersion.[Default], WSTrust13Constants.Actions.Issue, New RequestBodyWriter(trustSerializer, rst)), Nothing, Nothing))
        trustClient.Close()

        Dim reader As XmlDictionaryReader = response.GetReaderAtBodyContents()
        Return reader.ReadOuterXml()
    End Function

    Public Sub clientContext_ExecutingWebRequest(sender As Object, e As Microsoft.SharePoint.Client.WebRequestEventArgs)
        Dim cc As New CookieContainer
        Dim samlAuth As New Cookie("FedAuth", SAMLToken)
        samlAuth.Expires = DateTime.Now.AddHours(1)

        samlAuth.Path = "/"
        samlAuth.Secure = True
        samlAuth.HttpOnly = True
        samlAuth.Domain = samlUri.Host
        cc.Add(samlAuth)
        e.WebRequestExecutor.WebRequest.CookieContainer = cc
        'e.WebRequestExecutor.WebRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
    End Sub

End Class

<ServiceContract()> _
Public Interface IWSTrust13Contract
    <OperationContract(ProtectionLevel:=ProtectionLevel.EncryptAndSign, Action:="http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue", ReplyAction:="http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTRC/IssueFinal", AsyncPattern:=True)> _
    Function BeginIssue(request As System.ServiceModel.Channels.Message, callback As AsyncCallback, state As Object) As IAsyncResult
    Function EndIssue(asyncResult As IAsyncResult) As System.ServiceModel.Channels.Message
End Interface

Partial Public Class WSTrust13ContractClient
    Inherits ClientBase(Of IWSTrust13Contract)
    Implements IWSTrust13Contract

    Public Sub New(binding As System.ServiceModel.Channels.Binding, remoteAddress As System.ServiceModel.EndpointAddress)
        MyBase.New(binding, remoteAddress)
    End Sub

    Public Function BeginIssue(request As System.ServiceModel.Channels.Message, callback As System.AsyncCallback, state As Object) As System.IAsyncResult Implements IWSTrust13Contract.BeginIssue
        Return MyBase.Channel.BeginIssue(request, callback, state)
    End Function

    Public Function EndIssue(asyncResult As System.IAsyncResult) As System.ServiceModel.Channels.Message Implements IWSTrust13Contract.EndIssue
        Return MyBase.Channel.EndIssue(asyncResult)
    End Function
End Class
So when you need to talk with your SharePoint you just type
' Use windows login (Kerberose)
' Dim SPAuth As New SPAuth("https://somesite.portal.domain.com", "https://adfs.domain.com")

' Use FBA, send username and password
Dim SPAuth As New SPAuth("https://somesite.portal.domain.com", "https://adfs.domain.com", "username@domain.com", "Sup3rS3cret")

Dim clientContext As New ClientContext("https://somesite.portal.domain.com/")
AddHandler clientContext.ExecutingWebRequest, AddressOf SPAuth.clientContext_ExecutingWebRequest
clientContext.Credentials = CredentialCache.DefaultCredentials
CurrentSite = clientContext.Web
clientContext.Load(CurrentSite)
clientContext.ExecuteQuery()