Https error in WCF Web Api REST service - wcf-web-api

I've a windows xp machine with IIS 5.1 and I've signed the Default Web Site with a self created certificate. Now I've a REST service built using WCF Web API running under the default web site and when I try to invoke a particular resource I'm getting the followinng error.
The provided URI scheme 'https' is invalid; expected 'http'.
Parameter name: context.ListenUriBaseAddress
This is my configuration,
<system.webServer>
<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>
<services>
<service name="QuartzResource">
<endpoint binding="webHttpBinding" contract="webHttpBinding"
behaviorConfiguration="webHttp" bindingConfiguration="bindConfig"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="bindConfig">
<security mode="Transport">
<transport clientCredentialType="Certificate"></transport>
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
This is the resource class,
[ServiceContract]
public class QuartzResource
{
[WebGet(UriTemplate = "")]
public List<Job> GetJobs()
{
...
return allJobs;
}
}
This is my Global.asax.cs,
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapServiceRoute<QuartzResource>("");
}
Note: Things are working fine when runs in VS dev server.

Related

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

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

WCF Service calls error out with message Could not establish secure channel for SSL/TLS with authority

Hello I am trying to call a web service:-
https://example.com/Dealio/DealioCapLinkSvc.svc (actual name hidden).
I am able to browse this service on the browser. However when I call the service through my client application I get the following error:-
Could not establish secure channel for SSL/TLS with authority 'example.com'.
Can any one tell me what is going on ?
Below is App Config:-
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="SOAPEndPoint1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://example.com/dealio/DealioCapLinkSvc.svc/soap"
binding="basicHttpBinding" bindingConfiguration="SOAPEndPoint1"
behaviorConfiguration="authBehavior"
contract="DealioService.IDealioLib" name="SOAPEndPoint1" />
</client>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
<!-- Security Behavior -->
<endpointBehaviors>
<behavior name="authBehavior">
<authBehavior />
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="authBehavior" type="CanadaDealio.AuthBehavior, CanadaDealio , Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
</system.serviceModel>
</configuration>
This is the code that calls the service:-
static void Main(string[] args)
{
Deal deal = new Deal();
deal = PopulateDealDetails(deal);
DealReturnResults dealioReturnResults = null;
DealioLibClient dealioServiceProxy = new DealioLibClient();
try
{
ValidationErrorList validationErrorList =
dealioServiceProxy.ValidateDealDetails(deal);
}
catch(Exception e)
{
}
}
Can anyone tell me what is going on ? I don't think this should be very hard to call a WCF Service.
If you look at the Microsoft Documentation, they have the below example that shows how to connect basichttpbinding to SSL
<system.serviceModel>
<services>
<service
type="Microsoft.ServiceModel.Samples.CalculatorService"
behaviorConfiguration="CalculatorServiceBehavior">
<endpoint address=""
binding="basicHttpBinding"
bindingConfiguration="Binding1"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
</service>
</services>
<bindings>
<basicHttpBinding>
<!-- Configure basicHttpBinding with Transport security -- >
<!-- mode and clientCredentialType set to None.-->
<binding name="Binding1">
<security mode="Transport">
<transport clientCredentialType="None"
proxyCredentialType="None">
<extendedProtectionPolicy
policyEnforcement="WhenSupported"
protectionScenario="TransportSelected">
<customServiceNames></customServiceNames>
</extendedProtectionPolicy>
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
try to add the following code snippets when invoke the web service via adding the service reference.
Client-side.
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
try
{
var result = client.SayHello();
Console.WriteLine(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Feel free to let me know if the problem still exists.

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.

WCF web service custom authorization

I have WCF webservice using windows authentication and custom ServiceAuthorizationManager. Everything works fine, but if overridden CheckAccessCore returns false, I get error 500, instead of 401 as I expected. Service does not implement any service level error handling. How can I send 401 instead of 500 header?
Service config:
<!-- App configuration-->
<system.web>
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="Off" />
</system.web>
<appSettings>
<!-- Allowed users divided by comma -->
<add key="allowedUsers" value="DOMAIN\User1, DOMAIN\User2" />
</appSettings>
<!--Webservice-->
<system.serviceModel>
<services>
<service name="WebService.ApiService">
<endpoint binding="basicHttpBinding" bindingConfiguration="AuthenticatedBinding" bindingNamespace="http://namespace.com/customapi" contract="WebService.IApiService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceAuthorization serviceAuthorizationManagerType="WebService.Model.Services.AuthorizationService, WebService" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="AuthenticatedBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>
Custom authorization manager:
class AuthorizationService : ServiceAuthorizationManager
{
private List<string> allowedUsers = new List<string>();
public AuthorizationService() : base()
{
Configure();
}
protected override bool CheckAccessCore(OperationContext operationContext)
{
base.CheckAccessCore(operationContext);
return allowedUsers.Contains(operationContext.ServiceSecurityContext.WindowsIdentity.Name);
}
private void Configure()
{
var configRow = ConfigurationManager.AppSettings["allowedUsers"];
var parts = configRow.Split(',');
if (parts.Length > 0)
{
foreach (var part in parts)
allowedUsers.Add(part.Trim());
}
}
}
Result image:
I found on the web that error code 500 is the proper way how to send SOAP fault response. So everything is fine with my webservice (I am getting 'Access denied' fault with error code 500).
SOAP specification about it
Summary on Martin Karpiseks blog

Configuring WCF 4 with routing (global.asax) for both http & https endpoints

I'm still a newbie with wcf and not too well informed in .net in general. I have a WCF 4 web service that uses the global.asax routing approach and very simplified web.config using the standard endpoint method. This wcf service runs as an application with the default web site on iis 7.5 at present. I need it support both http and https interfaces, if possible. If that's too complex then only https. How is that best handled maintaining the current approach?
The contents of the global.asax.cs and web.config files are pretty basic:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
// Edit the base address of Service1 by replacing the "ippay" string below
RouteTable.Routes.Add(new ServiceRoute("myservice", new WebServiceHostFactory(),
typeof(myservice)));
}
}
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" contentTypeMapper="myservice.Util.RawMapper,myservice">
</standardEndpoint>
</webHttpEndpoint>
</standardEndpoints>
I found the answer: you just need to put this snippet in your web.config in the serviceModel tag:
<bindings>
<webHttpBinding>
<binding>
<security mode="Transport" />
</binding>
</webHttpBinding>
</bindings>
Thanks to this post: http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/1dd991a1-e32f-4035-a406-994729858b40
My full web.config is this:
<?xml version="1.0"?> <configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" /> </system.web>
<system.webServer>
<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"/>
<bindings>
<webHttpBinding>
<binding>
<security mode="Transport" />
</binding>
</webHttpBinding>
</bindings>
<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">
<security mode="Transport" >
</security>
</standardEndpoint>
</webHttpEndpoint>
</standardEndpoints> </system.serviceModel> </configuration>
The above works if you don't want both HTTP and HTTPS. In my case I want both, because some services require SSL (authentication) and others don't as the information they provide is not sensitive. The authentication services implementation do they own validation and refuse to answer if the request didn't come from an https scheme.
The bellow configuration works if you want to setup both HTTP and HTTPS on the same endpoint.
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding>
<security mode="Transport" />
</binding>
<binding name="UnsecureBinding"></binding>
</webHttpBinding>
</bindings>
<protocolMapping>
<add scheme="http" binding="webHttpBinding" bindingConfiguration="UnsecureBinding" />
</protocolMapping>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>