fredag den 9. september 2011

SuperOffice 7 – Connecting to the damn thing

updated 23-09-2011: Removed my remarks about superoffice. That was childish of me.
updated 23-09-2011: This config script wont work. The superoffice.config contain elements that will break when used from socrm.exe ( the client ) .. please look at my powershell snapin for the same thing

I really don’t like superoffice force me/us to use DNS instead of just giving the option to use connection strings. But that is just how it is for now.

Anyway, so in order to connect to SuperOffice you need to make a DSN link within ODCB administration in order for SuperOffice to be able to speak with its database. Once that is in place you need to create an app.config file defining how SuperOffice can connect to this database. They call this superoffice.config but it is just a plain app.config file. If using a client to connect you also need to put all this information in one more time, but in old school INI format .. ( how lame, talk about redundant redundancy )

I started with a PowerShell script to do all this but I ended up creating my own PowerShell PSCmdlet to handle all the SuperOffice stuff.

So first I need to create the DSN .. and of it needs to be the 32 bit version

function Create32bitDSNLink([string]$DSNName, [string]$DBServer, [string]$DBName, [string]$DriverName, [string]$Driverdll){
$HKLMPath1 = "HKLM:\SOFTWARE\Wow6432Node\ODBC\ODBC.INI\" + $DSNName
$HKLMPath2 = "HKLM:\SOFTWARE\Wow6432Node\ODBC\ODBC.INI\ODBC Data Sources"

md
$HKLMPath1 -ErrorAction silentlycontinue

set
-itemproperty -path $HKLMPath1 -name Driver -value $Driverdll
set
-itemproperty -path $HKLMPath1 -name Description -value $DSNName
set
-itemproperty -path $HKLMPath1 -name Server -value $DBServer
set
-itemproperty -path $HKLMPath1 -name LastUser -value ""
set
-itemproperty -path $HKLMPath1 -name Trusted_Connection -value "Yes"
set
-itemproperty -path $HKLMPath1 -name Database -value $DBName

## This is required to allow the ODBC connection to show up in the ODBC Administrator application.
md $HKLMPath2 -ErrorAction silentlycontinue
set
-itemproperty -path $HKLMPath2 -name "$DSNName" -value $DriverName
}


Next we need to create the ini file and superoffice.config


function CreateSuperOfficeconfig([string]$Path, [string]$dbserver, [string]$dbname, [string]$SOAdminUser, [string]$SOAdminPass){
$filename = ($Path + 'SuperOffice.config')
if ( (Test-Path $filename) -eq $true) { Clear-Content -path $filename }

add
-content -path $filename -value ('<?xml version="1.0" encoding="utf-8"?>')
add
-content -path $filename -value ('<configuration>')
add
-content -path $filename -value (' <configSections>')
add
-content -path $filename -value (' <sectionGroup name="SuperOffice">')
add
-content -path $filename -value (' <sectionGroup name="Security">')
add
-content -path $filename -value (' <section name="Cryptography" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />')
add
-content -path $filename -value (' </sectionGroup>')
add
-content -path $filename -value (' <section name="ClientConfigurationProvider" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />')
add
-content -path $filename -value (' <section name="Diagnostics" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />')
add
-content -path $filename -value (' <sectionGroup name="Data">')
add
-content -path $filename -value (' <section name="Session" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />')
add
-content -path $filename -value (' <section name="Database" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />')
add
-content -path $filename -value (' <section name="ImplicitAnonymous" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />')
add
-content -path $filename -value (' <section name="Explicit" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />')
add
-content -path $filename -value (' </sectionGroup>')
add
-content -path $filename -value (' <sectionGroup name="Factory">')
add
-content -path $filename -value (' <section name="CustomFactories" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />')
add
-content -path $filename -value (' <section name="DynamicLoad" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />')
add
-content -path $filename -value (' </sectionGroup>')
add
-content -path $filename -value (' <sectionGroup name="Mail">')
add
-content -path $filename -value (' <section name="Component" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>')
add
-content -path $filename -value (' </sectionGroup>')
add
-content -path $filename -value (' <section name="Documents" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />')
add
-content -path $filename -value (' <section name="Globalization" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />')
add
-content -path $filename -value (' <section name="Services" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />')
add
-content -path $filename -value (' </sectionGroup>')
add
-content -path $filename -value (' </configSections>')
add
-content -path $filename -value (' <Security>')
add
-content -path $filename -value (' <Cryptography>')
add
-content -path $filename -value (' <add key="SymmetricKey" value="mbiNaaa+3wWcbzGWCnvCvRBoLg8NADQiXaaChJ38W1w=" />')
add
-content -path $filename -value (' <add key="SymmetricIV" value="aBL3Kh0mXHzn+NvXkSS/Lg==" />')
add
-content -path $filename -value (' <add key="SymmetricSecret" value="SuperOffice NetServer 1.0 Alpha lab-testing" />')
add
-content -path $filename -value (' </Cryptography>')
add
-content -path $filename -value (' </Security>')
add
-content -path $filename -value (' <ClientConfigurationProvider>')
add
-content -path $filename -value (' <!-- FilePath should be the root directory of structure where GUI configuration XMLs are located. ')
add
-content -path $filename -value (' Application and instance names become subdirectories to this path. If empty, missing or invalid,')
add
-content -path $filename -value (' the path of the NetServer assemblies will be used as root. -->')
add
-content -path $filename -value (' <add key="FilePath" value="C:\RunningTests\TestConfiguration\" />')
add
-content -path $filename -value ('')
add
-content -path $filename -value (' <!-- If caching is true, the NetServer configuration services will cache configurations on a per-user or per-group basis in the')
add
-content -path $filename -value (' BinaryObject table, and the Six.Web client will cache them in session state. If false, no caching will be done and there will')
add
-content -path $filename -value (' be a significant amount of processing on each GUI refresh. However, you will see changes to the GUI immediately, useful for development. -->')
add
-content -path $filename -value (' <add key="CacheConfigurations" value="true" ></add>')
add
-content -path $filename -value (' </ClientConfigurationProvider>')
add
-content -path $filename -value ('')
add
-content -path $filename -value (' <Mail>')
add
-content -path $filename -value (' <Component>')
add
-content -path $filename -value (' </Component>')
add
-content -path $filename -value (' </Mail>')

add
-content -path $filename -value (' <SuperOffice>')
add
-content -path $filename -value (' <Factory>')
add
-content -path $filename -value (' <DynamicLoad>')
add
-content -path $filename -value (' </DynamicLoad>')
add
-content -path $filename -value (' </Factory>')
add
-content -path $filename -value (' <Diagnostics>')
add
-content -path $filename -value (' <!-- Log errors (default True). -->')
add
-content -path $filename -value (' <add key="LogError" value="True" />')
add
-content -path $filename -value (' <!-- Log warnings (default False) -->')
add
-content -path $filename -value (' <add key="LogWarning" value="False" />')
add
-content -path $filename -value (' <!-- Log general information. This includes successful SQLs passed to the database.')
add
-content -path $filename -value (' Only permit this option while debugging a bug. This will be a severe performance hit!')
add
-content -path $filename -value (' (default False) -->')
add
-content -path $filename -value (' <add key="LogInformation" value="False" />')
add
-content -path $filename -value (' <!-- Log failed authentications (default True) -->')
add
-content -path $filename -value (' <add key="LogFailureAudit" value="True" />')
add
-content -path $filename -value (' <!-- Log sucessfull authentications (default False) -->')
add
-content -path $filename -value (' <add key="LogSuccessAudit" value="False" />')
add
-content -path $filename -value (' <!-- Log to the OS event log (default True) -->')
add
-content -path $filename -value (' <add key="LogToEventLog" value="True" />')
add
-content -path $filename -value (' <!-- Log to SuperOffice Research and Product Development (Online through a WebService) (default False) -->')
add
-content -path $filename -value (' <add key="LogToSuperOffice" value="False" />')
add
-content -path $filename -value (' <!-- Log to a LogFile (default False) -->')
add
-content -path $filename -value (' <add key="LogToFile" value="True" />')
add
-content -path $filename -value (' <!-- Folder (e.g. UNC path) where the logfile is to recide. Note that the owner of the process needs to have access to manipulate files in this folder -->')
add
-content -path $filename -value (' <add key="LogFolder" value="P:\SO7\logs\" />')
add
-content -path $filename -value (' </Diagnostics>')
add
-content -path $filename -value (' <Data>')
add
-content -path $filename -value (' <Session>')
add
-content -path $filename -value (' <add key="Mode" value="Process" />')
add
-content -path $filename -value (' </Session>')
add
-content -path $filename -value (' <Database>')
add
-content -path $filename -value (' <add key="DatabaseMajor" value="MSSQL" />')
add
-content -path $filename -value (' <add key="DatabaseMinor" value="8" />')
add
-content -path $filename -value (' <add key="Server" value="' + $dbserver + '" />')
add
-content -path $filename -value (' <add key="Database" value="' + $dbname + '" />')
add
-content -path $filename -value (' <add key="CommandTimeOut" value="300" />')
add
-content -path $filename -value (' <add key="TablePrefix" value="dbo" />')
add
-content -path $filename -value (' <add key="ConnectionString" value="Server=[@Server];Database=[@Database];User ID=[@User];Password=[@Password]" />')
add
-content -path $filename -value (' </Database>')
add
-content -path $filename -value (' <ImplicitAnonymous>')
add
-content -path $filename -value (' <add key="Allowed" value="False" />')
add
-content -path $filename -value (' <add key="DBUser" value="" />')
add
-content -path $filename -value (' <add key="DBPassword" value="" />')
add
-content -path $filename -value (' <add key="CommonDBConnection" value="True" />')
add
-content -path $filename -value (' <add key="SoUser" value="" />')
add
-content -path $filename -value (' <add key="SoPassword" value="" />')
add
-content -path $filename -value (' </ImplicitAnonymous>')
add
-content -path $filename -value (' <Explicit>')
add
-content -path $filename -value (' <add key="ExternalPersonAllowed" value="False" />')
add
-content -path $filename -value (' <add key="EmployeeAllowed" value="True" />')
add
-content -path $filename -value (' <add key="SystemAllowed" value="True" />')
add
-content -path $filename -value (' <add key="DBUser" value="' + $SOAdminUser + '" />')
add
-content -path $filename -value (' <add key="DBPassword" value="' + $SOAdminPass + '" />')
add
-content -path $filename -value (' <add key="CommonDBConnection" value="True" />')
add
-content -path $filename -value (' </Explicit>')
add
-content -path $filename -value (' </Data>')
add
-content -path $filename -value (' <Documents>')
add
-content -path $filename -value (' <!-- Location of SO_ARC ; the Windows Client will override this with a real value at runtime (the value will not be visible in the file) -->')
add
-content -path $filename -value (' <add key="ArchivePath" value="c:\SO_ARC" />')
add
-content -path $filename -value (' <!-- Location of template folder. This folder only needs to be specifies when it is other than default. -->')
add
-content -path $filename -value (' <!-- Optional: add key="TemplatePath" value="" /-->')
add
-content -path $filename -value (' <!-- Location of temporary folder for streaming files. This path must resolve to the same location for farms/culsters. -->')
add
-content -path $filename -value (' <add key="TemporaryPath" value="" />')
add
-content -path $filename -value (' <!-- Impersonate user when accessing the document archive or the temporary folder -->')
add
-content -path $filename -value (' <add key="ImpersonateUser" value="false" />')
add
-content -path $filename -value (' <!-- Name of the user to impersonate with -->')
add
-content -path $filename -value (' <add key="ArchiveUser" value="" />')
add
-content -path $filename -value (' <!-- Password of the user to impersonate with -->')
add
-content -path $filename -value (' <add key="ArchivePassword" value="" />')
add
-content -path $filename -value (' <!-- Domain of the user to impersonate with -->')
add
-content -path $filename -value (' <add key="ArchiveDomain" value="" />')
add
-content -path $filename -value (' <!-- Size of internal buffer in KB -->')
add
-content -path $filename -value (' <add key="BufferSize" value="32" />')
add
-content -path $filename -value (' </Documents>')
add
-content -path $filename -value (' </SuperOffice>')
add
-content -path $filename -value ('</configuration>')
}


function CreateSuperOfficeini([string]$Path, [string]$dbserver, [string]$dbname, [string]$DriverName){
$filename = ($Path + 'SuperOffice.ini')
if ( (Test-Path $filename) -eq $true) { Clear-Content -path $filename }

add
-content -path $filename -value ('[Client]')
add
-content -path $filename -value ('PrefMailClient=Outlook2007')
add
-content -path $filename -value ('PrefWordProcessor=Word2007')
add
-content -path $filename -value ('PrefLang=US')
add
-content -path $filename -value ('[ODBC:' + $dbname + ']')
add
-content -path $filename -value ('Database=' + $dbname)
add
-content -path $filename -value ('Driver=' + $DriverName)
add
-content -path $filename -value ('Server=' + $dbserver)
add
-content -path $filename -value ('[SuperOffice]')
add
-content -path $filename -value ('Datapath=ODBC:' + $dbname)
add
-content -path $filename -value ('Archivepath=P:\SO7\SO_ARC')
add
-content -path $filename -value ('GlobalPrefix=dbo')
}


Well, not pretty but it works … I have pretty much the same code in VB.NET and together with this nifty little class it’s a piece of cake "”cheating” SuperOffice NetServer to connect to what ever database we want. ( Thanks too this link )


Imports System.Configuration
Imports System.Reflection

Public MustInherit Class AppConfig
Implements IDisposable
Public Shared Function Change(path As String) As AppConfig
Return New ChangeAppConfig(path)
End Function

Public MustOverride Sub Dispose() Implements IDisposable.Dispose

Private Class ChangeAppConfig
Inherits AppConfig
Private ReadOnly oldConfig As String = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString()

Private disposedValue As Boolean

Public Sub New(path As String)
AppDomain.CurrentDomain.SetData(
"APP_CONFIG_FILE", path)
ResetConfigMechanism()
End Sub

Public Overrides Sub Dispose()
If Not disposedValue Then
AppDomain.CurrentDomain.SetData(
"APP_CONFIG_FILE", oldConfig)
ResetConfigMechanism()


disposedValue
= True
End If
GC.SuppressFinalize(
Me)
End Sub

Private Shared Sub ResetConfigMechanism()
GetType(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic Or BindingFlags.[Static]).SetValue(Nothing, 0)

GetType(ConfigurationManager).GetField("s_configSystem", BindingFlags.NonPublic Or BindingFlags.[Static]).SetValue(Nothing, Nothing)

GetType(ConfigurationManager).Assembly.GetTypes().Where(Function(x) x.FullName = "System.Configuration.ClientConfigPaths").First().GetField("s_current", BindingFlags.NonPublic Or BindingFlags.[Static]).SetValue(Nothing, Nothing)
End Sub
End Class
End Class

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"
}

tirsdag den 6. september 2011

Claimsbased authentication and WCF Services

Update 22-09-2011: Code samples posted here
In the last few months I’ve spend a lot of time messing with claimsbased authentication. a lot of it have been toward implementing single sign on though various social providers. But some of it have also been involving working with SharePoint 2010 and CRM 2011 and developing and calling my own WCF services from both applications and websites.

I wanted to document what I learn, as I learned it, on this blog but the time just hasn’t been on my side, but I do how ever spend a little time on a piece of code I wrote that I think a lot people will find useful and can copy’n’paste a bit from.

Most of the actions and information I need in different places are all wrapped up in 1 WCF service, I call this WCF service from both other WCF services and websites and from various applications. I found it was easier for me to just create an Class Library that could talk with this WCF service and then reference that from all my projects.

image

Most of the code is about handling active federation against any kind of claimsbased identity provider, but I also put in a bit of code to handle passive federation that is needed when working with SharePoint 2010 though code.

I have client class that in a simple way make authentication against an identity provider and receiving a claims token back. I want to go though how to use this client to get a token and what can happen, since I have seen A LOT of forum post from people getting these errors and not getting an answer that fits.

We start by creating an instance of the client and choosing what kind of encryption we want to use.

Code Snippet
  1. Dim ClaimsClient As New ClaimsAuth.Client
  2. ClaimsClient.TokenEncryption = Microsoft.IdentityModel.SecurityTokenService.KeyTypes.Symmetric

if we look in Microsoft.IdentityModel.SecurityTokenService.KeyTypes we see we can use Asymmetric, Symmetric or Bearer. Tons of post out there about this.

If you use Asymmetric you as requestor need to supply a key to encrypt the claims with. ( set "UseKey” )

If you use Symmetric the identity provider have all ready been told what certificate to use, to encrypt the claims with.

If you choose Bearer. The token get signed, but claims will not be encrypted. If a token signing certificate have been assigned on the Relying Party, claims will simply not be included at all.

When you request a token, the token gets signed (not encrypted) with a certificate installed on the Identity Provider ( ADFS ). If you add a certificate on a Relying Party Trust (RP) on the ADFS server, the claims inside the token gets encrypted with with that certificate. Only host/applications that have access to the private key of that certificate can now decrypt the token and read the claims. You don’t need to read the claims in order to authenticate your self. For instance if you have a WCF Service you want to call from within an application. You can from within that application still request a token from the ADFS server and then access the WCF service with that Token. As long as the WCF service have access to the private key and can read the claims, your application don’t need it.

If you choose Symmetric but the Relying Party on the ADFS have not been assigned a certificate to encrypt the claims with you will get

ID3037: The specified request failed.

and in the event log on the ADFS server they would also see

ID4007: The symmetric key inside the requested security token must be encrypted. To fix this, either override the SecurityTokenService.GetScope() method to assign appropriate value to Scope.EncryptingCredentials or set Scope.SymmetricKeyEncryptionRequired to false.

Either request a Bearer token or Asymmetric (not sure if you can this?) token, or add a certificate on the RP

imageimage

To make it simple. If you want to make absolutely sure your ADFS server only issues tokens to the hosts you have given the certificate with private key too, sign the tokens with this certificate by taking the public part of the certificate and save to a file and then assign it on this tab.
If you need to authenticate from many places and don’t want to struggle with distributing a certificate including its private key around. or if you don’t care others can read the claim ( you need to successfully authenticate in order to get the claims in the first place so in theory they should have access to it anyway ) leave this field blank.

To add the certificate to the ADFS server, on the computer you have the certificate you want to use for signing claims with, open certificates and add Local computer or user, depending on where you have the certificate installed. Right click it and choose open

image
Go to Details and click Copy to file

image

Accept the defaults and save the file. Then use this file when adding a certificate on the RP on the ADFS server.

If you choose to get an Bearer token you cannot reuse this key to authenticate to other RP’s by authentication with the issued token, That will fail with

The signing token XXXX has no keys. The security token is used in a context that requires it to perform cryptographic operations, but the token contains no cryptographic keys. Either the token type does not support cryptographic operations, or the particular token instance does not contain cryptographic keys. Check your configuration to ensure that cryptographically disabled token types (for example, UserNameSecurityToken) are not specified in a context that requires cryptographic operations (for example, an endorsing supporting token).

When you have a token and you want read the claims inside, you will often see errors like

ID4022: The key needed to decrypt the encrypted security token could not be resolved. Ensure that the SecurityTokenResolver is populated with the required key.

Or from a asp.net website

ID4036: The key needed to decrypt the encrypted security token could not be resolved from the following security key identifier 'XXXXX'. Ensure that the SecurityTokenResolver is populated with the required key.

I think its pretty self explaining but there's a ton of forum post’s out there where people ask for help. Again, you have a token, its valid, you can authenticate your self with it, but when you try to read the token you get the above error. You get it be course a certificate has been added on the RP on the ADFS and you haven't given WIF the certificate including private key, needed to decrypt it. If using my code, just load it and add it on the TokenSigningCertificate Property. If you see this error on a websites you are probably missing the serviceCertificate  in web.config

 

Code Snippet
  1. <microsoft.identityModel>
  2.   <service saveBootstrapTokens="true">
  3.     <certificateValidation certificateValidationMode="None" />
  4.     <serviceCertificate>
  5.       <certificateReference x509FindType="FindByThumbprint" findValue="7A41CF269D6BCDED80DDD9B6FD517E37891453B5" storeLocation="LocalMachine" storeName="My" />
  6.     </serviceCertificate>
  7.   </service>
  8. </microsoft.identityModel>

And while at those errors. if you get something down the line of

ID4175: The issuer of the security token was not recognized by the IssuerNameRegistry. To accept security tokens from this issuer, configure the IssuerNameRegistry to return a valid name for this issuer.

you are missing the certificate from the Identity Provider ( ADFS )

Code Snippet
  1. <microsoft.identityModel>
  2.   <service saveBootstrapTokens="true">
  3.     <issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
  4.       <trustedIssuers>
  5.         <add thumbprint="86AC2E62900DF9451B0596562D52F7212AC31065" name="http://adfs.wingu.dk/adfs/services/trust" />
  6.       </trustedIssuers>
  7.     </issuerNameRegistry>
  8.   </service>
  9. </microsoft.identityModel>

Back to the code, Next I choose what I want to access (realm) and who to authenticate me (identity provider / ADFS) and how I want to authenticate

Code Snippet
  1. Dim ClaimsClient As New ClaimsAuth.Client
  2. ClaimsClient.TokenEncryption = Microsoft.IdentityModel.SecurityTokenService.KeyTypes.Symmetric
  3. ClaimsClient.IdentityProvider = "https://adfs.wingu.dk/"
  4. ClaimsClient.Realm = "https://admin.wingu.dk/ssi2/"
  5. ClaimsClient.authenticateBy = MessageCredentialType.Windows
  6. 'ClaimsClient.username = txtUsername.Text
  7. 'ClaimsClient.Password = txtPassword.Text
  8. 'ClaimsClient.ClientCertificate = MyPersonalCertificate
  9. 'ClaimsClient.IssuedToken = OtherIssuedToken
  10. 'Dim ClaimsID As Microsoft.IdentityModel.Claims.ClaimsIdentity = _
  11. 'DirectCast(HttpContext.Current.User.Identity, Microsoft.IdentityModel.Claims.ClaimsIdentity)
  12. 'Dim BootstrapToken As System.IdentityModel.Tokens.SecurityToken = ClaimsID.BootstrapToken
  13. 'ClaimsClient.ActAsToken = BootstrapToken
  14. ClaimsClient.authenticate()

AuthenticateBy can be either Certificate, IssuedToken, UserName or Windows. Just for fun I showed other ways to authenticate in the remarks. On that is particular interesting is the ActAs . This is what you would normally do from within an asp.net application that needs to call an WFC service on behalf of the user. Either Authenticate by Windows or username/password form within the asp.net application and then attach the user’s bootstrap token. you need permission to do this of course. That is what the Delegation Authorization Rules are for on the RP Claims rule dialog

image

Back to the code, so inside the client class I have my authenticate function.

Code Snippet
  1. Function authenticate() As System.IdentityModel.Tokens.SecurityToken
  2.     Select Case _authenticateBy
  3.         Case MessageCredentialType.UserName : _IssuedToken = GetADFSTokenUsernamemixed()
  4.         Case MessageCredentialType.Windows : _IssuedToken = GetADFSTokenKerberos()
  5.         Case MessageCredentialType.IssuedToken
  6.             If _IssuedToken Is Nothing Then Throw New Exception("No token found to issue new token with")
  7.             _IssuedToken = GetADFSTokenIssuedToken()
  8.         Case Else : Throw New Exception("unknown authentication schema")
  9.     End Select
  10.     Return _IssuedToken
  11. End Function

most of this code can be reused against any kind of Claimsbased authentication identity provider but for now I have only done the logic for ADFS and SharePoint.
GetADFSTokenUsernamemixed and GetADFSTokenKerberos is almost the same, GetADFSTokenIssuedToken is a bit more tricky

So here they are

Code Snippet
  1. Private Function GetADFSTokenUsernamemixed() As System.IdentityModel.Tokens.SecurityToken
  2.     Dim Token As System.IdentityModel.Tokens.SecurityToken
  3.     Dim UserNameMixed As String = _IdentityProvider & "adfs/services/trust/13/usernamemixed"
  4.     Dim STSbinding = New Microsoft.IdentityModel.Protocols.WSTrust.Bindings.UserNameWSTrustBinding
  5.     STSbinding.SecurityMode = SecurityMode.TransportWithMessageCredential
  6.     Dim trustChannelFactory As New WSTrustChannelFactory(STSbinding, New EndpointAddress(UserNameMixed))
  7.     trustChannelFactory.TrustVersion = System.ServiceModel.Security.TrustVersion.WSTrust13
  8.  
  9.     trustChannelFactory.Credentials.SupportInteractive = False
  10.     trustChannelFactory.Credentials.UserName.UserName = _Username
  11.     trustChannelFactory.Credentials.UserName.Password = _Password
  12.  
  13.     Try
  14.         Dim rst As New RequestSecurityToken()
  15.         rst.RequestType = WSTrust13Constants.RequestTypes.Issue
  16.         rst.AppliesTo = New EndpointAddress(_Realm)
  17.         rst.KeyType = _TokenEncryption
  18.         rst.TokenType = _TokenType
  19.  
  20.         If _ClientCertificate IsNot Nothing Then
  21.             Dim clause As System.IdentityModel.Tokens.SecurityKeyIdentifierClause = _
  22.                 New System.IdentityModel.Tokens.X509RawDataKeyIdentifierClause(_ClientCertificate)
  23.  
  24.             rst.UseKey = New UseKey(New System.IdentityModel.Tokens.SecurityKeyIdentifier(clause), _
  25.                                      New System.IdentityModel.Tokens.X509SecurityToken(_ClientCertificate))
  26.         End If
  27.  
  28.         'This part will give you identity of logged in user
  29.         If _ActAs IsNot Nothing Then rst.ActAs = _ActAs
  30.  
  31.         If _requestClaims.Count > 0 Then
  32.             For Each claim In _requestClaims
  33.                 rst.Claims.Add(claim)
  34.             Next
  35.         End If
  36.         Dim channel = trustChannelFactory.CreateChannel()
  37.         Dim rstr As RequestSecurityTokenResponse = Nothing
  38.         Token = channel.Issue(rst, rstr)
  39.     Catch ex As Exception
  40.         Throw New Exception(ex.Message, ex)
  41.     Finally
  42.         Try
  43.             If trustChannelFactory.State = CommunicationState.Faulted Then
  44.                 trustChannelFactory.Abort()
  45.             Else
  46.                 trustChannelFactory.Close()
  47.             End If
  48.         Catch generatedExceptionName As Exception
  49.         End Try
  50.     End Try
  51.     Return Token
  52. End Function
  53.  
  54. Private Function GetADFSTokenKerberos() As System.IdentityModel.Tokens.SecurityToken
  55.     Dim Token As System.IdentityModel.Tokens.SecurityToken
  56.     Dim KerberosMixed As String = _IdentityProvider & "adfs/services/trust/13/kerberosmixed"
  57.     Dim STSbinding = New Microsoft.IdentityModel.Protocols.WSTrust.Bindings.KerberosWSTrustBinding
  58.     STSbinding.SecurityMode = SecurityMode.TransportWithMessageCredential
  59.  
  60.     Dim trustChannelFactory As New WSTrustChannelFactory(STSbinding, New EndpointAddress(KerberosMixed))
  61.  
  62.     trustChannelFactory.TrustVersion = System.ServiceModel.Security.TrustVersion.WSTrust13
  63.     trustChannelFactory.Credentials.SupportInteractive = False
  64.     trustChannelFactory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation
  65.     trustChannelFactory.Credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials
  66.  
  67.     Try
  68.         Dim rst As New RequestSecurityToken()
  69.         rst.RequestType = WSTrust13Constants.RequestTypes.Issue
  70.         rst.AppliesTo = New EndpointAddress(_Realm)
  71.         rst.KeyType = _TokenEncryption
  72.         rst.TokenType = _TokenType
  73.         If _ActAs IsNot Nothing Then rst.ActAs = _ActAs
  74.  
  75.         If _requestClaims.Count > 0 Then
  76.             For Each claim In _requestClaims
  77.                 rst.Claims.Add(claim)
  78.             Next
  79.         End If
  80.         Dim channel = trustChannelFactory.CreateChannel()
  81.         Dim rstr As RequestSecurityTokenResponse = Nothing
  82.         Token = channel.Issue(rst, rstr)
  83.         Dim t = rstr.RequestedSecurityToken.SecurityToken
  84.         Dim s As String = ""
  85.  
  86.     Catch ex As Exception
  87.         Throw New Exception(ex.Message, ex)
  88.     Finally
  89.         Try
  90.             If trustChannelFactory.State = CommunicationState.Faulted Then
  91.                 trustChannelFactory.Abort()
  92.             Else
  93.                 trustChannelFactory.Close()
  94.             End If
  95.         Catch generatedExceptionName As Exception
  96.         End Try
  97.     End Try
  98.     Return Token
  99. End Function
  100.  
  101. Private Function GetADFSTokenIssuedToken() As System.IdentityModel.Tokens.SecurityToken
  102.     Try
  103.         Dim Token As System.IdentityModel.Tokens.SecurityToken
  104.         Dim IssuedtokenMixed As String = _IdentityProvider & "adfs/services/trust/13/issuedtokenmixedsymmetricbasic256"
  105.  
  106.         Dim binding = New Microsoft.IdentityModel.Protocols.WSTrust.Bindings.IssuedTokenWSTrustBinding()
  107.         binding.SecurityMode = SecurityMode.TransportWithMessageCredential
  108.  
  109.         Dim factory = New WSTrustChannelFactory(binding, New EndpointAddress(IssuedtokenMixed))
  110.         factory.TrustVersion = TrustVersion.WSTrust13
  111.         factory.Credentials.SupportInteractive = False
  112.  
  113.         Dim rst = New RequestSecurityToken() With { _
  114.          .RequestType = WSTrust13Constants.RequestTypes.Issue, _
  115.          .AppliesTo = New EndpointAddress(_Realm), _
  116.          .KeyType = WSTrust13Constants.KeyTypes.Symmetric _
  117.         }
  118.         rst.TokenType = _TokenType
  119.         rst.KeyType = _TokenEncryption  
  120.         factory.ConfigureChannelFactory()
  121.  
  122.         If _requestClaims.Count > 0 Then
  123.             For Each claim In _requestClaims
  124.                 rst.Claims.Add(claim)
  125.             Next
  126.         End If
  127.  
  128.         Dim channel = factory.CreateChannelWithIssuedToken(_IssuedToken)
  129.         Token = channel.Issue(rst)
  130.         Return Token
  131.     Catch ex As Exception
  132.         Throw ex
  133.     End Try
  134. End Function

I need to wrap up a few more loose ends and add a few comments but the class library and a simple test application will be available for download on this blog in a few days

søndag den 4. september 2011

Web services and wildcard certificate

I’m fiddling with web services that uses claims based authentication, and spend a few hours banging my head against the wall with this scenario.

Image you have the following code

 

Code Snippet
  1. Dim binding = New WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential)
  2. binding.Security.Message.EstablishSecurityContext = False
  3. binding.Security.Mode = WSFederationHttpSecurityMode.Message
  4. Dim factory As New ChannelFactory(Of wsClaimsCloudAPI.ClaimsCloudAPIChannel)(binding, "http://admin.wingu.dk/CloudAPI/ClaimsCloudAPI.svc")
  5. factory.ConfigureChannelFactory()   '(Of wsClaimsCloudAPI.ClaimsCloudAPIChannel)()
  6. factory.Credentials.SupportInteractive = False
  7. Dim channel = factory.CreateChannelWithIssuedToken(Token)
  8. Dim s = channel.getToken
  9. MsgBox(s)
and get this error back

Identity check failed for outgoing message. The expected DNS identity of the remote endpoint was 'admin.wingu.dk' but the remote endpoint provided DNS claim 'wingu.dk'. If this is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'wingu.dk' as the Identity property of EndpointAddress when creating channel proxy.

m using a wildcard certificate on the webserver and I guess that’s what confusing things. Some people claim you can fix this by setting the host identity on the web service binding on the server, but that didn’t seem to work for me. but doesn’t matter, the error it self explains what to do. Explicitly specify the identity. so the code becomes

Code Snippet
  1. Dim EndpointURI As New Uri("http://admin.wingu.dk/CloudAPI/ClaimsCloudAPI.svc")
  2. Dim EndpointIdentity As EndpointIdentity = EndpointIdentity.CreateDnsIdentity("wingu.dk")
  3. Dim remoteAddress As New EndpointAddress(EndpointURI, EndpointIdentity, New System.ServiceModel.Channels.AddressHeaderCollection)
  4. Dim factory As New ChannelFactory(Of wsClaimsCloudAPI.ClaimsCloudAPIChannel)(binding, remoteAddress)

And everything works like a charm.

Note if using CreateChannelWithIssuedToken() and supply nothing or an illegal token, you will get back.

The address of the security token issuer is not specified. An explicit issuer address must be specified in the binding for target 'http://admin.wingu.dk/CloudAPI/ClaimsCloudAPI.svc' or the local issuer address must be configured in the credentials.

So make sure the token your testing with is valid.