使用WCF和.net 4.5的自定义ServiceHostFactory

时间:2013-08-05 02:36:45

标签: wcf .net-4.5 wif

尝试创建自定义ServiceHostFactory并查看事件查看器中记录的以下错误。

WebHost无法处理请求。  发件人信息:System.ServiceModel.ServiceHostingEnvironment + HostingManager / 38902774  例外:System.ServiceModel.ServiceActivationException:服务' /services/clientservices.svc'由于编译期间的异常,无法激活。异常消息是:安全令牌管理器无法为需求创建令牌身份验证器&System; Service.ServiceModel.Security.Tokens.RecipientServiceModelSecurityTokenRequirement: PropertyName:http://schemas.microsoft.com/ws/2006/05/identitymodel/securitytokenrequirement/KeyType PropertyValue:SymmetricKey

PropertyName:http://schemas.microsoft.com/ws/2006/05/identitymodel/securitytokenrequirement/KeyUsage PropertyValue:签名

PropertyName:http://schemas.microsoft.com/ws/2006/05/identitymodel/securitytokenrequirement/RequireCryptographicToken PropertyValue:True

PropertyName:http://schemas.microsoft.com/ws/2006/05/identitymodel/securitytokenrequirement/KeySize PropertyValue:0

PropertyName:http://schemas.microsoft.com/ws/2006/05/identitymodel/securitytokenrequirement/IsOptionalTokenProperty PropertyValue:错误 PropertyName:http://schemas.microsoft.com/ws/2006/05/servicemodel/securitytokenrequirement/SupportSecurityContextCancellation PropertyValue:False

PropertyName:http://schemas.microsoft.com/ws/2006/05/servicemodel/securitytokenrequirement/IsInitiator PropertyValue:False

PropertyName:http://schemas.microsoft.com/ws/2006/05/servicemodel/securitytokenrequirement/SecurityBindingElement PropertyValue:System.ServiceModel.Channels.SymmetricSecurityBindingElement: DefaultAlgorithmSuite:Basic256 IncludeTimestamp:True KeyEntropyMode:CombinedEntropy MessageSecurityVersion:WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11 SecurityHeaderLayout:严格 ProtectTokens:错 EndpointSupportingTokenParameters:   赞同[0]     System.ServiceModel.Security.Tokens.IssuedSecurityTokenParameters:     InclusionMode:AlwaysToRecipient     ReferenceStyle:内部     RequireDerivedKeys:是的     TokenType:samlTokenType     KeyType:SymmetricKey     KeySize:0     IssuerAddress:https://sirona-locl-use.accesscontrol.windows.net/v2/wstrust/13/certificate     IssuerMetadataAddress:null     DefaultMessgeSecurityVersion:null     UseStrTransform:False     IssuerBinding:null     ClaimTypeRequirements:无   没有签名的令牌。   没有签名的加密令牌。   没有签署认可令牌。 OptionalEndpointSupportingTokenParameters:   没有认可代币。   没有签名的令牌。   没有签名的加密令牌。   没有签署认可令牌。 OperationSupportingTokenParameters:无 OptionalOperationSupportingTokenParameters:none MessageProtectionOrder:SignBeforeEncryptAndEncryptSignature RequireSignatureConfirmation:是的 ProtectionTokenParameters:System.ServiceModel.Security.Tokens.X509SecurityTokenParameters:   InclusionMode:从不   ReferenceStyle:内部   RequireDerivedKeys:是的   X509ReferenceStyle:指纹

...

以下是我正在使用的创建servicehostfactory

的代码

public class WSTrustServiceHostFactory : ServiceHostFactory
{

     public static Binding CreateIssuedTokenForCertificateBinding(string acsCertificateEndpoint)
    {
        //http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0
        BindingElementCollection bec = new BindingElementCollection();
        bec.Add(SecurityBindingElement.
            CreateIssuedTokenForCertificateBindingElement(
            new IssuedSecurityTokenParameters("samlTokenType", new EndpointAddress(acsCertificateEndpoint))));
        bec.Add(new TextMessageEncodingBindingElement());
        bec.Add(new HttpTransportBindingElement());
        return new CustomBinding(bec);
    }


    protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        if (serviceType == null)
            throw new ArgumentNullException("serviceType cannot be null");

        if (baseAddresses.Count() == 0)
            throw new ArgumentException("baseAddresses must have at least 1 member.");

        string acsCertificateEndpoint = "https://acs url ...."



        WSFederationHttpSecurityMode securityMode = WSFederationHttpSecurityMode.TransportWithMessageCredential;
        if ( debugging )
        {
            securityMode = WSFederationHttpSecurityMode.Message;
        }


        ServiceHost serviceHost = new ServiceHost(serviceType, baseAddresses);

        //IssuedTokenWSTrustBinding issuedTokenWSTrustBinding = new IssuedTokenWSTrustBinding(
        //    new CertificateWSTrustBinding(securityMode),
        //    new EndpointAddress(acsCertificateEndpoint));


        System.IdentityModel.Configuration.IdentityConfiguration serviceConfiguration = 
            new System.IdentityModel.Configuration.IdentityConfiguration();



            serviceHost.Credentials.ServiceCertificate.Certificate =  // fetch acs decryption certificate;


            acsSigningCertificate = //fetch acs signing certificate.

        ConfigurationBasedIssuerNameRegistry issuerNameRegistry = new ConfigurationBasedIssuerNameRegistry();

        issuerNameRegistry.AddTrustedIssuer(acsSigningCertificate.Thumbprint, acsSigningCertificate.SubjectName.Name);
        serviceConfiguration.IssuerNameRegistry = issuerNameRegistry;

        serviceConfiguration.AudienceRestriction.AudienceMode = System.IdentityModel.Selectors.AudienceUriMode.Always;

        serviceConfiguration.CertificateValidationMode = X509CertificateValidationMode.None;

        serviceConfiguration.SecurityTokenHandlers.AddOrReplace(new Saml2SecurityTokenHandler());

        // wif 3.5 //serviceHost.AddServiceEndpoint(serviceType.GetInterfaces()[0], issuedTokenWSTrustBinding, String.Empty);
        serviceHost.AddServiceEndpoint(serviceType.GetInterfaces()[0], CreateIssuedTokenForCertificateBinding(acsCertificateEndpoint), String.Empty);

        //var creds = serviceHost.Description.Behaviors.Find<ServiceCredentials>();
        // creds.UseIdentityConfiguration = true;
        //creds.IdentityConfiguration = serviceConfiguration;

        serviceHost.Credentials.UseIdentityConfiguration = true;
        serviceHost.Credentials.IdentityConfiguration = serviceConfiguration;
        // <--wif 3.5 FederatedServiceCredentials.ConfigureServiceHost(serviceHost, serviceConfiguration);  -->

        if (RegionConfiguration.GetSetting<bool>(Settings.CLIENTSERVICES_INCLUDE_EXCEPTION_DETAILS))
        {
            if (serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>() == null)
            {
                serviceHost.Description.Behaviors.Add(new ServiceDebugBehavior());
            }
            serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
        }

        return serviceHost;
    }

}

public class WSTrustServiceHostFactory : ServiceHostFactory { public static Binding CreateIssuedTokenForCertificateBinding(string acsCertificateEndpoint) { //http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0 BindingElementCollection bec = new BindingElementCollection(); bec.Add(SecurityBindingElement. CreateIssuedTokenForCertificateBindingElement( new IssuedSecurityTokenParameters("samlTokenType", new EndpointAddress(acsCertificateEndpoint)))); bec.Add(new TextMessageEncodingBindingElement()); bec.Add(new HttpTransportBindingElement()); return new CustomBinding(bec); } protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { if (serviceType == null) throw new ArgumentNullException("serviceType cannot be null"); if (baseAddresses.Count() == 0) throw new ArgumentException("baseAddresses must have at least 1 member."); string acsCertificateEndpoint = "https://acs url ...." WSFederationHttpSecurityMode securityMode = WSFederationHttpSecurityMode.TransportWithMessageCredential; if ( debugging ) { securityMode = WSFederationHttpSecurityMode.Message; } ServiceHost serviceHost = new ServiceHost(serviceType, baseAddresses); //IssuedTokenWSTrustBinding issuedTokenWSTrustBinding = new IssuedTokenWSTrustBinding( // new CertificateWSTrustBinding(securityMode), // new EndpointAddress(acsCertificateEndpoint)); System.IdentityModel.Configuration.IdentityConfiguration serviceConfiguration = new System.IdentityModel.Configuration.IdentityConfiguration(); serviceHost.Credentials.ServiceCertificate.Certificate = // fetch acs decryption certificate; acsSigningCertificate = //fetch acs signing certificate. ConfigurationBasedIssuerNameRegistry issuerNameRegistry = new ConfigurationBasedIssuerNameRegistry(); issuerNameRegistry.AddTrustedIssuer(acsSigningCertificate.Thumbprint, acsSigningCertificate.SubjectName.Name); serviceConfiguration.IssuerNameRegistry = issuerNameRegistry; serviceConfiguration.AudienceRestriction.AudienceMode = System.IdentityModel.Selectors.AudienceUriMode.Always; serviceConfiguration.CertificateValidationMode = X509CertificateValidationMode.None; serviceConfiguration.SecurityTokenHandlers.AddOrReplace(new Saml2SecurityTokenHandler()); // wif 3.5 //serviceHost.AddServiceEndpoint(serviceType.GetInterfaces()[0], issuedTokenWSTrustBinding, String.Empty); serviceHost.AddServiceEndpoint(serviceType.GetInterfaces()[0], CreateIssuedTokenForCertificateBinding(acsCertificateEndpoint), String.Empty); //var creds = serviceHost.Description.Behaviors.Find<ServiceCredentials>(); // creds.UseIdentityConfiguration = true; //creds.IdentityConfiguration = serviceConfiguration; serviceHost.Credentials.UseIdentityConfiguration = true; serviceHost.Credentials.IdentityConfiguration = serviceConfiguration; // <--wif 3.5 FederatedServiceCredentials.ConfigureServiceHost(serviceHost, serviceConfiguration); --> if (RegionConfiguration.GetSetting<bool>(Settings.CLIENTSERVICES_INCLUDE_EXCEPTION_DETAILS)) { if (serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>() == null) { serviceHost.Description.Behaviors.Add(new ServiceDebugBehavior()); } serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true; } return serviceHost; } } 有什么想法在这里发生吗?