how to use roles - Method is only supported if the user name parameter matches the user name in the current Windows Identity - wcf

I have managed to get windows authentication working with a service call using this .config:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="Unsecured">
<security mode="None"/>
</binding>
<binding name="Secured">
<security mode="Message">
<message clientCredentialType="Windows"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="ServiceBehaviour" name="WebApplication.SecureService">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="Secured" contract="WebApplication.ISecureService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Windows"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>
In the service I'm able to see who is logged in using:
OperationContext.Current.ServiceSecurityContext.PrimaryIdentity;
I'd like to check the user is a member of a particular role, so I have tried enabling the roleManager thusly:
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
<providers>
<clear/>
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
Then checking the role using Roles
Roles.IsUserInRole(#"DOMANIN\Role");
or:
var id = OperationContext.Current.ServiceSecurityContext.PrimaryIdentity;
Roles.IsUserInRole(id.Name, #"DOMANIN\Role");
But both throw exception:
"Method is only supported if the user name parameter matches the user name in the current Windows Identity."
Also if there is an attribute to check roles, that would be ideal as it would throw the right exception rather than me handling it myself.
Update
I just tried this:
if (Roles.RoleExists(#"DOMANIN\Role"))
and got a different exception:
"The configured Role Provider (WindowsTokenRoleProvider) relies upon Windows authentication to determine the groups that the user is allowed to be a member of. ASP.NET Role Manager cannot be used to manage Windows users and groups. Please use the SQLRoleProvider if you would like to support custom user/role assignment." Which I will Google, just thought it might help anyone who's looking at this for me.

The exceptions are telling you that you can only check the Role of the currently logged in User. To get a list of those in String form, this should work for you:
Roles.GetRolesForUser()
But, you cannot get the Roles for some arbitrary user like you can when using Forms authentication.

[PrincipalPermission(SecurityAction.Demand, Role = #"DOMAIN\Role")]
public string DoWork()
{
//user is authenticated and in the role
}
Still would be interested if any one can shed light on the exceptions.
This works even with out the roleManager enabled so clearly a different mechanism at work.

Related

Issues creating client for WCF Service using Federation

After modifying my service to use federation (see web.config below) I'm having trouble on my client getting it connected. In all that I have read it seems I should be able to just create
var client = new MyService()
and then set username and password on that credential and then WCF takes care of the STS token stuff, but I do not have a constructor that takes 0 arguments, I only have one that takes a binding and endpoint address. I do not see a way to create the binding manually and would just like to use it the default way, before when I was just using a basicHTTPBinding with Https I was able to create the client with the default constructor I don't see why this does not follow same logic.
The service has web.config as such:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</configSections>
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics">
<filter type="" />
</add>
</listeners>
</trace>
</system.diagnostics>
<location path="FederationMetadata">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<machineKey decryption="AES" decryptionKey="[DecrpytKey]" validation="SHA1" validationKey="[ValidationKey]" />
</system.web>
<system.serviceModel>
<services>
<service name="MyService">
<endpoint address="" binding="wsFederationHttpBinding" bindingConfiguration="wsFedBinding" contract="MyService.IMyService" />
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="https://myservice.cloudapp.net/MyService.svc" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<wsFederationHttpBinding>
<binding name="wsFedBinding">
<security mode="TransportWithMessageCredential">
<message>
<issuer address="http://mysts.com"/>
<issuerMetadata address="https://mysts.com/adfs/services/trust/mex" />
<claimTypeRequirements>
<add claimType="http://mysts.com/user/UserDomain" isOptional="true"/>
<add claimType="http://mysts.com/user/Alias" isOptional="true"/>
</claimTypeRequirements>
</message>
</security>
</binding>
</wsFederationHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false before deployment -->
<serviceMetadata 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="true" />
<serviceCredentials useIdentityConfiguration="true">
<!--Certificate added by Identity and Access Tool for Visual Studio.-->
<serviceCertificate findValue="[Thumbprint]" storeLocation="CurrentUser" storeName="My" x509FindType="FindByThumbprint" />
</serviceCredentials>
<serviceSecurityAudit auditLogLocation="Application" serviceAuthorizationAuditLevel="Failure" messageAuthenticationAuditLevel="Failure" suppressAuditFailure="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment 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="false" />
</system.webServer>
<connectionStrings>
[Some connection strings]
</connectionStrings>
<system.identityModel>
<identityConfiguration>
<audienceUris>
<add value="https://myservice.cloudapp.net/MyService.svc" />
</audienceUris>
<issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
<authority name="http://mysts.com">
<keys>
<add thumbprint="[Thumbprint]" />
</keys>
<validIssuers>
<add name="http://mysts.com" />
</validIssuers>
</authority>
</issuerNameRegistry>
<!--certificationValidationMode set to "None" by the the Identity and Access Tool for Visual Studio. For development purposes.-->
<certificateValidation certificateValidationMode="ChainTrust"/>
<securityTokenHandlers>
<add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</securityTokenHandlers>
</identityConfiguration>
</system.identityModel>
<appSettings>
<add key="ida:FederationMetadataLocation" value="https://mysts.com/FederationMetadata/2007-06/FederationMetadata.xml" />
<add key="ida:ProviderSelection" value="productionSTS" />
</appSettings>
</configuration>

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>

WCF Service Error on Client Service Test - SVCUtil

I created a WCF service which compiles fine and published ok; I created a web app to test the WCF service and initially when using svcutil.exe it created the source file but not the config file. So I added the service as a service reference and that looked fine until I tried to run the client app. The following error showed up:
Could not find default endpoint element that
references contract 'ServiceReference1.IService1' in the ServiceModel
client configuration section. This might be because no configuration
file was found for your application, or because no endpoint
element matching this contract could be found in the client element.
I figured its something wrong with the web.config file and searching for posts I found that I needed to copy the service model section from the service config file to the client test web config file. This did not help.
WCF Service config file
<configuration>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<bindings>
<webHttpBinding>
<binding name="webHttpBinding" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="webHttpBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="webHttpBehavior" name="WcfInstanceRules2.Service1">
<endpoint address="mex"
binding="webHttpBinding" bindingConfiguration="webHttpBinding"
contract="WcfInstanceRules2.IService1" behaviorConfiguration="web"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
WebApp Test Config file
<configuration>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<bindings>
<webHttpBinding>
<binding name="webHttpBinding" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="webHttpBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="webHttpBehavior" name="WcfInstanceRules2.Service1">
<endpoint address="mex" binding="webHttpBinding"
bindingConfiguration="webHttpBinding"
contract="WcfInstanceRules2.IService1" behaviorConfiguration="webHttpBehavior"/>
</service>
</services>
</system.serviceModel>
</configuration>
You need to use a client endpoint defined on the client side. You are currently defining a new service host on the web app. On the client side, you should have something like...
<system.serviceModel>
<client>
<endpoint address="http://.../mex" binding="webHttpBinding"
bindingConfiguration="webHttpBinding"
contract="ServiceReference1.IService1" behaviorConfiguration="webHttpBehavior"/>
</client>
</system.serviceModel>
To make this easier, VS.NET will add this client endpoint for you when you use Add Service Reference.
In your endpoint tag change contract="ServiceReference1.IService1"
where ServiceReference1 is service refference which you add in your project.

Problem in WCF Configuration

There are two templates:one Middleware and other the webclient.
The web.config for the Middleware is as :
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="HoneywellMiddleware.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Windows"/>
<anonymousIdentification enabled="true"/>
<identity impersonate="true"/>
</system.web>
<connectionStrings>
<add name="SQLConnectionString" connectionString="server=01HW361477;uid=sa;pwd=MSS#L2008;database=Honeywell"/>
</connectionStrings>
<system.serviceModel>
<services>
<service name="HoneywellMiddleware.HoneywellService" behaviorConfiguration="ServiceBehaviour">
<endpoint address="" binding="webHttpBinding" contract="HoneywellMiddleware.IHoneywellService" behaviorConfiguration="web"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:56334/HoneywellService.svc"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above 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>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
For the webclient web application it is like this :
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<bindings>
<basicHttpBinding>
<binding name="HoneywellMiddleware_IHoneywellService"/>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:56334/HoneywellService.svc" binding="basicHttpBinding"
bindingConfiguration="HoneywellMiddleware_IHoneywellService" contract="HoneywellService.IHoneywellService"
name="HoneywellMiddleware_IHoneywellService" />
</client>
</system.serviceModel>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Error:
There was no endpoint listening at http://localhost:56334/HoneywellService.svc
that could accept the message. This is often caused by an incorrect address or
SOAP action. See InnerException, if present, for more details.
Any help will be appreciated
Either you have a binding mismatch (http vs web binding) or you have a contract mismatch (HoneywellService.IHoneywellService vs HoneywellMiddleware.IHoneywellService).
Change your client endpoint to:
<client>
<endpoint address="http://localhost:56334/HoneywellService.svc" binding="webHttpBinding"
contract="HoneywellService.IHoneywellService"
name="HoneywellMiddleware_IHoneywellService" />
</client>
or
<client>
<endpoint address="http://localhost:56334/HoneywellService.svc" binding="webHttpBinding"
contract="HoneywellMiddleware.IHoneywellService"
name="HoneywellMiddleware_IHoneywellService" />
</client>

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!