AspNetMembership provider with WCF service - wcf

I'm trying to configure AspNetMembershipProvider to be used for authenticating in my WCF service that is using basicHttpBinding. I have following configuration:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<bindings>
<basicHttpBinding>
<binding name="basicSecureBinding">
<security mode="Message"></security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="MyApp.Services.ComputersServiceBehavior">
<serviceAuthorization roleProviderName="AspNetSqlRoleProvider" principalPermissionMode="UseAspNetRoles" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="AspNetSqlMembershipProvider"/>
</serviceCredentials>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="MyApp.Services.ComputersServiceBehavior" name="MyApp.Services.ComputersService">
<endpoint binding="basicHttpBinding" contract="MyApp.Services.IComputersService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
Roles are enabled and membership provider is configured (its working for web site).
But authentication process is not fired at all. There is no calles to data base during request, and when I try to set following attribute on method:
[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
public bool Test()
{
return true;
}
I'm getting access denied exception. Any thoughts how to fix it?

Try this CodePlex Security Guide, the How Tos and Application Scenarios have detailed setup and configurations guides for a number of configuration options that might help you find the missing piece of your puzzle.

Related

Not able to access the methods from secure wcf rest service

I have a running wcf rest service hosted on IIS. I have successfully added the .x509 certificates to the client and the server and it works fine.As it is a secure service it is accessed using https The problem I am facing is that I am not able to access any of the methods from the service it keeps throwing 404 error however when I browse the service from IIS using https link it open the WSDL fine but throws 404 error while accessing any of the methods.
Here is my Interface implementation of a method from the service.
[ServiceContract]
public interface IRestDemo
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/DoWork/{name}")]
string DoWork(string name);
}
Here is my configuration file:
<system.serviceModel>
<services>
<service name="RestDemo.RestDemo" behaviorConfiguration="serviceBehavior">
<host>
<baseAddresses>
<add baseAddress="https://localhost/RestDemo/RestDemo.svc" />
</baseAddresses>
</host>
<endpoint address="" binding="webHttpBinding" contract="RestDemo.IRestDemo" behaviorConfiguration="web">
<!--<identity>
<dns value="localhost"/>
</identity>-->
</endpoint>
<endpoint address="mex" binding="mexHttpsBinding" contract="RestDemo.IRestDemo" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="web" crossDomainScriptAccessEnabled="true">
<security mode="Transport">
<transport clientCredentialType="Certificate" />
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<!--<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="PeerTrust"
trustedStoreLocation="LocalMachine" />
</clientCertificate>
<serviceCertificate findValue="ServerCertificate"
storeLocation="LocalMachine"
storeName="My"
x509FindType="FindBySubjectName" />
</serviceCredentials>-->
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" httpsGetUrl="/RestDemo.svc" />
<!-- 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 aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint
crossDomainScriptAccessEnabled="true">
</standardEndpoint>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
Any suggestions would be really appreciated.

The remote server returned an error: (401) Unauthorized - WCF basicHttpBinding

I get this error when I want to execute a method on my service with wcfstorm client.
I tried so many different settings and I can't get it to work. If I switch to Transport security I get another error.. It worked perfectly with wsHttpBinding but customer wants basicHttpBinding because of PHP compatibility. I need a custom user authentication class to authenticate users against my sql database..
web.config
<services>
<service name="e3kConnector.E3KConnectorService" behaviorConfiguration="basicHttpBehavior">
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="basicHttpBinding" name="basicHttpEndpoint"
contract="e3kConnector.e3kConnectorService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<client />
<behaviors>
<serviceBehaviors>
<behavior name="basicHttpBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="e3kConnector.App_Data.Security.CustomUserNameValidator,e3kConnector" />
</serviceCredentials>
<serviceAuthorization principalPermissionMode="Custom">
<authorizationPolicies>
<add policyType="e3kConnector.App_Data.Security.AuthorizationPolicy, e3kConnector" />
</authorizationPolicies>
</serviceAuthorization>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

Unable to invoke the methods of a WCF service hosted in Azure with https

I have a WCF service hosted in Azure, I am able to get the wsdl properly but when trying to call a method it gives me the following error.
There was no endpoint listening at
https://pactwp7.cloudapp.net/Service1.svc that could accept the
message. This is often caused by an incorrect address or SOAP action.
See InnerException, if present, for more details.
I have used a self signed certificate while making it https so I have added the following before accessing the service from the client side:
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, error) => true;
Below is the service config that I have used:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="httpsAzureBehavior">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<useRequestHeadersForMetadataAddress>
<defaultPorts>
<add scheme="http" port="80" />
<add scheme="https" port="443" />
</defaultPorts>
</useRequestHeadersForMetadataAddress>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="httpsBinding">
<binaryMessageEncoding />
<httpsTransport allowCookies="true" />
</binding>
</customBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"
aspNetCompatibilityEnabled="true" />
<services>
<service behaviorConfiguration="httpsAzureBehavior"
name="PactServices.ServiceImplementation.PactService">
<endpoint address="" binding="customBinding"
bindingConfiguration="httpsBinding"
contract="PactServices.ServiceContracts.IPactServices"
listenUri="Service1.svc" />
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
any reasons why?
Did you open the 443 for input endpoint on your CSDEF file?
RDP to your VM and have a local try might helps to identify and debug I think.

AddressFilter mismatch at the EndpointDispatcher - the msg with To

Any ideas how I correct this.. calling a service via js
The message with To 'http://MySite.svc/GetStateXML' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree
thanks
The error listed below indicates that the Web Service implements WS-Addressing.
"The message with To '' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree"
Include the following in your SOAP Headers to access the Web Service:
<soap:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
<wsa:To>http://example.com/service</wsa:To>
</soap:Header>
I just ran into this as well while going through an example in the Learning WCF book by Bustamante.
I had used the WCF Config Editor to fill out my config on my host and had put the value in the name attribute for my endpoint rather than the address attribute. Once I fixed it things worked.
I found another post that suggested using:
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
on the implementation class, which worked but wasn't the root cause.
Bottom line appears to be: make sure your client and server configs match.
I got this error while I was using webHttpBinding.
I resolved it by adding
<endpointBehaviors>
<behavior name="EndPointBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
under <behaviors> and setting behaviorConfiguration="EndPointBehavior" in my endpoint with binding="webHttpBinding".
Full config:
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndPointBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="WcfService1.Service1" behaviorConfiguration="ServiceBehavior">
<endpoint address=""
binding="webHttpBinding"
contract="WcfService1.IService1"
behaviorConfiguration="EndPointBehavior">
</endpoint>
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange">
</endpoint>
</service>
</services>
I know it sounds silly but for anyone else that has this error check your address. We were getting this error because we had a double slash where there should have only been one.
http://localhost//servicename.svc
The above address caused the problem.
http://localhost/servicename.svc
Did not exhibit the problem.
We were dynamically creating the full address from parts of data read in from windows forms and a database. The user was entering /servicename.svc instead of servicename.svc
I had this issue in my development environment for a web service hosted in IIS. Solved it by going to 'IIS Manager' and added a binding to the host name complained about in the error message.
Add webHttp attribute to your config:
endpointBehaviors
behavior name ="yourServiceContract"
webHttp automaticFormatSelectionEnabled ="true "
behavior
I had the same kind of issue, just to be complete :
I used visual studio 2017
I needed to create a wcf service on an old application using .net 3.5
It should be exposed as a soap service and as a "Rest" service
the configuration that I needed to use (for rest part) was :
there is a config for the service behaviour and the endpoint behaviour
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="myServiceBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webEndpointBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="My.Service" behaviorConfiguration="myServiceBehaviour">
<endpoint address="" binding="webHttpBinding" contract="My.IService" behaviorConfiguration="webEndpointBehaviour">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
In my case I have WCF Service library application which is a RESTFul and Windows Service Host. I had problem with Host App.Config. Please see below
WCF Rest Service App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<services>
<service name="MyService.DocumentWCFRESTService" behaviorConfiguration="defaultServiceBehavior">
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address="http://localhost:2023/DocumentWCFRESTService"
binding="webHttpBinding" behaviorConfiguration="webBehaviorConfiguration"
contract="MyService.IDocumentWCFRESTService" >
<!--
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.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8733/Design_Time_Addresses/Document.Server.WCFREST.Service/DocumentWCFRESTService/" />
</baseAddresses>
</host>
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<bindings> </bindings>
<behaviors>
<serviceBehaviors>
<behavior name="defaultServiceBehavior">
<!-- To avoid disclosing metadata information,
set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="True" httpGetUrl="http://localhost:2023/DocumentWCFRESTService"/>
<!-- 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="webBehaviorConfiguration">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Windows Service Host App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingConfiguration" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="documentWCFRESTServiceBehavior">
<!-- To avoid disclosing metadata information,
set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="True" httpGetUrl="http://localhost:2023/DocumentWCFRESTService"/>
<!-- 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="webBehaviorConfiguration">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="MyService.DocumentWCFRESTService" behaviorConfiguration="documentWCFRESTServiceBehavior">
<endpoint address="http://localhost:2023/DocumentWCFRESTService" behaviorConfiguration="webBehaviorConfiguration"
binding="webHttpBinding" bindingConfiguration="webHttpBindingConfiguration"
contract="MyService.IDocumentWCFRESTService"></endpoint>
</service>
</services>
</system.serviceModel>
</configuration>
if you have multiple endpoints in your WCFService.config like:
<endpoint address="urn:Service.Test" .../>
<endpoint address="urn:Service.Test2".../>
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:1234/Service/" />
<add baseAddress="http://localhost:1233/Service/" />
<add baseAddress="net.pipe://localhost/Service/" />
</baseAddresses>
</host>
You need to set EndpointAddress like in your config file.
Then you need ClientViaBehavior for the baseAddress.
NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
EndpointAddress address = new EndpointAddress("urn:Service.Test");
AndonClient client = new AndonClient(binding, address);
client.ChannelFactory.Endpoint.EndpointBehaviors.Add(new ClientViaBehavior(new Uri("net.tcp://localhost:1234/Service/Test")));
var response = client.GetDataAsync().Result;
For .net core you need to write the Behavior by yourself:
public class ClientViaBehavior : IEndpointBehavior
{
Uri uri;
public ClientViaBehavior(Uri uri)
{
if (uri == null)
throw new ArgumentNullException(nameof(uri));
this.uri = uri;
}
public Uri Uri
{
get { return this.uri; }
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
this.uri = value;
}
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
if (clientRuntime == null)
{
throw new ArgumentNullException(nameof(clientRuntime));
}
clientRuntime.Via = this.Uri;
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
throw new NotImplementedException();
}
void IEndpointBehavior.Validate(ServiceEndpoint serviceEndpoint)
{
}
}
I had a similar problem.
The following address was provided to the client:
https://test.mycompany.ru/ChannelService/api/connect.svc
But according to the logs, the client sent requests to the following address:
https://test.mycompany.ru/ChannelService/api/connect.svc/SOAP/Adapter
After I added the endpoint address to the configuration file, the service started working:
<services>
<service name="connect">
<endpoint address="/SOAP/Adapter"
binding="basicHttpBinding"
bindingConfiguration="secureHttpBinding"
contract="IContract">
</endpoint>
<endpoint address="mex"
binding="mexHttpsBinding"
contract="IMetadataExchange"/>
</service>
</services>
The key elements are the webHttp and binding="webHttpBinding" for the Json work in the browser test. However SoapUI still failed to return JSon.
Look at <webHttp />
<services>
<service name="SimpleService.SimpleService" behaviorConfiguration="serviceBehaviour">
<endpoint address="" binding="webHttpBinding" contract="SimpleService.ISimpleService" behaviorConfiguration="web">
</endpoint>
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange">
</endpoint>
</service>
</services>
....
....
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
</endpointBehaviors>

How to use SSL with a WCF web service?

I have a web service in asp.net running and everything works fine. Now I need to access some methods in that web-service using SSL. It works perfect when I contact the web-service using http:// but with https:// I get "There was no endpoint listening at https://...".
Can you please help me on how to set up my web.config to support both http and https access to my web service. I have tried to follow guidelines but I can't get it working.
Some code:
My TestService.svc:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class TestService
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public bool validUser(string email) {
return true;
}
}
My Web.config:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<behaviors>
<endpointBehaviors>
<behavior name="ServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="TestService">
<endpoint address="" behaviorConfiguration="ServiceAspNetAjaxBehavior"
binding="webHttpBinding" bindingConfiguration="ServiceBinding"
contract="TestService" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="ServiceBinding" maxBufferPoolSize="1000000" maxReceivedMessageSize="1000000">
<readerQuotas maxDepth="1000000" maxStringContentLength="1000000" maxArrayLength="1000000" maxBytesPerRead="1000000" maxNameTableCharCount="1000000"/>
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
Instead of using the webHttpBinding, try creating a customBinding instead:
<customBinding>
<binding name="poxBindingHttps" closeTimeout="00:00:20">
<textMessageEncoding writeEncoding="utf-8" />
<httpsTransport manualAddressing="true"/>
</binding>
<binding name="poxBindingHttp" closeTimeout="00:00:20">
<textMessageEncoding writeEncoding="utf-8" />
<httpTransport manualAddressing="true"/>
</binding>
</customBinding>
You'll also need to setup the webHttpBehavior like so:
<behaviors>
<endpointBehaviors>
<behavior name="ajaxBehavior">
<enableWebScript/>
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
And finally, your service & endpoint:
<services>
<service name="TestService">
<endpoint name="sslDefault" address="" binding="customBinding" bindingConfiguration="poxBindingHttps" behaviorConfiguration="ajaxBehavior" contract="TestService"/>
<endpoint name="noSslDefault" address="" binding="customBinding" bindingConfiguration="poxBindingHttp" behaviorConfiguration="ajaxBehavior" contract="TestService"/>
</service>
</services>
Hopefully that works out for you in creating an SSL endpoint
It sounds like there is more an issue with IIS no listening on port 443 (The port used for HTTPS). Check IIS that there is a certificate installed and that it is listening on the secure port.