Username Authentication for WCF client identification and authentication

Source: Internet
Author: User

This article mainly aims to build a simple WCF username authentication, which can be found as your own notes as needed. If you have nothing to say, let's start with the question below.

Environment: Server 2008 r2 + vs2010 + iis7.0

Example: Enter text on the client (Asp.net) interface and click the button to call the server (WCF) Service to display a text section to the client interface.

Process: The user calls the service, and the server verifies the user's username and password (X509 Certificate is used for verification and encryption and decryption during transmission). If the verification succeeds, the service is called.

1.Generate a certificate:This will only generate a certificate for testing (generated using makecert.exe), and then use MMC
Console gives corresponding permissions (manage private keys ...).

Makecert.exe-Sr localmachine-SS my-N Cn = myservercert-sky exchange-PE

2. Server:Use vs2010 ide to create a "WCF Service Application" project solution to implement our own username authentication method. In fact, it inherits usernamepasswordvalidator (you need to add to system. identitymodel. DLL reference) and override the method validate.

/// <summary>    /// MyCustomValidator.cs    /// </summary>    public class MyCustomValidator: UserNamePasswordValidator    {        /// <summary>        /// Override Validate method to implement custom validation        /// </summary>        /// <param name="userName">Username</param>        /// <param name="password">Password</param>        public override void Validate(string userName, string password)        {            if (string.IsNullOrEmpty(userName))            {                throw new ArgumentNullException("userName");            }            if (string.IsNullOrEmpty(password))            {                throw new ArgumentNullException("password");            }            // This is for testing purpose            if (userName != "Admin" || password != "123456")            {                // Why we can't catch this fault exception in client                FaultException fault =                    new FaultException(                        new FaultReason("UserName or password is wrong!"),                        new FaultCode("Error:0x0001"));                throw fault;            }        }}

After that, it is very simple to write our services.

    [ServiceContract]    public interface IValidationService    {        [OperationContract]        string PrintMessage(string message);}    public class ValidationService : IValidationService    {        public string PrintMessage(string message)        {            Console.WriteLine("Message = " + message);            return message;        }}

Here, the server code is basically complete, and the next step is how to make the code work together, we need to modify our configuration file web. config, there are three places to modify or add.

First, add binding. Here we add wshttpbinding;

    <!-- Manually added bindings -->    <bindings>      <wsHttpBinding>        <binding name="mySecurityBinding">          <security mode="Message">            <message clientCredentialType="UserName" />          </security>        </binding>      </wsHttpBinding>    </bindings>

 Second, add the configuration for username authentication, that is, servicecredentials configuration.

          <!-- Manually added credentials -->          <serviceCredentials>            <serviceCertificate findValue="MyServerCert" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFValidationServer.CustomValidation.MyCustomValidator,WCFValidationServer" />          </serviceCredentials>

Third, configure an essential endpoint;

    <!-- Manually added service endpoint -->    <services>      <service behaviorConfiguration="WCFValidationServer.ValidationServiceBehavior" name="WCFValidationServer.ValidationService">        <endpoint address="" binding="wsHttpBinding" contract="WCFValidationServer.IValidationService"                   bindingConfiguration="mySecurityBinding">          <identity>            <dns value="MyServerCert" />          </identity>        </endpoint>        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />      </service>    </services>

At this point, the server still needs to do the last thing, that is, host to IIS. Here we will not talk much about it. You can test the host successfully.

3. Client:Similarly, use vs2010 to create an "ASP. net web application project, add reference to the WCF Service, IDE will automatically add the relevant WCF configuration work, here you need to note that, because our certificate is not a real certificate, but a test is generated, this certificate will not pass verification, therefore, when the client accesses the service, an error will be reported (if the specific error is not mentioned, we will know it after we try it). We need to add our own X509 Certificate verification method on the client, here, for the purpose of testing, the new validate method is empty, that is, no authentication judgment is made.

    public class MyX509Validator : X509CertificateValidator    {        public override void Validate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)        {                    }    }

Okay. After the code is complete, we also need to modify the Web. config configuration file of the client to make the Code take effect. Add the following behavior and set the behaviorconfiguration of the client endpoint to the one we added.

    <client>      <endpoint address="http://localhost:8000/ValidationService.svc"        binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IValidationService"        contract="WCFValidationService.IValidationService" name="WSHttpBinding_IValidationService" behaviorConfiguration="myClientBehavior">        <identity>          <dns value="MyServerCert" />        </identity>      </endpoint>    </client>    <behaviors>      <endpointBehaviors>        <behavior name="myClientBehavior">          <clientCredentials>            <serviceCertificate>              <authentication certificateValidationMode="Custom" customCertificateValidatorType="WCFValidationClient.MyX509Validator,WCFValidationClient" />            </serviceCertificate>          </clientCredentials>        </behavior>      </endpointBehaviors>    </behaviors>

Now, our entire project is complete. The client interface and service call will not be mentioned. You can view the uploaded source code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.