Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

Tutorial and Articles about Windows Hosting, SQL Hosting, MVC Hosting, and Silverlight Hosting

WCF Hosting with ASPHostPortal.com :: How to Secure WCF Service on IIS

clock May 21, 2014 13:24 by author Kenny

In this article i will explain about how to secure WCF Service on IIS. That is typically an easy requirement but I had a couple of restrictions:

- Only BasicHttpBinding could be used on the client-side
- Client credentials (username / password) must be sent and validated with each request


Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.

One option is to send and validate the credentials as parameters to each method. This method is usually seen as unacceptable because credentials are passed across the service as plain-text. Do you want your password sent over a web service as plain-text?

After doing some research, I came up with a solution that is largely a combination of two sources: configuring a WCF service on IIS with SSL and username authentication over BasicHttpBinding… I’ll do my best to consolidate both of those sources for simplicity.

Programming / Configuring the WCF Service
1. Open Visual Studio.
2. Create a new ‘WCF Service Application’ project.
3. Define a service interface:

using System.ServiceModel;
namespace Brett.Service
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);
    }
}


4. Implement your service interface. Our  GetData method will return a string that shows the authenticated username and the integer value passed. If the current identity is not authenticated, we throw an exception (this is not our validation method, that is shown shortly):
using System;
using System.ServiceModel;
namespace Brett.Service
{
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("{0} entered: {1}", GetCurrentUserName(), value);
        }
        private string GetCurrentUserName()
        {
            var primaryIdentity = ServiceSecurityContext.Current.PrimaryIdentity;
            if (primaryIdentity.IsAuthenticated)
            {
                return primaryIdentity.Name;
            }
            else
            {
                throw new Exception(@"User is not authenticated...");
            }
        }
    }
}

5. Implement a custom credential validator. The class needs to extend the abstract class UserNamePasswordValidator . The important implementation detail here is that you want to throw a FaultException  if the credentials are incorrect:
using System.IdentityModel.Selectors;
using System.ServiceModel;
namespace Brett.Service
{
    public class CustomValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            if (userName != @"hello")
            {
                throw new FaultException(@"User name must be 'hello'.");
            }
        }
    }
}


6. Edit your web config file. This is probably the most tedious portion of the process. I’ll go ahead and attach the whole file here:
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="Brett.Service.Service1"
               behaviorConfiguration="Brett_Behavior">
        <endpoint address=""
                  binding="basicHttpBinding"
                  bindingConfiguration="Brett_BindingConfiguration"
                  contract="Brett.Service.IService1" />
        <endpoint address="mex"
                  binding="mexHttpsBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="Brett_BindingConfiguration">
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Brett_Behavior">
          <serviceMetadata httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom"
                                    customUserNamePasswordValidatorType="Brett.Service.CustomValidator,
Brett.Service"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
</configuration>


Some important things to note here… We expose two endpoints – one for the BasicHttpBinding and one for service metadata (mex). We are using BasicHttpBinding  withTransportWithMessageCredential  security (that further specifies a message credential type ofUserName ). The service credentials point to our CustomValidator . This is the absolute minimum needed for me to get the web service working – all elements were needed.

7. Publish the project somewhere local on your machine (right-click project, publish).

Configuring IIS for WCF Service with SSL
1. Follow instructions in this guide, until you reach ‘Configure WCF Service for HTTP Transport Security’ (don’t do that part). I would list these out myself, but I think the visuals provided in the link are very helpful.
2. I ended up having some file access issues with my application pool, so I ended up making my application pool run as an administrator identity.

Programming / Configuring the WCF Client
1. Open Visual Studio.
2. Create a new ‘Windows Console Application’ project.
3. Add a new service reference – use the location of your WCF Service that is hosted with IIS. The metadata for the service has been downloaded and an app.config file has been produced. We won’t use the app.config.

Program the console application to make a call to the service:
using Brett.Client.ServiceReference1;
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace Brett.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);
            var endpointAddress = new
EndpointAddress(@"https://localhost/WhateverYouNamedThis/Service1.svc");
            using (var service = new Service1Client(binding, endpointAddress))
            {
                var loginCredentials = new ClientCredentials();
                loginCredentials.UserName.UserName = @"hello";
                loginCredentials.UserName.Password = @"brett's password";
                var defaultCredentials = service.Endpoint.Behaviors.Find<ClientCredentials>();
                service.Endpoint.Behaviors.Remove(defaultCredentials); //remove default ones
                service.Endpoint.Behaviors.Add(loginCredentials); //add required ones
                var data = service.GetData(100);
                Console.WriteLine(data);
                Console.ReadLine();
            }
        }
    }
}



Visual Studio 2010 Hosting :: Deploying a WPF Application Using Click-Once Deployment Technology in Microsoft Visual C# 2010 Express

clock November 14, 2013 05:07 by author Ben

Click -Once Enables Web - style application deployment for non - web applications. Applications are published to and deployed from a web or file servers . Although Click Once does not support the full range of features that client applications installed by the Windows Installer does , it does support a subset that includes the following :

  1. Integration with the Start menu and Programs Control Panel .
  2. Versioning , rollback , and Uninstallation .
  3. Online install mode , that always launches an application from the deployment location .
  4. Automatic updating when new versions are released.
  5. Registration of file extensions .

Before proceeding for the deployment , Ensure that your application has been built properly and ready for the deployment . Explains this article with respect to Game in a WPF and the game name is Mr . Gunner .

1.
In Solution Explorer, right-click the project name and select "Properties" as shown in the following snapshot.



2. After clicking on Properties a Publishing Window will open and it has various options, such as Application, Built, Security, Publish and so on. as you can see in the following snapshot.



3. To set an icon for your application, browse for the suitable icon for your application. To set the icon, click on the application and browse the icon (the icon should be a .ico file) , if you don't want to set an icon  for the application then it will be deployed with a default icon in your application as I highlighted with red circles in the following snapshot.



4: Then click on "Publish". Here select the publishing location nothing but browse the folder where you want keep the setup file and other application files and after selecting the publish location then click on the "Publish Wizard" to proceed as shown in the highlighted red circles.



5. After clicking "Publish" a wizard window will open, then click on the "Next" button as shown in the following snapshot:



6.  After selecting CD-ROM or DVD then click "Next" to proceed as shown in the following snapshot:



7. After selecting "Updates" Click "Next" to proceed to the final step as shown in the following snapshot.



8. Now, finally click on the "Finish" button to complete the Publish Wizard as shown in the following snapshot.



Finally, a setup file has been created on the selected folder. Now you can install the application on your system by clicking on the setup file. Have fun working with the installed application.



WCF Hosting Trial - ASPHostPortal.com :: Consuming AJAX-Enabled WCF Services from both Client and Server

clock October 24, 2013 11:38 by author Ben

This is a simple example of an Ajax-Enabled WCF Service (hosted in IIS) that can be consumed using both client-side and server-side code.

1. Add a WCF Service Application project to the solution called FooService

2. Delete everything in the service project’s web.config file.

 

a. Create a class file called FooServiceOne.cs
b. Replace the code with this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace GooberFoo.FooServices
{

    [ServiceContract(Namespace = "GooberFoo.FooServices")]
    public interface IFooServiceOne
    {
        [OperationContract]
        double Add(double n1, double n2);
    }

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class FooServiceOne : IFooServiceOne
    {
        public double Add(double n1, double n2)
        {
            return n1 + n2;
        }
    }
}

c. Create another file called FooServiceOne.svc and past the following code into the file.

<%@ServiceHost
         language="C#"
         Debug="true"
         Service="GooberFoo.FooServices.FooServiceOne"
         Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
 %>

d. Save and Compile

3. Host in IIS

a. Make sure "Enable anonymous access" is checked.
b. Make sure "Integrated Windows authentication" is unchecked.
c. Test the service by navigating to http://*******:90/FooServiceOne.svc
d. The service will be displayed with the message "Metadata publishing for this service is currently disabled."

4. Access the service from the client-side code

a. Create an Empty ASP.NET Web Application in your solution.
b. Drag and drop an AJAX Extensions ScriptManager control into your web page.
c. In the ServiceReference Collection Editor, set the path to http://********:90/FooServiceOne.svc
d. Drag and Drop an ASP.NET button and Label control on the page.

 <asp:Button ID="Button1" runat="server" OnClientClick="return Button1_Click();" Text="Add 5 and 7" />
 <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

e. Add client-side script. 

<script language="javascript" type="text/javascript">
     function onSuccess(result) {
       document.getElementById('<%=Label1.ClientID %>').innerHTML = result;
     }
     function Button1_Click() {
       var proxy = new GooberFoo.FooServices.IFooServiceOne();
       proxy.Add(parseFloat(5), parseFloat(7), onSuccess, null, null);
       return false;
     }
 </script>

f. Compile and test.

5. Modify the service project to allow server-side code to consume the service

Change the service project's web.config file to look like this.

<?xml version="1.0"?>
        <configuration>
          <system.serviceModel>

            <bindings>
              <basicHttpBinding>
                <binding name="basicHttpBinding" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                  <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                      maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                  <security mode="None">
                    <transport clientCredentialType="None" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="UserName" algorithmSuite="Default" />
                  </security>
                </binding>
              </basicHttpBinding>
            </bindings>

            <behaviors>
              <serviceBehaviors>
                <behavior name="AspNetAjaxBehavior" >
                  <serviceMetadata httpGetEnabled="true" />
                </behavior>
              </serviceBehaviors>

              <endpointBehaviors>
                <behavior name="AspNetSOAPBehavior">
                </behavior>
              </endpointBehaviors>
            </behaviors>

            <services>
              <service name="GooberFoo.FooServices.FooServiceOne" behaviorConfiguration="AspNetAjaxBehavior" >
                <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
                <endpoint address="soapreq" behaviorConfiguration="AspNetSOAPBehavior" bindingConfiguration="basicHttpBinding"
                          binding="basicHttpBinding" contract="GooberFoo.FooServices.IFooServiceOne" name="GooberFoo.FooServices.IFooServiceOne" />
              </service>
            </services>
          </system.serviceModel>
        </configuration>

6. Test the Service

a. In IE, open the URL http://*******:90/FooServiceOne.svc.
b. You will see the FooServiceOne Service page along with instructions to use svcutil.exe http://*******:90/FooServiceOne.svc?wsdl

7. Add the Web Reference to your asp.net web application

a. In your web application, "Add Service Reference".
b. Use http://GooberServer:90/FooServiceOne.svc?wsdl
c. Click Go.
d. Use FooServiceOneRef as the namespace.
e. Click OK.
f. View web application’s web.config file.

8. Use server-side C# code to consume the service in your web application

a. Add Button control to the page along with a button click event.

 <asp:Button ID="Button2" runat="server" Text="Add 10 and 13" onclick="Button2_Click" />

b. The button click event will look like this:

protected void Button2_Click(object sender, EventArgs e)
 {
   FooServiceOneRef.FooServiceOneClient mySvc = new FooServiceOneRef.FooServiceOneClient();
   Label1.Text = Convert.ToString(mySvc.Add(10, 13));
 }

c. Compile and test.



About ASPHostPortal.com

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions

 photo ahp banner aspnet-01_zps87l92lcl.png

Author Link

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Sign in