Sunteți pe pagina 1din 19

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

1 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Articles Platforms, Frameworks & Libraries Windows Communication Foundation General

Self Hosted WCF Service as Windows Service with custom Authentication


Murugan Sivananantha Perumal, 30 Aug 2015

CPOL

2.2K

4.00 (1 vote)

Self Hosted WCF Service as Windows Service with custom User Authentication over Http.
Download source MSMSystemServices.rar

Introduction
In this article, I want to demonstrate a very simple WCF Server / Client application but this demo application is intended to demonstrate about the Self
hosted service. You may raise a question "what is self hoting ?". Let me explain in detail.
There are two ways to host a WCF Service; they are;
1. Hosting with IIS : The traditional way to host a WCF web service.
2. Self Hosting : An alternate way to host a service with no IIS.
What is self hosting ?
Hosting a service inside a managed application is known as self-hosted service. A managed application either can be a Console Application, Windows Forms
Application, WPF or Windows Service. Check out this link on MSDN for more details and check this MSDN link for sample code.

There is a detailed discussion on this asp.net forum regarding the differences between self-hosted and IIS hosted services.

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

2 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Lets move to WCF;


WCF has two zones:
1. Services
2. Clients

1. Service
The basic steps to make a Service live.
1. Define a service contract
2. Implement a service contract
3. Host and run a service contract

2. Clients
WCF Clients is an application which can communicate with WCF Service operations as method.
The dynamic WCF Client communication to the Service has three steps:
1. Create a WCF Client using channel factory class ( System.ServiceModel.ChannelFactory )
2. Configure a WCF Client
3. Use a WCF Client

In this article, I'm going to use Windows Service as managed application to host the WCF service.
The source code contains Windows Service and Self Hosted WCF Service on Http.
All examples are programmed in Visual Basic .Net,
Sample sends the requests / responses via Port 9090 over Http.
Sample uses dynamic connection string using INI file and uses simple AES Cryptography for password encryption / decryption.
Topics of hosting on Https is not covered.
After reading this article and studying the samples, you may get an idea to create self hosted web service with custom authentication on windows
service.

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

3 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Background
Recently, I had a requirement to host a service with authentication where I didnt have IIS and the solution is to have self hosted WCF service which use
custom user authentication and the clients can consume it dynamically using channel factory method.

Server Side
So, lets start with WCF Service. Create a WCF Service Library project and then add the below references and name the Project as MSMSystemService.
1. System.ServiceModel
2. System.IdentityModel
3. System.IdentityModel.Selectors
WCF Library Project

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

4 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

1. Add an Interface (IDataServices.vb) to the Project and define the Service Contract
In this example, I had used the data class from MSMSystemService.DataModels.Academics.
Imports System
Imports System.ServiceModel
Imports MSMSystemService.DataModels.Academics

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

5 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Namespace MSMServices
<servicecontract()>
Public Interface IDataServices
' TODO: Add your service operations here
<operationcontract()>
Function GetPupilData(ByVal lngStudentID As Long) As StudentInfo
End Interface
End Namespace

2. Add a data class (DataServices.vb) and Implement the Service Contract


In this example, the class DataServices returns the data from MSMSystemService.DataModels.Academics.StudentInfo data class.
Imports MSMSystemService.DataModels.Academics
Namespace MSMServices
Public Class DataServices
Implements IDataServices
Public Function GetPupilData(ByVal lngStudentID As Long) As StudentInfo Implements IDataServices.GetPupilData
Dim oStudent As New StudentInfo
oStudent.StudentID = lngStudentID
oStudent.Fill()
Return oStudent
End Function
End Class
End Namespace

3. Custom Authentication
Add an new class (MSMServiceAuthentication.vb) and Inherit the class System.IdentityModel.Selectors.UserNamePasswordValidator and
implement Validate subroutine. There is a custom exception class (MSMSecurityException) demonstrated for managing custom security token
validation faliure.

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

6 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Add the below code to MSMServiceAuthentication.vb.


Imports
Imports
Imports
Imports
Imports

System
System.Security
System.Security.Principal
System.IdentityModel
System.IdentityModel.Selectors

Namespace MSMServices
Public Class MSMServiceAuthentication
Inherits UserNamePasswordValidator
Public Overrides Sub Validate(userName As String, password As String)
If userName = "admin" And password = "admin" Then
'OK
Else
Throw New MSMSecurityException()
End If
End Sub
End Class
Public Class MSMSecurityException
Inherits Exception
Public Sub New()
MyBase.New("Invalid Security Token")
End Sub
End Class
End Namespace

The WCF service part is ready and the next job is to create an Managed Application which hosts the WCF service. In this case, Windows Service is going
to act as a Managed Application.
Add an new Windows Service project (name it as MSMServiceController) to MSMServiceController project and setup the ServiceName and Service
Description properties as described below.
4. Windows Service

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

7 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Set Service Properties


Open the Properties of the Service class MSMServiceController.vb and set "ServiceName" property to "MSMDataServices".

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

8 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Add Installer Class


Right click on Service class MSMServiceController.vb and select Add Installer.

Visual Studio will create an new class ProjectInstaller.vb with two components;
1. ProcessInstaller (Rename as MSMProcessInstaller)

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

9 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

2. Service Installer. (Rename as MSMServiceInstaller)

Open ProjectInstaller.vb class and set the Properties of Service Installer.


Note: The values set in ServiceName and Description properties will be displayed on the Windows Service Management console once the Windows
Service was installed.

Add the below code to windows service class. In this code, I have used a custom registry manager and custom INI file manager for reading the
connection string from INI settings file.
Note: Developers can use the WSHttpBinding class instead of BasicHttpBinding for Https hosting over SSL .

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

10 of 19

Imports
Imports
Imports
Imports
Imports
Imports
Imports
Imports
Imports

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

System
System.ServiceProcess
System.ComponentModel
System.Configuration
System.Configuration.Install
System.ServiceModel
System.ServiceModel.Description
MSMSystemService.MSMServices
MSMSystemService.Utilities

Public Class MSMServiceController


Dim sBAddress As Uri
Dim oSelfHost As ServiceHost 'New ServiceHost(GetType(DataServices), sBAddress)
Protected Overrides Sub OnStart(ByVal args() As String)
Dim
Dim
Dim
Dim
Dim
Dim

oSetting As New MSMSettingManager


oRegistry As New MSMRegistryManager
oWSHttpBind As New BasicHttpBinding
oSmb As ServiceMetadataBehavior
sFilename As String
sServiceURI As String

' Add code here to start your service. This method should set things
' in motion so your service can do its work.
Try
oRegistry.RegistryRootKey = SystemRegistryRoot.SystemLocalComputer
oRegistry.RegistryKeyPath = "SOFTWARE\MSMServices\DataService"
oRegistry.KeyName = "RootFolder"
oRegistry.ReadKey()
sFilename = oRegistry.keyValue
oSetting.SettingsFileName = Replace(sFilename & "\MSMServices.ini", "\\", "\")
oSetting.ApplicationName = "Service"
oSetting.KeyName = "URI"
sServiceURI = oSetting.ReadSettings()
If Trim(sServiceURI) <> "" Then
oWSHttpBind.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly
oWSHttpBind.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic
sBAddress = New Uri(sServiceURI)
oSelfHost = New ServiceHost(GetType(DataServices), sBAddress)

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

11 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

oSmb = oSelfHost.Description.Behaviors.Find(Of ServiceMetadataBehavior)()


If (oSmb Is Nothing) Then
oSmb = New ServiceMetadataBehavior
oSmb.HttpGetEnabled = True
oSelfHost.Description.Behaviors.Add(oSmb)
End If
oSelfHost.AddServiceEndpoint(GetType(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex")
oSelfHost.AddServiceEndpoint(GetType(IDataServices), oWSHttpBind, sBAddress)
oSelfHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode =
ServiceModel.Security.UserNamePasswordValidationMode.Custom
oSelfHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = New MSMServiceAuthentication()
oSelfHost.Open()
Else
EventLog.WriteEntry("MSM Data Service Error: Invalid URI Specified", EventLogEntryType.Error, 10255)
End If
Catch ex As Exception
EventLog.WriteEntry("MSM Data Service Error: " & ex.Message.ToString(), EventLogEntryType.Error, 10255)
End Try
End Sub
Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
If (oSelfHost IsNot Nothing) Then
If oSelfHost.State = CommunicationState.Opened Then
oSelfHost.Close()
End If
End If
End Sub
End Class

Windows Service part is complete, next step is to compile and test the code.

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

12 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Follow the below step to install and run the sample windows service.
1. Build the Solution and copy the compiled EXEs & Assemblies to a folder.
2. Run MSMServiceUtilities.exe to configure the dynamic URI and Database.
Note: Verify the port's availability before setting up the URI.
3. Click "Register Root" first and then click "Register Service".

Step 4: Use the below command from the folder to Install / uninstall the Windows Service;

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

13 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Step 5: Start the installed Windows Service and verify the status in the Event Viewer

Service Status in Event Viewer

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

14 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Client Side
Create an new Windows Forms Application project and design a form with the required fields;
Add the below references to the project;
Imports System.Net.Security
Imports System.ServiceModel

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

15 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Add the service reference with user authentication;

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

16 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

This service reference will create WSDL references to our DataServices web service.
This sample client appilcation deploys BasicHttpBinding class for creating Http traffic over custom authentication using ChannelFactory method.
Note: Developers can make this client application more dynamic by reading URI from INI file.
Code of the Click event of Get button.
Private Sub cmdGetStudent_Click(sender As Object, e As EventArgs) Handles cmdGetStudent.Click
Dim oWSHttp As New WSHttpBinding 'For Https access
Dim oBSHttp As New BasicHttpBinding 'For Http access

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

17 of 19

Dim
Dim
Dim
Dim

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

oDSClient As IDataServices
oURI As New Uri("http://192.168.1.92:9090/DataServices")
oDSStudent As New StudentInfo
oEndpoint As New EndpointAddress(oURI)

If Trim(txtStudentID.Text) <> "" Then


oBSHttp.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly
oBSHttp.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic
Dim oChFactory As New ChannelFactory(Of IDataServices)(oBSHttp, oEndpoint)
oChFactory.Credentials.UserName.UserName = "admin"
oChFactory.Credentials.UserName.Password = "admin"
oDSClient = oChFactory.CreateChannel()
oDSStudent = oDSClient.GetPupilData(Val(txtStudentID.Text))
txtFirstname.Text = oDSStudent.FirstName
txtMiddleName.Text = oDSStudent.MiddleName
txtLastname.Text = oDSStudent.LastName
txtGrnnumber.Text = oDSStudent.GRNNumber
txtGender.Text = ""
CType(oDSClient, IClientChannel).Close()
End If
End Sub

Client side coding part is complete, you can test the application now.

Points of Interest
Implementting WCF webservice over HTTPS (SSL) greatly improves the security, maintainability, scalability, and stability of the application.
Your feedback is always welcome.

License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

18 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Share
About the Author
Murugan Sivananantha Perumal
Software Developer (Senior) Wellcare Infotech LLC
United Arab Emirates
Murugan Shivananantha Perumal is from Chennai, India, He is Currently Working with Wellcare Infotech LLc, UAE., as
a Senior Software Architect
Murugan has 11+ yrs of experience in the IT industry working on Microsoft Technologies. He is involved in various
project activities like designing the system and technical architecture, leading technical front and doing core
development. He also has strong knowledge of ERP Domain.
Technical experience : Visual Basic 6, Classic ASP, Visual Basic .Net, C#, ASP.NET MVC 5 @Razor, Bootstrap, JQuery,
WCF and RESTFul Webservices, SSRS, SSIS Automation, Crystal Reports.

You may also be interested in...


WCF Hosting with Windows Service

AvePoint & Amazon Web Services: SharePoint in AWS

31/08/2015 14:54

Self Hosted WCF Service as Windows Service with custom Authentication - CodeProject

19 of 19

http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Service...

Create, Host (Self Hosting, IIS hosting) and Consume


WCF Service

Getting Started with the Intel Edison Board on


Windows

WCF Service with custom username password


authentication

Intel Edison Board User Guide

Comments and Discussions


1 message has been posted for this article Visit http://www.codeproject.com/Articles/1020342/Self-Hosted-WCF-Service-as-Windows-Servicewith-cu to post and view comments on this article, or click here to get a print view with messages.

Permalink | Advertise | Privacy | Terms of Use | Mobile


Web01 | 2.8.150819.1 | Last Updated 30 Aug 2015

Selecione o idioma

Article Copyright 2015 by Murugan Sivananantha Perumal


Everything else Copyright CodeProject, 1999-2015

31/08/2015 14:54

S-ar putea să vă placă și