Monday, August 4, 2014

Extension Methods and Namespaces

When working with Extension Methods, they will not be available unless you import the namespace in which they are found.  Extension methods appear that they are part of the object you are using but they are actually in a totally different module.  So, they won't show up in intellisense or complile or that matter if you don't import the namespace.

Friday, August 1, 2014

Setting up a secure WCF web service from "scratch" with ASP.NET Identity

For this example, I'm using Visual Studio 2013 with Update 2 installed.  Update 2 will ensure that the templates use the latest and greatest versions of all technologies involved.

Add a project using the WCF Service Application template.  You could also use the Asp.Net Web Application template, but I think you'll just end up with a bunch of extra references you don't need.  Now take a look at the web.config file.  You'll notice that using this template automatically adds the protocolMapping element which allows the service to be accessed using https.  If you did not use this template, you would have had to add this for https support.  You'll also notice that there are no endpoints or bindings configured.  That's because WCF has default bindings and IIS can determine the endpoint by examining the .svc file.

I delete the sample service created for you.

Next, I find it convenient to host the web services I'm developing on my local IIS.  Click on My Project, Web tab, and type http://{name of your computer}.{domain}.{com}/{something meaningful}.  It is important to use the fully qualified name of your computer because the certificate you will soon use is named the same and WCF won't like it if they are not the same.  Click Create Virtual Directory.  Open up IIS Manager, and change the app pool of the site to one with an associated identity of your (hopefully powerful) account.  This becomes important when you connect to a database for authentication.

Add your web service by using the WCF Service template.  Build the solution, and right click the service.  Choose View in Browser to make sure all is well so far.

Now it's time to enable SSL (https).  Read here to do this.  At this point, you'll want to change the Project URL to include https on the Web tab when you go to My Project.  I think it's a good idea to go ahead and setup a binding configuration and an endpoint.  As I said earlier, WCF can figure all this out because of default values.  However, Visual Studio's Add Service Reference automatic proxy generator can get confused when you are setting up a client.  You can either use the Microsoft Service Configuration Editor (Right click web.config and choose Edit WCF Configuration) tool or edit the web.config by hand.  If you use the tool, just click the Service folder, and choose Create a New Service.  This will walk you through a wizard to create the service node.  After that there is a link to create the binding configuration.  You end up with this inside the <system.serviceModel> element:

    <bindings>
      <basicHttpsBinding>
        <binding name="BasicHttpsBindingConfig" />
      </basicHttpsBinding>
    </bindings>
    <services>
      <service name="AssemblyName.YourService">
        <endpoint address="https://ComputerName.domain.whatever/IISSite/YourService.svc"
          binding="basicHttpsBinding" bindingConfiguration="BasicHttpsBindingConfig"
          contract="AssemblyName.IYourService" />
      </service>
    </services>

You also need to set the multipleSiteBindingEnabled to False when you are using https:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />

At this point, I would create a little test app in a completely different solution and make sure you can call your new web service.  A Windows Console app will work great.  Just Add, Service Reference and specify the endpoint of the service.  By adding the reference, Visual Studio will add the following to your app.config file:

        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpsBinding_IYourService">
                    <security mode="Transport" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="https://ComputerName.domain.whatever/IISSite/YourService.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpsBinding_IYourService"
                contract="BenefitsServiceReference.IYourService" name="BasicHttpsBinding_IYourService" />
        </client>

There are a couple of things to note here.  Why does the client configuration set up for basicHttpBinding when the server configuration is set up for basicHttpsBinding?  Essentially basicHttpBinding and basicHttpsBinding are exactly the same.  The only difference is that basicHttpsBinding includes the <security mode="Transport" /> by default.

Now that the web service is up and running with SSL we want to configure it to require credentials in order to access it.  You can use the ASP.NET Membership, but this has been superceded by ASP.NET Identity and WCF doesn't directly interface with ASP.NET Identity yet.  So, we will create a custom user name and password validator which we will eventually use to authenticate with ASP.NET Identity.  First, we need to create the validator class itself.  Add references to the following:
  • System.IdentityModel
  • System.IdentityModel.Selectors
Add this class to your project:

Imports System.IdentityModel.Selectors
Imports System.ServiceModel

Public Class CustomUserNameValidator
    Inherits UserNamePasswordValidator

    Public Overrides Sub Validate(userName As String, password As String)

        If Not (userName = "Steve" AndAlso password = "topsecret") Then

            Throw New FaultException("Unknown Username or Incorrect Password")

        End If

    End Sub

End Class

It's pretty obvious what is happening here.  If your User Name and Password is not right, an exception gets thrown back to the client.  Now we have to configure the web service to use this.  First of all we need to edit our binding configuration.  Remember that by default basicHttpsBinding uses Transport as the Security mode.  We need to change this to TransportWithMessageCredential.  We are protecting (SSL) the service at the transport (IIS) level and authenticating at the message (web service) level.  Here is the binding configuration after we do that:

    <bindings>
      <basicHttpsBinding>
        <binding name="BasicHttpsBindingConfig">
          <security mode="TransportWithMessageCredential" />
        </binding>
      </basicHttpsBinding>
    </bindings>

You also need to add a serviceCredentials behavior to your existing behavior element:

    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom"
              customUserNamePasswordValidatorType="AssemblyName.CustomUserNameValidator, AssemblyName" />
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>

As with most configuration changes, here you're definitely better off using the Service Configuration Editor tool.  This is where we specify our custom class for validating the user name and password.  Note the specific way that the class is specified along with the assembly that contains the class.

The only configuration change in your client console app is changing the security mode to "TransportWithMessageCredential".  When you run your console, you will notice that you'll get an exception if you fail to provide credentials.  To specify the client's credentials, do the following:

        YourServiceProxy.ClientCredentials.UserName.UserName = "Steve"
        YourServiceProxy.ClientCredentials.UserName.Password = "topsecret"

If the client provides accurate credentials, then the service will return results; otherwise, an exception will be thrown.

With this infrastructure in place, you can change the code in the CustomUserNameValidator class to connect to any database you want to authenticate.  I mentioned earlier my desire to access ASP.NET Identity to authenticate users for the web service.  In a separate solution, I have set up an ASP.NET MVC Web Application and configured it with ASP.NET Identity authentication.  I am going to use this web application to administer user accounts for my web service.  I simply add this class to my MVC project:

Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework

Public Module SecurityManager

    Public Function IsAuthenticated(userName As String, password As String) As Boolean

        Dim MyUserStore As UserStore(Of IdentityUser) = New UserStore(Of IdentityUser)
        Dim MyUserManager As UserManager(Of IdentityUser) = New UserManager(Of IdentityUser)(MyUserStore)

        Dim MyUser As IdentityUser = MyUserManager.Find(userName, password)

        If MyUser Is Nothing Then
            Return False
        Else
            Return True
        End If

    End Function

End Module

Now, if I can call this function from my CustomUserNameValidator in my WCF project, I will be authenticating using ASP.NET Identity.  First add a reference to the dll produced by building the MVC project.  Then, simply add this code to your CustomUserNameValidator:

        If Not SecurityManager.IsAuthenticated(userName, password) Then
            Throw New FaultException("Unknown Username or Incorrect Password")
        End If

Of course, it's not quite that easy.  You need to do two more things:
  1. Use NuGet to install the same version of Entity Framework that your MVC project uses.  This will setup your web.config with some special Entity Framework stuff that you will need.
  2. Copy the connectionStrings section out of the MVC web.config file and put it into the WCF web.config file.  This connection string contains the database where the identity data is.
To get the name of the user who is accessing your service use this line:

System.ServiceModel.ServiceSecurityContext.Current.PrimaryIdentity.Name

So there we go.  We now have a secure web service.  Only accessible via https and secured by credentials stored in an ASP.NET Identity database.

Wednesday, July 30, 2014

Protect a WCF service using SSL - Part 2

In a prior post, I described how to protect a WCF service using SSL.  In the service .config file, you must do the following in order to expose the https endpoint:

<configuration>
  <system.serviceModel>
    <protocolMapping>
      <add scheme="https" binding="basicHttpsBinding" />
    </protocolMapping>
  </system.serviceModel>
</configuration>

The client configuration also needs some specific settings:

    <system.serviceModel>
        <bindings>
          <basicHttpsBinding>
            <binding name="BasicHttpsBinding_IDayOfTheWeekService"></binding>
          </basicHttpsBinding>
        </bindings>
        <client>
            <endpoint address="https://computername.yourdomain.net/WcfSecureServer/DayOfTheWeekService.svc"
                binding="basicHttpsBinding" bindingConfiguration="BasicHttpsBinding_IDayOfTheWeekService"
                contract="DayOfTheWeekReference.IDayOfTheWeekService" name="BasicHttpsBinding_IDayOfTheWeekService" />
        </client>
    </system.serviceModel>

Note that I am using basicHttpsBinding.  This just came out with .NET 4.5.  It's exactly the same as basicHttpBinding except the <security mode="Transport" /> is default so you don't have to specify this.  Also, if you generate your own certificate, you will get an error message that says something like:
Could not establish trust relationship for the SSL/TLS secure channel with authority 'localhost'
This is because WCF doesn't trust your self generated cert.  However, if you generate a certificate with the name of the computer that it is issued to, and specify the fully qualified name of the computer in the URL like I did above, WCF will allow it.

Tuesday, July 29, 2014

Specify ASP.NET timeout

ASP.NET will only allow a request to execute for 110 seconds by default.  This can be easily extended in the web.config with the following attribute:

<configuration>
  <system.web>
    <httpRuntime executionTimeout="300" />
  </system.web>
</configuration>

This example sets the timeout to 300 seconds.

Friday, July 18, 2014

WCF and ASP.NET Web API

When writing web services using .NET technology, you have a few options.

WCF:  Tried and true, this is the successor to the original ASMX style web services.  WCF has capabilities to create any type of service that can be accessed over a network, not just HTTP.  WCF tends to be a bit configuration heavy requiring the use of a special tool in Visual Studio to set the myriad of options up.  WCF generally uses the SOAP protocol.  While it is possible to create a REST style web service using WCF, it is recommended by Microsoft to use Web API technology for REST style web services.

ASP.NET Web API:  Web API allows you to create a REST style web service (no SOAP support) using an architecture that is very similar to MVC.  You create a set of controllers and configure a routing system to create your operations and accept parameters.  This tends to be simpler to setup and configure as it is very close to what you would do to configure an MVC web application.

There are also a couple of terms that need to be defined:

REST style web service:  When you apply a REST architecture to a web service, this changes the way in which the client calls the operations of the web service.  With a traditional web service, each call is represented by an HTTP GET verb with the URL that represents the name of the operation.  With a REST style web service, the URL represents a set of operations that are differentiated by the use of 4 different HTTP verbs (GET, POST, PUT, and DELETE).   I believe that the advantage of REST is that it is (allegedly) easier and makes more sense when called from client side code like JavaScript.  Therefore, it can be consumed by a wider variety of devices.  Also REST is necessary when implementing a data API using the OData protocol.

OData Protocol:  OData is set of specifications for creating a data API.  A data API is a service that exposes your database more directly over the web.  Instead of abstract operations that perform CRUD operations on the callers behalf, the data API allows the consumer to perform the CRUD operations nearly directly.  For example, each table could be represented as a URL and the user could query the table directly or even join together multiple tables.  This has the effect of moving the business logic to the client.

Conclusions

Using OData to access a database over the internet sounds like it could be useful.  And obviously you need to use REST in order to implement this.  However, setting up an OData endpoint using Web API is anything but straight forward right now.  In my opinion, this technology needs to mature a little longer for me to recommend using it.

If you're not going to use OData, then I just don't see the big advantage of using REST.  It seems to me that it would be awkward to organize your operations into sets of four HTTP verbs.  Another big disadvantage to using REST, is that there is no automatic proxy generation for consumers of REST style services.  Web API does seem like it works well, but it requires a REST style architecture.

This is my bottom line:  If you want to use a REST architecture, use Web API.  If you want to use a SOAP architecture, then use WCF.  At this time, I will continue to use SOAP and therefore WCF.

Wednesday, July 16, 2014

WCF Message Tracing

Message Tracing logs details on each communication in and out of the web service.  When making significant configuration changes, it is almost always best to use the Microsoft Service Configuration Editor to edit the web.config.  In many cases, it is just not practical to edit the web.config directly.  To access the editor, in the Visual Studio Solution Explorer, right click the web.config of the service and click Edit WCF Configuration.

To configure message tracing, follow these steps in the Configuration Editor:

  1. In the Diagnostics folder, click Message Logging and set LogEntireMessage to True.  Also set LogMessagesAtServiceLevel and/or LogMessagesAtTransportLevel to True, depending on your needs.  Most of the time these messages will be identical.  If you are encrypting at the message level, then the message logged at the transport level will be encrypted.  If you are encrypting at the transport level, then both will be unencrypted and practically identical.  The Transport Level is the host level.  So this is logged when the host (IIS in most cases) redirects the message to the service.  The Message Level is the actual service level.
  2. In the Diagnostics folder, right-click Sources and choose New Source.
    • From the drop down, choose System.ServiceModel.MessageLogging
    • Choose Verbose as the Trace Level.
  3. In the Diagnostics folder, right-click Listeners and choose New Listener.
    • Type "MessageLog" as the Name.
    • In the InitData field, use the browse button to set a path and filename of the logfile.
    • TraceOutputOptions:  Click the drop down and select which options you want.  I just like to include the DateTime
    • TypeName:  Click the ellipses and choose System.Diagnostics.XmlWriterTraceListener
To view the log file, you want to use a tool called Microsoft Service Trace Viewer.  I believe this is included with Visual Studio.  To find it just do a search using the start button for Service Trace Viewer.  Or try just right-clicking the log file and choosing Open.

An alternative way to accomplish this is:

  1. Click the Diagnostics folder and then click the Enable Message Logging link.
  2. Set the Log Level by clicking the link next to the "Log Level:" label and only check the Service messages box.
  3. Click on the link of the listener, and choose a location and options as described above.
  4. You may also want to click the Message Logging node and choose Log Entire Message.
  5. You may also want to click the Source that was created and select Verbose.



UPDATE 7/22/2015:  Curiously, I couldn't find it on a PC that I know has .NET installed.  I found it here:  C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools

UPDATE 7/24/2015:  Added the alternative method of setting up tracing.  I had some issues getting the standard method to work.

Tuesday, July 15, 2014

Protect a WCF service using SSL - Part 1

We have a scenario where we are exposing a WCF service over the internet that is hosted in IIS.  We want the communication with the service to be protected using SSL.  The encryption/decryption is handled completely by IIS, so there is minimal need to edit the configuration of the service itself (See Part 2).  First you need a certificate.  To create your own for testing:

  1. Open IIS (as administrator).
  2. Choose the top level node in the Connections pane.
  3. Click Server Certificates in the IIS section of the middle pane.
  4. Click Create Self Signed Certificate.  The friendly name should match the name of the computer.
Now configure SSL:
  1. Right click Default Web Site and choose Edit Bindings.
  2. Click Add, choose HTTPS, and select the certificate you just created.
Finally, set up your service to require SSL:
  1. Click on the web application that hosts your service.
  2. In the middle pane, IIS section, double click on SSL Settings and check the "Require SSL" box.