IdentityServer / IdentityServer3.WsFederation

WS-Federation Plugin for IdentityServer v3
Apache License 2.0
25 stars 36 forks source link

WS-Federation signin response exception (SharePoint 2013) #85

Open vizvtwow opened 8 years ago

vizvtwow commented 8 years ago

Hello,

i've configured the IdentityServer3 (2.5.4) with IdentityServer3.WsFederation plugin (2.6.0) as trusted identity provider for SharePoint 2013. Both applications using SSL are running on different machines (Windows Server 2012) within test environment. The following exception occured in the function CreateSecurityToken in class SignInResponseGenerator. The authentication process at ADFS is working without any problems.

First i've supposed some permission issues with the signing certificate and private key access on Windows Server 2012. But it doesn't seems so. The identity of the default application pool of the identity server within the IIS has been set to 'Network Service'. The details of the exception message in combination with the global member are not very helpful.

Exception

System.Security.Cryptography.CryptographicException: m_safeCertContext is an invalid handle.

I've attached the important configuration parts and log file.

Log

w3wp.exe Information: 0 : 2016-11-11 12:55:49.326 +01:00 [Information] rendering login page
w3wp.exe Information: 0 : 2016-11-11 12:55:51.411 +01:00 [Information] External login requested for provider: "adfs"
w3wp.exe Information: 0 : 2016-11-11 12:55:51.412 +01:00 [Information] Triggering challenge for external identity provider
w3wp.exe Information: 0 : 2016-11-11 12:55:51.689 +01:00 [Information] Clearing tokens
w3wp.exe Information: 0 : 2016-11-11 12:56:01.750 +01:00 [Information] Clearing tokens
w3wp.exe Information: 0 : 2016-11-11 12:56:10.400 +01:00 [Information] CORS request made for path: "/" from origin: "https://adfs.***.local" but rejected because invalid CORS path
w3wp.exe Information: 0 : 2016-11-11 12:56:10.447 +01:00 [Information] Callback invoked from external identity provider
w3wp.exe Information: 0 : 2016-11-11 12:56:10.449 +01:00 [Information] external user provider: "adfs", provider ID: "***@***.local"
w3wp.exe Information: 0 : 2016-11-11 12:56:10.449 +01:00 [Information] External identity successfully validated by user service
w3wp.exe Information: 0 : 2016-11-11 12:56:10.449 +01:00 [Information] Calling PostAuthenticateAsync on the user service
w3wp.exe Information: 0 : 2016-11-11 12:56:10.449 +01:00 [Information] issuing primary signin cookie
w3wp.exe Information: 0 : 2016-11-11 12:56:10.449 +01:00 [Information] redirecting to: https://test_auth.***.local/IdentityServer/wsfed?wa=wsignin1.0&wtrealm=urn:identityServer&wctx=https:%2f%2ftest_sps.***.local%2f_layouts%2f15%2fAuthenticate.aspx%3fSource%3d%252F
w3wp.exe Information: 0 : 2016-11-11 12:56:10.492 +01:00 [Information] Start WS-Federation request
2016-11-11 12:56:10.492 +01:00 [Debug] AbsoluteUri: ["https://test_auth.***.local/IdentityServer/wsfed?wa=wsignin1.0&wtrealm=urn%3aidentityServer&wctx=https%3a%2f%2ftest_sps.***.local%2f_layouts%2f15%2fAuthenticate.aspx%3fSource%3d%252F"]
2016-11-11 12:56:10.492 +01:00 [Debug] PublicUri: [https://test_auth.***.local/IdentityServer/wsfed?wa=wsignin1.0&wtrealm=urn:identityServer&wctx=https:%2f%2ftest_sps.***.local%2f_layouts%2f15%2fAuthenticate.aspx%3fSource%3d%252F]
w3wp.exe Information: 0 : 2016-11-11 12:56:10.492 +01:00 [Information] WsFederation signin request
w3wp.exe Information: 0 : 2016-11-11 12:56:10.493 +01:00 [Information] Start WS-Federation signin request validation
2016-11-11 12:56:10.561 +01:00 [Debug] Calling into custom validator: IdentityServer3.WsFederation.Services.DefaultCustomWsFederationRequestValidator
w3wp.exe Information: 0 : 2016-11-11 12:56:10.561 +01:00 [Information] End WS-Federation signin request validation
"{
  \"Realm\": \"urn:identityServer\",
  \"ReplyUrl\": \"https://test_auth.***.local/IdentityServer\"
}"
w3wp.exe Information: 0 : 2016-11-11 12:56:10.561 +01:00 [Information] Creating WS-Federation signin response
w3wp.exe Error: 0 : 2016-11-11 12:56:10.598 +01:00 [Error] Unhandled exception
System.Security.Cryptography.CryptographicException: m_safeCertContext is an invalid handle.
   at System.Security.Cryptography.X509Certificates.X509Certificate.get_Issuer()
   at System.IdentityModel.Tokens.X509SecurityToken.CreateKeyIdentifierClause[T]()
   at System.IdentityModel.Tokens.X509EncryptingCredentials..ctor(X509SecurityToken token)
   at System.IdentityModel.Tokens.EncryptedKeyEncryptingCredentials..ctor(X509Certificate2 certificate)
   at IdentityServer3.WsFederation.ResponseHandling.SignInResponseGenerator.CreateSecurityToken(SignInValidationResult validationResult, ClaimsIdentity outgoingSubject)
   at IdentityServer3.WsFederation.ResponseHandling.SignInResponseGenerator.<GenerateResponseAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at IdentityServer3.WsFederation.WsFederationController.<ProcessSignInAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

WsFederationAuthenticationOptions

var adfs = new WsFederationAuthenticationOptions
{
    AuthenticationType = "adfs",
    Caption = "ADFS",
    SignInAsAuthenticationType = signInAsType,
    MetadataAddress = "https://TEST_AUTH.***.local/FederationMetadata/2007-06/FederationMetadata.xml",
    Wtrealm = "urn:identityServer"
};

app.UseWsFederationAuthentication(adfs);

RelyingParty

public static IEnumerable<RelyingParty> Get()
{
    return new List<RelyingParty>
    {
        new RelyingParty
        {
            Realm = "urn:identityServer",
            Enabled = true,
            TokenType = TokenTypes.Saml11TokenProfile11,
            TokenLifeTime = 1000,
            DefaultClaimTypeMappingPrefix = "https://schema.org/",
            ReplyUrl = "https://test_sps/", //_trust/",
            SignatureAlgorithm = SecurityAlgorithms.RsaSha1Signature,
            DigestAlgorithm = SecurityAlgorithms.Sha1Digest,
            ClaimMappings = new Dictionary<string, string>
            {
                { "sub", ClaimTypes.NameIdentifier },
                { "name", ClaimTypes.Name },
                { "given_name", ClaimTypes.GivenName },
                { "family_name", ClaimTypes.Surname },
                { "email", ClaimTypes.Email },
                { "upn", ClaimTypes.Upn }
            }
        }
    };
}

PowerShell script to append trusted provider

## DEFINE FUNCTIONS
function findObjectItem($object, $name, $value) {
    for ($i=0; $i -lt $object.length; $i++) {
        $item = $object[$i]
        if ($item.$name -eq $value) {
            return $item
        }
    }
}

## PROPERTIES
$realm = "urn:identityServer"
$signinurl = "https://test_auth.***.local/IdentityServer/wsfed"
$description = "This ist  Provide description here"
$url = "http://test_sps/"
$metadataurl = "https://test_auth.***.local/IdentityServer/wsfed/metadata"

## LOAD FEDERATION METADATA
$fedmd = Invoke-WebRequest -Uri $metadataurl
$fedmdXml = New-Object Xml
$fedmdXml.LoadXml($fedmd.Content)
$base64 = $fedmdXml.EntityDescriptor.RoleDescriptor.KeyDescriptor.KeyInfo.X509Data.X509Certificate
$base64| Out-File -FilePath temp.cer -Append:$false
$cert = Get-PfxCertificate -FilePath temp.cer
Remove-Item temp.cer

## ADD TRUST IN SP
asnp *sh*
$name = $fedmdXml.EntityDescriptor.RoleDescriptor.GetAttribute("ServiceDescription")[0]
$auth = findObjectItem -object $(Get-SPTrustedRootAuthority) -name "Name" -value $name
if ($auth) {
   Remove-SPTrustedRootAuthority -Identity $auth
}
New-SPTrustedRootAuthority -Name $name -Certificate $cert | Out-Null

## CREATE TRUSTED IDENTITY TOKEN ISSUER
$map1 = New-SPClaimTypeMapping "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" `
    -IncomingClaimTypeDisplayName "Email" -SameAsIncoming 
$map2 = New-SPClaimTypeMapping "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" `
    -IncomingClaimTypeDisplayName "Role" -SameAsIncoming
$map3 = New-SPClaimTypeMapping "http://schemas.microsoft.com/ws/2008/06/identity/claims/givenname" `
    -IncomingClaimTypeDisplayName "GivenName" -SameAsIncoming
$map4 = New-SPClaimTypeMapping "http://schemas.microsoft.com/ws/2008/06/identity/claims/surname" `
    -IncomingClaimTypeDisplayName "Surname" -SameAsIncoming
$issuer = findObjectItem -object $(Get-SPTrustedIdentityTokenIssuer) -name "Name" -value $name
if ($issuer) {
    Remove-SPTrustedIdentityTokenIssuer -Identity $issuer
}
$issuer = New-SPTrustedIdentityTokenIssuer -Name $name -Description $description -Realm $realm `
    -ImportTrustCertificate $cert -ClaimsMappings $map1,$map2,$map3,$map4 -SignInUrl $signinurl `
    -IdentifierClaim $map1.InputClaimType

SharePoint External Authentication Provider enabled

05_sharepoint_external_authentication_provider

Properties of the Certificate for token signing

06_token_signing_certificate_properties

Maybe there is someone with experience of adding IdentityServer3 as trusted provider to SharePoint 2013. A new sample in the repository would also be helpful. Most entries on GitHub and Stackoverflow are deprecated or affect IdentityServer2.

An example for the creation of the signing certificate with New-SelfSignedCertificate (PowerShell) would also be nice. The only example i found was made for MakeCert. Microsoft says: "MakeCert is deprecated. To create self-signed certificates, use the Powershell Cmdlet New-SelfSignedCertificate".

Thanks for the help in advance.

scottbrady91 commented 7 years ago

It looks like IdentityServer is trying to pull in an encryption certificate, but you don't have one. If you are storing wsfed configuration in a database, make sure the encryption certificate is set to null, not just whitespace.

codestellar commented 7 years ago

@vizvtwow Should this issue be closed? Can you please let us know what are the steps performed in case the issue has been fixed and if not what all you have tried?

scottbrady91 commented 7 years ago

I think if this was an issue on our side, it would have been solved by https://github.com/IdentityServer/IdentityServer3.WsFederation.EntityFramework/pull/1

codestellar commented 7 years ago

@scottbrady91 Thanks a lot. Its working for me using link the link you provided.