Click here to Skip to main content
15,891,700 members
Articles / Programming Languages / C#

Generate username authentication based on basicHttpBinding without certificate

Rate me:
Please Sign up or sign in to vote.
3.54/5 (7 votes)
24 Oct 2013CPOL1 min read 58.6K   16   18
Use basicHttpBinding to create an application for username authentication.

Introduction

A wizard to help you develop a complete WCF service and client based on basicHttpBinding without certificate.

Background

I took up a work to investigate WCF authentication with username. So I researched about basicHttpBinding and wsHttpBinding. In the following article, I will show you how to use wsHttpBinding to communicate with authentication.

And you may know how to build a WCF application. So, this article is not about how to build a WCF application, but how to build a custom username validator and how to build the configuration file.

Using the code

There are two parts of the application, the service part, and the client part.

In the server part, you could build a class named CustomUserNameValidator and inherit UserNamePasswordValidator. And implement the abstract method "Validate". And you can throw an exception when the username and password are invalid.

The custom validator code:

C#
public class CustomUserNameValidator : UserNamePasswordValidator
{
    private const string USERNAME_ELEMENT_NAME = "userName";

    private const string PASSWORD_ELEMENT_NAME = "password";

    private const string FAULT_EXCEPTION_MESSAGE = "UserName or Password is incorrect!";

    public override void Validate(string userName, string password)
    {
        Guarder.Guard.ArgumentNotNull(userName)
            .ArgumentNotNull(password);
        var validateUserName = ConfigurationManager.AppSettings[USERNAME_ELEMENT_NAME];
        var validatePassword = ConfigurationManager.AppSettings[PASSWORD_ELEMENT_NAME];
        var validateCondition = 
            userName.Equals(validateUserName) && password.Equals(validatePassword);
        if (!validateCondition)
        {
            throw new FaultException(FAULT_EXCEPTION_MESSAGE);
        }
    }
}

And the service configuration, you should notice the serviceCredentials element in serviceBehaviors and the security element in the binding element:

XML
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="customBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceCredentials>
            <userNameAuthentication 
              userNamePasswordValidationMode="Custom" 
              customUserNamePasswordValidatorType="EmployeesHost.CustomUserNameValidator, EmployeesHost"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings >
      <basicHttpBinding>
        <binding name="EmployeeQueryBinding_BasicHttp">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Basic"/>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="EmployeesHost.EmployeesQueryService" behaviorConfiguration="customBehavior">
        <!--For basic http binding endpoint-->
        <endpoint address="http://127.0.0.1:12215/EmployeeQuery" binding="basicHttpBinding" 
                  bindingConfiguration="EmployeeQueryBinding_BasicHttp"
                  contract="EmployeesHost.IEmployeesQueryService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://127.0.0.1:8733/Design_Time_Addresses/EmployeesHost/EmployeesQueryService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>
  <appSettings>
    <add key="userName" value="your user name"/>
    <add key="password" value="your password"/>
  </appSettings>
</configuration>  

And the client configuration, binding configuration should like the service:

XML
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="DefaultBinding_IEmployeesQueryService">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Basic"/>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <!--For basic http binding endpoint-->
      <endpoint address="http://127.0.0.1:12215/EmployeeQuery/"
                binding="basicHttpBinding" bindingConfiguration="DefaultBinding_IEmployeesQueryService"
                contract="IEmployeesQueryService" 
                name="DefaultBinding_IEmployeesQueryService_IEmployeesQueryService" />
    </client>
  </system.serviceModel>
  <appSettings>
    <add key="userName" value="your user name"/>
    <add key="password" value="your pass word"/>
  </appSettings>
</configuration> 

Notice

Our point is not building the WCF application, but how to configure the communication and build the Validator. I hope this page will be useful for you to build a WCF application with authentication.

License

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


Written By
Software Developer (Senior)
China China
I am a new bird of .Net programming. I want to discuss with other engineer, so please teach me.

Comments and Discussions

 
QuestionWEbapi creating endpoint with credentials in C# Pin
Kavitha sunitha19-Aug-19 1:26
Kavitha sunitha19-Aug-19 1:26 
QuestionCode does not authenticate Pin
FrenkyB15-Jun-17 20:51
FrenkyB15-Jun-17 20:51 
AnswerRe: Code does not authenticate Pin
FrenkyB15-Jun-17 21:57
FrenkyB15-Jun-17 21:57 
QuestionIt Works Pin
Roshan_khoirom25-Oct-16 8:14
Roshan_khoirom25-Oct-16 8:14 
Questionmake request from fiddler, Pin
moemotto23-Sep-16 13:59
moemotto23-Sep-16 13:59 
Question[My vote of 2] Please post the source Pin
Zipadie Doodah24-Apr-16 13:56
Zipadie Doodah24-Apr-16 13:56 
QuestionNot working for me Pin
Álvaro De Los Reyes14-Aug-15 0:14
Álvaro De Los Reyes14-Aug-15 0:14 
QuestionNot working for me Pin
Member 1055216326-Jan-14 23:54
Member 1055216326-Jan-14 23:54 
AnswerRe: Not working for me Pin
yafeya27-Jan-14 13:29
yafeya27-Jan-14 13:29 
GeneralRe: Not working for me Pin
Member 1055216327-Jan-14 17:12
Member 1055216327-Jan-14 17:12 
GeneralRe: Not working for me Pin
mehmetolgungun1-Apr-14 1:12
mehmetolgungun1-Apr-14 1:12 
GeneralRe: Not working for me Pin
moemotto23-Sep-16 14:01
moemotto23-Sep-16 14:01 
GeneralRe: Not working for me Pin
Member 450116013-Nov-17 21:42
Member 450116013-Nov-17 21:42 
Question[My vote of 1] Source code sample Pin
kiquenet.com28-Oct-13 20:37
professionalkiquenet.com28-Oct-13 20:37 
General[My vote of 1] Poor Pin
Gehan Fernando28-Oct-13 0:11
Gehan Fernando28-Oct-13 0:11 
GeneralThanks for the article! Pin
Kamran Mackey24-Oct-13 9:01
professionalKamran Mackey24-Oct-13 9:01 
GeneralRe: Thanks for the article! Pin
yafeya24-Oct-13 19:20
yafeya24-Oct-13 19:20 
GeneralRe: Thanks for the article! Pin
Kamran Mackey25-Oct-13 14:06
professionalKamran Mackey25-Oct-13 14:06 

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.