How to make a secure WCF Service with AD FS - wcf

I'm trying to add claims-based security on a WCF service, using ADFS. I've succesfully done so for a Web Application (Passive federation), but I find myself stuck due to lack of documentation on the subject.
I've been playing with the Web.Config files to make it work... however, I just seem to be going from one problem to the next. Here's the Security Part of the client side web.config:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior>
<clientCredentials>
<serviceCertificate>
<authentication certificateValidationMode="None"/>
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<ws2007FederationHttpBinding>
<binding name="WS2007FederationHttpBinding_IService1">
<security mode="Message">
<message>
<issuer address="https://myIssuer/adfs/services/trust/13/windows" binding="basicHttpsBinding" />
<issuerMetadata address="https://myIssuer/adfs/services/trust/mex" />
<tokenRequestParameters>
<trust:SecondaryParameters xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">
<trust:KeyType xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey</trust:KeyType>
<trust:KeySize xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">256</trust:KeySize>
<trust:KeyWrapAlgorithm xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p</trust:KeyWrapAlgorithm>
<trust:EncryptWith xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/04/xmlenc#aes256-cbc</trust:EncryptWith>
<trust:SignWith xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2000/09/xmldsig#hmac-sha1</trust:SignWith>
<trust:CanonicalizationAlgorithm xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/10/xml-exc-c14n#</trust:CanonicalizationAlgorithm>
<trust:EncryptionAlgorithm xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/04/xmlenc#aes256-cbc</trust:EncryptionAlgorithm>
</trust:SecondaryParameters>
</tokenRequestParameters>
</message>
</security>
</binding>
</ws2007FederationHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost/Services/Service1.svc"
binding="ws2007FederationHttpBinding" bindingConfiguration="WS2007FederationHttpBinding_IService1"
contract="ServiceRef.XISecurity.IService1" name="WS2007FederationHttpBinding_IService1" />
</client>
</system.serviceModel>
I'm unsure if I'm using the correct binding type or endpoint here. When I run the following code:
Service1Client obj = new Service1Client();
string str = obj.GetData(5);
I get the following exception:
Addressing Version 'AddressingNone (http://schemas.microsoft.com/ws/2005/05/addressing/none)' is not supported.
Here's my web.config on the server side
<configuration>
<configSections>
<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="ida:FederationMetadataLocation" value="https://myIssuer/FederationMetadata/2007-06/FederationMetadata.xml" />
<add key="ida:ProviderSelection" value="productionSTS" />
</appSettings>
<location path="FederationMetadata">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceCredentials useIdentityConfiguration="true">
<!--Certificate added by Identity and Access Tool for Visual Studio.-->
<serviceCertificate findValue="CN=localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectDistinguishedName" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add scheme="http" binding="ws2007FederationHttpBinding" />
<!--<add binding="basicHttpsBinding" scheme="https" />-->
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<bindings>
<ws2007FederationHttpBinding>
<binding name="">
<security mode="Message">
<message>
<issuerMetadata address="https://myIssuer/adfs/services/trust/mex" />
</message>
</security>
</binding>
</ws2007FederationHttpBinding>
</bindings>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true" />
</system.webServer>
<system.identityModel>
<identityConfiguration>
<audienceUris>
<add value="http://localhost:2017/Service1.svc" />
</audienceUris>
<issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
<authority name="http://myIssuer/adfs/services/trust">
<keys>
<add thumbprint="7502424014D0A1BD87A5DEEF0D1EB13390101F07" />
</keys>
<validIssuers>
<add name="http://myIssuer/adfs/services/trust" />
</validIssuers>
</authority>
</issuerNameRegistry>
<!--certificationValidationMode set to "None" by the the Identity and Access Tool for Visual Studio. For development purposes.-->
<certificateValidation certificateValidationMode="None" />
</identityConfiguration>
</system.identityModel>
</configuration>
My first question is: is there a good, step by step tutorial on how to set up my web.config files for that? Ideally one with .NET 4.5?
Second question: I'm really confused about which binding ADFS endpoint or binding to use. Here's what it's currently set to.
<issuer address="https://myIssuer/adfs/services/trust/13/windows" binding="basicHttpsBinding" />
Any help would be hugely appreciated. Thank you

In answer to your second question you can find some information on endpoints at http://technet.microsoft.com/en-us/library/adfs2-help-endpoints(WS.10).aspx. An endpoint basically specifies an address that you can use to communicate with the ADFS server. The type of endpoint will also tell you some things about its requirements such as whether you need to provide a certificate or a username.
There is also a mapping between endpoints and WIF bindings at http://blogs.msdn.com/b/alikl/archive/2011/10/01/how-to-use-ad-fs-endpoints-when-developing-claims-aware-wcf-services-using-wif.aspx. This has been helpful to me when I have been using code instead of the configuration file to communicate with the endpoint.

Related

Request Entity Too Large I've tried everything

I've searched this and tried everything that SO has to offer. I've been at this for quite some time and I cannot find in my web.config what is wrong. I'm getting the message "The remote server returned an unexpected response: (413) Request Entity Too Large."
I can't for the life of me figure out what I'm doing wrong! Help!
Here is my web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.web>
<compilation targetFramework="4.6" debug="true">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="DefaultCache" duration="60" varyByParam="none" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
<authentication mode="Windows" />
<pages controlRenderingCompatibilityVersion="4.0" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="3521478366" />
</requestFiltering>
</security>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding" allowCookies="true"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647">
<readerQuotas maxDepth="32"
maxArrayLength="2147483647"
maxStringContentLength="2147483647"/>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="false" />
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="TruckService.TruckService">
<endpoint
binding="basicHttpBinding"
bindingConfiguration="BasicHttpEndpointBinding"
contract="TruckService.ITruckService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<directoryBrowse enabled="false" showFlags="Date, Time, Size, Extension" />
</system.webServer>
<connectionStrings>
<!-- removed for security purposes -->
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
What I've tried:
how to increase MaxReceivedMessageSize when calling a WCF from C#
The maximum message size quota for incoming messages (65536) has been exceeded
First of all, you need to keep the file transfer format of the server-side and the client-side the same. Deviation may cause this problem.
In addition, on the premise that increasing the message size and buffer size does not work, you can try to change a value: maxitemsinobjectgraph like this:
<behaviors>
<endpointBehaviors>
<behavior name="restBehavior">
<dataContractSerializer maxItemsInObjectGraph="1365536" />
</behavior>
</behaviors>
<serviceBehaviors>
<behavior name="restBehavior">
<dataContractSerializer maxItemsInObjectGraph="1365536" />
</behavior>
</serviceBehaviors>

WCF Service to get data from SQL database not hosting properly

I have the WCF Service to getdata from the SQL Database for my android application. the service works fine for the WCFTestClient but its not Hosting in IIS,
HTTP Error 500.24 - Internal Server Error
An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.
when trying to browse from IIS.
adding website in IIS
after adding new website in IIS and trying to browse
my service config file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings />
<!--
For a description of web.config changes for .NET 4.5 see http://go.microsoft.com/fwlink/?LinkId=235367.
The following attributes can be set on the <httpRuntime> tag.
<system.Web>
<httpRuntime targetFramework="4.5" />
</system.Web>
-->
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<pages controlRenderingCompatibilityVersion="4.0" clientIDMode="AutoID" />
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="restLargeBinding" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" transferMode="Streamed">
<readerQuotas maxStringContentLength="2147483647"/>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<!--<serviceBehaviors>
<behavior>
--><!--To avoid disclosing metadata information, set the values below to false before deployment--><!--
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
--><!--To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information--><!--
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>-->
<endpointBehaviors>
<behavior name ="myWebEndPointBehaviour">
<webHttp automaticFormatSelectionEnabled="true" defaultBodyStyle="Bare" defaultOutgoingResponseFormat="Json" helpEnabled="true"/>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="mybehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</serviceBehaviors>
</behaviors>
<!--</behaviors>-->
<services>
<service name="FeedbackSrvc.Service1" behaviorConfiguration="mybehaviour">
<endpoint address="" contract="FeedbackSrvc.IService1" binding ="webHttpBinding" bindingConfiguration="restLargeBinding" behaviorConfiguration="myWebEndPointBehaviour"/>
<endpoint address="mex" contract="FeedbackSrvc.IService1" binding="mexHttpBinding" />
</service>
</services>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</configuration>
There is no error in your webconfig file, I have tested it.This is due to an IIS configuration error.I suggest you try to change the application pool setting, turn the managed pipeline mode into Classic, or you could use the ASP.NET v4.0 Classic.
In general, this is own to the fact that this IIS version is too old. For example hosting WCF requires configuration on IIS 7.5, we should
In Developer command prompt for vs2017 Install the asp.net.
aspnet_regiis.exe -i
Enable the WCF HTTP Activation.which is in turn on/off windows feature.
Feel free to contact me if you have any questions

Bad request 400 error while acessing wcf rest service frequently

I am facing the problem of Bad request 400 while accessing the wcf service. I have tried all the solution related to this topic but still not solved. Wcf service is on IIS7 .
I am trying to call the service with below code.
try
{
WebClient client = new WebClient();
byte[] data = client.DownloadData(ApplicationRunTimeSettings.ServiceURL() + userID);
Stream stream = new MemoryStream(data);
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
result = obj.ReadObject(stream).ToString();
}
catch (Exception)
{
}
return result;
The config file at service is below, the config file is same for the wcf as well as web application. Actually wcf service is developed with in the web application and the web app hosted on iis7 and we are accessing the service with in it.
The configuration file is below. Most of the time it does not return error but it is breaking after some time. Request on the wcf service is frequent . Data is form of JSON.
Now after making the below suggested changes for serviceThrottling the web.config file look like mentioned below but it still gives the same error some times.
<system.web>
<sessionState timeout="1440"/>
<customErrors mode="Off"/>
<httpRuntime executionTimeout="90" maxRequestLength="104857600" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" enableVersionHeader="true"/>
<!--set compilation defug="false" when releasing-->
<compilation targetFramework="4.0" >
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="86400"/>
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers"/>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- maxAllowedContentLength = bytes -->
<requestLimits maxAllowedContentLength="104857600"/>
</requestFiltering>
</security>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.serviceModel>
<services>
<service name="Glance.DynamicBusinessService.DynamicBusinessService" behaviorConfiguration="ServiceBehaviour">
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address="customBinding" binding="customBinding" bindingConfiguration="basicConfig" contract="Glance.DynamicBusinessService.IDynamicBusinessService"/>
<endpoint address="" binding="webHttpBinding" contract="Glance.DynamicBusinessService.IDynamicBusinessService" behaviorConfiguration="REST">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="throttleThis">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="True" />
<serviceThrottling
maxConcurrentCalls="40"
maxConcurrentInstances="20"
maxConcurrentSessions="20"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="REST">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding maxReceivedMessageSize="999999999" receiveTimeout="24" closeTimeout="24" maxBufferPoolSize="999999999" maxBufferSize="999999999">
<readerQuotas maxDepth="32" maxStringContentLength="999999999" maxArrayLength="99999" maxBytesPerRead="4096" maxNameTableCharCount="99999" />
</binding>
</webHttpBinding>
<customBinding>
<binding name="basicConfig">
<binaryMessageEncoding/>
<httpTransport transferMode="Streamed" maxReceivedMessageSize="67108864"/>
</binding>
</customBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0"/>
</system.serviceModel>
</configuration>
Thanks for any suggestion and help.
I'd be tempted to comment out that configuration line on the client and host, and then trying running it. That config seems to set minimums and performance limits. If that doesn't change anything, you might try setting the performance throttling.
You could add this to the configuration and tinker with the settings until the performance of your web service smooths out. The default, for instance, for concurrent calls is 16, but if you raise that number using the ServiceThrottling, you might get better results.
<serviceBehaviors>
<behavior name="throttleThis">
<serviceMetadata httpGetEnabled="True" />
<serviceThrottling
maxConcurrentCalls="40"
maxConcurrentInstances="20"
maxConcurrentSessions="20"/>
</behavior>
</serviceBehaviors>

Installed WCF service with Installshield generated setup Error

I've just generated the installer for a WCF Service and I'm trying to use:
The structure installed at the wwwroot is the following:
http://bit.ly/11zZ85E
In the bin folder are included all dlls in which the service depends. The class that implements the service contract is defined in one of those dll. All generation and instalation proccess is all good. And I have on the IIS Manager the following:
http://bit.ly/10xBI3Y
The issue is that when I try to access the wsdl at the browser I'm only able to see:
<%# ServiceHost Language="VB" Debug="true" Service="MyApplication.ServiceImplementation.LicensingService" CodeBehind="MyApplication.ServiceImplementation.Service.vb" %>
And If I try to use the Add Service Reference from a Visual Studio project I see this:
There was an error downloading
(ServiceAddress)/$metadata
The request failed with HTTP status 404: Not Found.
Metadata contains a reference that cannot be resolved:
(ServiceAddress)
The remote server returned an unexpected response: (405) Method Not Allowed.
The remote server returned an error: (405) Method Not Allowed.
If the service is defined in the current solution, try building the solution and adding the service reference again.
The installer I did was generated with Installshield 2010.
Here is my Web.Config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation strict="false" explicit="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.serviceModel>
<services>
<service name="MyApp.ServiceImplementation.Service" behaviorConfiguration="WSSecurityBehavior">
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address="Operations" binding="wsHttpBinding" contract="MyApp.ServiceContracts.IService" />
<endpoint binding="wsHttpBinding" name="mex" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WSSecurityBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="WSSecurityBinding">
<reliableSession enabled="true" ordered="true" />
</binding>
</wsHttpBinding>
</bindings>
<!--protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping-->
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<directoryBrowse enabled="true" />
<handlers accessPolicy="Read, Script" />
<defaultDocument>
<files>
<clear />
<add value="Service.svc" />
</files>
</defaultDocument>
<httpErrors>
<clear />
</httpErrors>
</system.webServer>
</configuration>

Is it possible to use ASP.NET MembershipProvider/RoleProvider in self-hosted WCF services?

I am trying to use custom ASP.NET MembershipProvider and RoleProvider to handle security for my service. The service is self-hosted in a console app, not in IIS.
I use webHttpBinding with Basic Authentication. I configured serviceCredentials and serviceAuthorization to use providers. Providers really get initialized. But WCF seems to ignore my settings and tryes to login user to Windows. I figured that out from Events Log, and proved by sending my windows credentials to the service. Below you can see my configuration and debug screenshots. Why is it using windows for auth? Maybe it is impossible to use ASP.NET auth providers without IIS?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<roleManager
enabled="true"
defaultProvider="CustomRoleProvider">
<providers>
<clear/>
<add
name="CustomRoleProvider"
type="CustomRoles.CustomRoleProvider, CustomRoles"/>
</providers>
</roleManager>
<membership defaultProvider="CustomMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="CustomMembershipProvider"
type="CustomRoles.CustomMembershipProvider, CustomRoles"/>
</providers>
</membership>
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttp">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic" />
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="Service">
<serviceAuthorization principalPermissionMode="UseAspNetRoles"
roleProviderName="CustomRoleProvider" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider"
membershipProviderName="CustomMembershipProvider" />
</serviceCredentials>
<serviceSecurityAudit auditLogLocation="Application" serviceAuthorizationAuditLevel="SuccessOrFailure"
messageAuthenticationAuditLevel="SuccessOrFailure" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="Service" name="CustomRoles.Service">
<endpoint address="http://127.0.0.1:8060" binding="webHttpBinding"
bindingConfiguration="webHttp" contract="CustomRoles.IService" />
</service>
</services>
</system.serviceModel>
</configuration>
That's what I see when debug. Why is it using windows for auth?
credentials screen http://img81.imageshack.us/img81/1289/credentials.gif
link to full size screen
I'm trying to do the same thing.
My service is working well, I'm able to trace the call made to the service via the Service Trace Viewer.
The only problem remaining is that I don't receive any answer to the call. My application is freezing and I have a TimoutException on the call. Here's my settings :
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider"
type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
serviceUri="http://localhost:21200/Authentication_JSON_AppService.axd"
credentialsProvider="LacT.Windows.LoginWindow, LacT.Windows" />
<add name="FooMembershipProvider"
type="Foo.Security.Business.Provider.FooTMembershipProvider, LacT.Security.Business"
serviceUri="http://localhost:21200/Authentication_JSON_AppService.axd"
credentialsProvider="Foo.Windows.LoginWindow, Foo.Windows" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider"
type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
serviceUri="http://localhost:21200/Role_JSON_AppService.axd"
cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
And the service model...`
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp />
<enableWebScript />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="WebBehavior">
<serviceMetadata httpGetEnabled="true" httpGetUrl="" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="basicHttpMode">
<security mode="None" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding name="webHttpMode">
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="WebBehavior"
name="Foo.Security.Business.Manager.Wcf.Host.SecurityManager">
<endpoint address=""
binding="webHttpBinding"
contract="Foo.Security.Business.Contract.ISecurityContract"
behaviorConfiguration="WebBehavior"
bindingConfiguration="webHttpMode" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:21200" />
</baseAddresses>
</host>
</service>
</services>
`
Maybe with this piece of code it can help you to figure out what's going on with yours.
If you find let me know something.
I've done this during the WCF Master Class, so it is definitely possible. Unfortunately I did not use this in practice and it's a year ago now...
However, try this link, and look for the different downloads about ASP.NET membership stuff. It is basically the outcome of the training session.
Yes is possible:
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<connectionStrings>
<add name="mySqlConnection" connectionString="Data Source=.\SQLEXPRESS2012;Integrated Security=SSPI;Initial Catalog=aspnetdb;"/>
</connectionStrings>
<system.web>
<compilation debug="true"/>
<!-- Configure the Sql Membership Provider -->
<membership defaultProvider="MySqlMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="MySqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="mySqlConnection" applicationName="UsersManagementNavigationApplication" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed"/>
</providers>
</membership>
<!-- Configure the Sql Role Provider -->
<roleManager enabled="true" defaultProvider="MySqlRoleProvider">
<providers>
<clear/>
<add name="MySqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="mySqlConnection" applicationName="UsersManagementNavigationApplication"/>
</providers>
</roleManager>
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic"/>
</security>
</binding>
</webHttpBinding>
<basicHttpBinding>
<binding name="basicBindingConfiguration">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="webEndpointBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="webServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceThrottling/>
<serviceDebug/>
</behavior>
<behavior name="myServiceBehavior">
<!-- Configure role based authorization to use the Role Provider -->
<serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="MySqlRoleProvider">
</serviceAuthorization>
<serviceCredentials>
<!-- Configure user name authentication to use the Membership Provider -->
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WcfServiceHTTPSelfHosted.MyCustomValidator, WcfServiceHTTPSelfHosted"/>
</serviceCredentials>
<!-- To avoid disclosing metadata information, set the value below to false before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="myServiceBehavior" name="WcfServiceHTTPSelfHosted.WcfServiceHTTPSelfHosted">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicBindingConfiguration"
contract="WcfServiceHTTPSelfHosted.IWcfServiceHTTPSelfHosted" />
<endpoint address="web" behaviorConfiguration="webEndpointBehavior"
binding="webHttpBinding" bindingConfiguration="webBinding"
contract="WcfServiceHTTPSelfHosted.IWcfServiceHTTPSelfHosted" />
<endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:50002/WcfServiceHTTPSelfHosted/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
And uses a custom UserNamePasswordValidator:
public class MyCustomValidator : UserNamePasswordValidator
{
public MyCustomValidator()
{
}
public override void Validate(string userName, string password)
{
if (!Membership.ValidateUser(userName, password))
{
throw new SecurityTokenException("Users validation failed: " + userName);
}
}
}
this works fine!