How to call WCF Rest service with Basic Auth using Postman? - wcf

I have created a WCF service with Basic Authentication following this article https://learn.microsoft.com/en-gb/dotnet/framework/wcf/feature-details/transport-security-with-basic-authentication.
But when I call it using Postman, I get an error (400 Bad Request).
If I use a small application written in C# setting out ClientCredentials, it works well.
Here is my server code:
public class DataService : IDataService
{
public bool GetData()
{
return true;
}
}
[ServiceContract]
public interface IDataService
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GetData")]
bool GetData();
}
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.2" />
<httpRuntime targetFramework="4.6.2"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<bindings>
<wsHttpBinding>
<binding name="UsernameWithTransport">
<security mode="Transport">
<transport clientCredentialType="Basic" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="BasicAuthenticationTest">
<endpoint
address=""
binding="wsHttpBinding"
bindingConfiguration="UsernameWithTransport"
name="BasicEndpoint"
contract="BasicAuthTest.IDataService"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
I also turned off "SSL certificate verification" and proxy in Postman

Related

Protobuf-net return type List<t> is null

I'm trying to config my service to use protobuf-net. The methods that return T[] and T works but List is returning null. Is it supported?
Also, how can i tell that it is really using protobuf for during serialization. I tried to use fiddler but i can't really tell the difference.
public interface IOrdersService
{
[OperationContract(IsOneWay = false)]
OrderDTO[] GetAllOrders();
[OperationContract(IsOneWay = false)]
List<OrderDTO> GetAllOrders2();
[OperationContract(IsOneWay = false)]
OrderDTO GetOrder();
}
public class OrdersClient : IOrdersServiceCallback
{
private OrdersServiceClient client;
public OrdersClient()
{
}
public void Init()
{
InstanceContext site = new InstanceContext(null, new OrdersClient());
client = new OrdersServiceClient(site);
}
public void Start()
{
OrderDTO[] orders = client.GetAllOrders();
OrderDTO[] orders2 = client.GetAllOrders2();
OrderDTO dto = client.GetOrder();
Console.WriteLine(dto);
}
}
web config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<services>
<service name="OrdersServer.OrdersService">
<endpoint address=""
binding="wsDualHttpBinding"
bindingConfiguration="Binding1"
contract="OrdersServer.IOrdersService"
behaviorConfiguration="ProtoBufBehavior" />
</service>
</services>
<bindings>
<wsDualHttpBinding>
<binding name="Binding1">
<!-- Binding property values can be modified here. -->
<security mode="None"/>
</binding>
</wsDualHttpBinding>
</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="ProtoBufBehavior">
<protobuf />
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<!--add binding="basicHttpsBinding" scheme="https" />-->
<add scheme="http" binding="wsDualHttpBinding"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<extensions>
<behaviorExtensions>
<add name="protobuf" type="ProtoBuf.ServiceModel.ProtoBehaviorExtension, protobuf-net, Version=2.0.0.640, Culture=neutral, PublicKeyToken=257b51d87d2e4d67"/>
</behaviorExtensions>
</extensions>
</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>
</configuration>
client config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<wsDualHttpBinding>
<binding name="WSDualHttpBinding_IOrdersService" clientBaseAddress="http://localhost:8000/whatisthis/">
<security mode="None" />
</binding>
</wsDualHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost.fiddler:49522/OrdersService.svc"
binding="wsDualHttpBinding" bindingConfiguration="WSDualHttpBinding_IOrdersService"
contract="OrdersServiceReference.IOrdersService" name="WSDualHttpBinding_IOrdersService"
behaviorConfiguration="proto"/>
</client>
<behaviors>
<endpointBehaviors>
<behavior name="proto">
<protobuf />
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="protobuf" type="ProtoBuf.ServiceModel.ProtoBehaviorExtension, protobuf-net, Version=2.0.0.640, Culture=neutral, PublicKeyToken=257b51d87d2e4d67"/>
</behaviorExtensions>
</extensions>
</system.serviceModel>
</configuration>

WCF configuration - Custom authentication on the host

I've been struggling with this for a couple of days now - I cannot get this WCF service configured correctly to use a custom membership provider. When I fire up the test client I get this error:
The username/password Membership provider MidlandsCoop.MembersWcfService.Business.UserAuthentication specified in the configuration is invalid. No such provider was found registered under system.web/membership/providers.
I have been following this MSDN link to no avail. Can anyone tell me where I'm going wrong?
Here's my web.config:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyCS" connectionString="Data Source=my server;Initial Catalog=MyDB;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="wsHttpBinding">
<security>
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="MidlandsCoop.MembersWcfService.MembersService" behaviorConfiguration="Service_Behaviour">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration=""
name="basicHttpBinding" contract="MidlandsCoop.MembersWcfService.IMembersService" />
<endpoint binding="wsHttpBinding" bindingConfiguration="wsHttpBinding"
name="wsHttpBinding" contract="MidlandsCoop.MembersWcfService.IMembersService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Service_Behaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom"
membershipProviderName="MidlandsCoop.MembersWcfService.Business.UserAuthentication" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
</configuration>
My user authentication class is as follows:
public class UserAuthentication : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (null == userName || null == password)
{
throw new ArgumentNullException();
}
var db = new PetaPoco.Database("MyDB");
db.Fetch<dynamic>("SELECT Username, Password FROM MyTable WHERE Username=#0 AND Password =#1",
userName, password);
}
}
Any suggestions would be greatly appreciated.
the link that you have provided mentions customUserNamePasswordValidatorType to specify custom authentication type, UserAuthentication in your case. I think MembershipProviderName should be a class derived from MembershipProvider Class.

error on returning a class by wcf

I've been struggling with this error for a while:
An error occurred while receiving the HTTP response to
....8332/Service1.svc. This could be due to the service endpoint
binding not using the HTTP protocol. This could also be due to an HTTP
request context being aborted by the server (possibly due to the
service shutting down). See server logs for more details.
I traced the error and apparently it's something to do with the binding or the connection that I can't figure out how to solve.
..I am putting the class and the config files below.please guide me.thanks in advance.
[DataContract]
public class filepack
{
string filesize = "0";
int accesspermitid =0;
System.IO.Stream str ;
[DataMember]
public System.IO.Stream Filestr
{
get { return str; }
set { str = value; }
}
[DataMember]
public string Filesize
{
get { return filesize; }
set { filesize = value; }
}
[DataMember]
public int Accesspermitid
{
get { return accesspermitid; }
set { accesspermitid = value; }
}
}
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="debugbeh">
<dataContractSerializer />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" maxBufferSize="500000000"
maxReceivedMessageSize="500000000">
<security mode="None">
<message algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8332/Service1.svc" behaviorConfiguration="debugbeh"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
contract="vcpservice.IService1" name="BasicHttpBinding_IService1" />
</client>
</system.serviceModel>
</configuration>
<?xml version="1.0"?>
<configuration>
<system.diagnostics>
<trace autoflush="true" />
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="sdt"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="c:\\logclientHOST.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="mybinding" closeTimeout="00:10:00" maxBufferPoolSize="52428800"
maxBufferSize="500000000" maxReceivedMessageSize="500000000" />
</basicHttpBinding>
</bindings>
<diagnostics>
<messageLogging logMalformedMessages="true" logMessagesAtTransportLevel="true" />
</diagnostics>
<behaviors>
<endpointBehaviors>
<behavior name="NewBehavior0">
<dataContractSerializer />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"
httpGetBinding="webHttpBinding" httpGetBindingConfiguration="" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483646" />
</behavior>
</serviceBehaviors>
</behaviors>
<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"/>
</system.webServer>
</configuration>
You cannot send a stream. You will need to either materialize your stream into a real data object (string or byte array for example) by reading it to the end before sending or if you really want streaming (which I doubt) you can read this.
the problem seems to be solved by removing the stream from the class and returning it separately!
but I don't know how did it help to solve it!

WCF username authentication not working

I'm new to WCF service. I wanted to create a WCF service with basichttpbinding to create a custom authentication mechanism before giving access to my WCF service. I have used
security mode = Transport and clientcredentialtype = basic. I have written a custom validator function for validating my username and password.
validator function
namespace CustomValidator
{
public class MyCustomValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
// This isn't secure, though!
if ((userName != "check") || (password != "check"))
{
throw new SecurityTokenException("Validation Failed!");
}
}
}
}
This is my service config file
< ?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<identity impersonate="false" />
</system.web>
<system.serviceModel>
<diagnostics>
<endToEndTracing activityTracing="true" messageFlowTracing="true" propagateActivity="true"></endToEndTracing>
</diagnostics>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="Transport">
<transport clientCredentialType="Basic" />
<!-- <message clientCredentialType="UserName" />-->
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="" binding="basicHttpBinding" name="BasicHttpEndpoint" bindingConfiguration="BasicHttpEndpointBinding" contract="IService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- 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="false" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CustomValidator.MyCustomValidator, App_Code" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<security>
<authentication>
<basicAuthentication enabled="true" />
<anonymousAuthentication enabled="false" />
<windowsAuthentication enabled="false" />
</authentication>
</security>
</system.webServer>
</configuration>
So the problem here is that whenever I run my service, I get a login dialog were I enter username and password(my validator expects both username and password to be same), I'm not getting my service details page, which used to come up in normal case (without authentication mechanism). I don't know what I'm missing, I do feel like its all in configurations which matters in my case but still I can't find out the mistake.
Have Created and Shared a Demo Project for Username Password Authentication.Its Working Fine.
Pls Check
https://onedrive.live.com/redir?resid=3FE322C74D6AA4D1%21169
You can use SelfCert,given inside,to Create a Certificate with name TrustedPeople , Store Location LocalMachine

Cannot upload more than 64kb to WCF REST Service from client

I have created a WCF REST Service and have successfully created a function to upload a file from the client to the service.
The problem is, this only works when the file being sent is 64kb or less. How can I fix this problem.
web.config file:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147483647"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="100000000"> </requestLimits>
</requestFiltering>
</security>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
and global.asax:
namespace WCFRESTService
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
// Edit the base address of Service1 by replacing the "Service1" string below
RouteTable.Routes.Add(new ServiceRoute("RO", new WebServiceHostFactory(), typeof(Service1)));
}
}
}
After 3 days of my googling search finally i found the solution
In my solution, web.config i've added https code and etc. after that i have removed all the config and added this below code
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehaviour" name="NativeAppServices.Service1">
<endpoint address="" binding="webHttpBinding" bindingConfiguration="StreamedRequestWebBinding" contract="NativeAppServices.IService1" behaviorConfiguration="webBehavior">
</endpoint>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="StreamedRequestWebBinding" closeTimeout="00:25:00"
openTimeout="00:25:00" receiveTimeout="00:25:00" sendTimeout="00:25:00"
bypassProxyOnLocal="true" hostNameComparisonMode="WeakWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
transferMode="StreamedRequest" useDefaultWebProxy="false">
<readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" />
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors >
<behavior name="ServiceBehaviour">
<!-- 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="webBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"></serviceHostingEnvironment>
</system.serviceModel>
<system.webServer>
<directoryBrowse enabled="true"/>
</system.webServer>
Figured it out. Had to add attributes "maxReceivedMessageSize" and "maxBufferSize" to the