Click here to Skip to main content
15,885,366 members
Articles / Security

Selfhosted Secure WCF by Id password, custom validation

Rate me:
Please Sign up or sign in to vote.
4.90/5 (14 votes)
16 Jul 2014CPOL1 min read 41.8K   23   14
No config file needed – all setting in code only, No IIS – Self hosted, consume by channel factory

Introduction

Selfhosted Secure WCF Custom validation, No config file needed – all setting in code only, No IIS – Self hosted, consume by channel factory

 

Background

I recently came in situation where I need to make Secure WCF POC in environment where we don’t have IIS and we have only VS 2010 Express. And we need to create totally self dependent POC so no certificate.

The solution is to create self hosted WCF service use custom validation and consume it by using Channel factory. While create this POC I got some error then I started searching internet for similar kind of POC I got couple of them but most of them Is not in ready to run position like have only server side code or have only client or need to change something in app.config.<o:p> 

 

WCF Server side 

 Image 1

Self hosted (console) WCF service,  Transport security (ID/Pwd) 

C++
using System;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.IdentityModel.Tokens;
using System.IdentityModel.Selectors;
using System.Security.Principal;
using System.ServiceModel.Description;
 
namespace SecurWCFSelfHosting
{
    class Program
    {
        [ServiceContract]
        public interface IDemoService
        {
            [OperationContract]
            int Add(int x, int y);
        }
 
        public class DemoService : IDemoService
        {
           public int Add(int x, int y)
            {
                return x + y;
            }
        }

        static void Main(string[] args)
        {
        
            // This is a address of our service
            Uri httpUrl = new Uri("http://localhost:999/MyService/");
            //Create ServiceHost
            ServiceHost host = new ServiceHost(typeof(DemoService), httpUrl);
            
            /// Set behaviour of **binding**
            BasicHttpBinding http = new BasicHttpBinding();
            //1. set Mode TransportCredentialOnly = no httpS 
            http.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            //2. Transport security Basic = user id and password
            http.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
            
             
            ///** Set behaviour of **host**
            //Add a service endpoint
            host.AddServiceEndpoint(typeof(IDemoService), http, "");
            host.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
            host.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new MyCustomValidator();
 
            // checking and publishing meta data
            ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
            if (smb == null)
            {
                smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                host.Description.Behaviors.Add(smb);
            }
            
            //Start the Service
            host.Open();
 
            Console.WriteLine(DateTime.Now.ToString()+" Service is host at " + httpUrl.ToString());
            Console.WriteLine("The service is running in the following account: {0}", WindowsIdentity.GetCurrent().Name);
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.ReadLine(); 
        }
    }
 
    public class MyCustomValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            //For Demo only here you can add logic to validate ID,Pwd in AD or DB
            if ((userName != "h") || (password != "p"))
            {
                throw new SecurityTokenException("Him:) Validation Failed!");
            }
            Console.WriteLine(DateTime.Now.ToString()+" Validation success for user :"+ userName);
        }
    }
}

 

Client side 

  Image 2

Consume in console apps, using channel factory 

C++
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
 
/// svcuti. @ C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin

namespace WCFConsumeByChannelFactory
{
    class Program
    {
        static void Main(string[] args)
        {
 
            EndpointAddress Serviceaddress = new EndpointAddress("http://localhost:999/MyService/");
 
            /// Set behaviour of **binding** Same setting as ##Server##
            BasicHttpBinding httpBinding = new BasicHttpBinding();
            httpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
            
            ChannelFactory<IDemoService> myChannelFactory =
                new ChannelFactory<IDemoService>(httpBinding, Serviceaddress);
            var defaultCredentials = myChannelFactory.Endpoint.Behaviors.Find<ClientCredentials>();
 
            //#1 IF this dosen not work then try #2
            myChannelFactory.Credentials.UserName.UserName = "h";
            myChannelFactory.Credentials.UserName.Password = "p";
 
            ///#2
            //ClientCredentials CC = new ClientCredentials();
            //CC.UserName.UserName = "h";
            //CC.UserName.Password = "p";
            // myChannelFactory.Endpoint.Behaviors.Remove(defaultCredentials); //remove default ones
            // myChannelFactory.Endpoint.Behaviors.Add(CC); //add required on

            // Create a channel.
            IDemoService wcfClient1 = myChannelFactory.CreateChannel();
 
            double s = wcfClient1.Add(73, 22);
            Console.WriteLine(s.ToString());
            ((IClientChannel)wcfClient1).Close();
 
            Console.ReadKey();
 
        }
    }
}

These all code is in attached zip file.

 

Points of Interest

While searching in internet i found this :How to: Call Operations Asynchronously Using a Channel Factory  http://msdn.microsoft.com/en-us/library/bb885132.aspx

Bindings Summary

 

http://wcfsecurityguide.codeplex.com/releases/view/15892 
Image 3
 

License

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


Written By
Technical Lead Sapient Global Market
United States United States
Himanshu Thawait is Associate Arch at Sapient Global Markets.

He is expert in developing EAI, BizTalk with EDI(HIPPA)., Web applications, Micro web services, Angular, ASP.NET MVC, C#, VB.NE T, VB 6, SQL Server, Oracle, No SQL, Classic ASP, XML and JavaScript, IBM MQSC, IBM DB2.

Comments and Discussions

 
QuestionDoes this solution require the server hosting the WCF to be ran as Administrator? Pin
Myron K. Crandall17-Jul-14 8:38
Myron K. Crandall17-Jul-14 8:38 
AnswerRe: Does this solution require the server hosting the WCF to be ran as Administrator? Pin
Himanshu Thawait29-Jul-14 4:14
Himanshu Thawait29-Jul-14 4:14 
QuestionQuestion regarding Security Mode ? Pin
Tridip Bhattacharjee16-Jul-14 21:49
professionalTridip Bhattacharjee16-Jul-14 21:49 
AnswerRe: Question regarding Security Mode ? Pin
Himanshu Thawait29-Jul-14 4:17
Himanshu Thawait29-Jul-14 4:17 
Questionsource code file link broken Pin
Tridip Bhattacharjee16-Jul-14 21:31
professionalTridip Bhattacharjee16-Jul-14 21:31 
GeneralMy vote of 5 Pin
w.jian16-Jul-14 19:54
w.jian16-Jul-14 19:54 
GeneralMy vote of 5 Pin
Altaf N Patel27-May-13 22:47
Altaf N Patel27-May-13 22:47 
Questiondownload broken Pin
Member 967590111-Dec-12 3:55
Member 967590111-Dec-12 3:55 
AnswerRe: download broken Pin
Himanshu Thawait11-Dec-12 4:41
Himanshu Thawait11-Dec-12 4:41 
GeneralRe: download broken Pin
Riana13-Jul-14 9:48
Riana13-Jul-14 9:48 
GeneralRe: download broken Pin
Member 1072351716-Jul-14 3:58
Member 1072351716-Jul-14 3:58 
AnswerRe: download broken Pin
Himanshu Thawait16-Jul-14 10:57
Himanshu Thawait16-Jul-14 10:57 
GeneralRe: download broken Pin
fredatcodeproject16-Jul-14 13:15
professionalfredatcodeproject16-Jul-14 13:15 
GeneralMy vote of 4 Pin
Christian Amado2-Aug-12 10:36
professionalChristian Amado2-Aug-12 10:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.