WCF development-use the Certificate file to configure the message security mode for custom X509 Certificate Authentication

Source: Internet
Author: User
Tags baseuri pfx file

In Internet-based WCF services, security is a very important part. There are many security modes in WCF. This time, we will consider using a limited server environment (such as a virtual host) to configure the message security mode for X509 Certificate authentication. Generally, in this extreme environment, it is difficult to implement SSL-based transmission security. Therefore, we consider deploying message security and X509 certificates are used for mutual authentication between servers and clients.

First, create two certificates, Microsoft Visual Studio 2008 --> Visual Studio Tools --> Visual Studio 2008 command prompt line, enter the console, and then create the server certificate and client certificate respectively, as shown below:

 
Makecert-r-pe-n "cn = testserver"-e 08/10/2020-sky exchange-SS mymakecert-r-pe-n "cn = testclient"-e 08/10/2020-sky exchange-SS my

After execution:

Then go to the Certificate Management page to export the two certificates respectively. During the export process, each certificate is exported twice as a pfx file containing the private key and a CER file without the private key, in this way, we get four certificate files named testserver. pfx, testserver. CER, testclient. pfx, testclient. cer.

This part is shown in the following figure:

Create a WCF ServerProgram,

Because user-defined certificate authentication is used, we need to provide the server-side and client-side authentication procedures. The server-side authentication procedures are as follows:

 
Public class authorization: x509certificatevalidator {public override void validate (x509certificate2 Certificate) {string Path = hostingenvironment. mappath (webconfig. clientcertificate); If (! File. exists (PATH) {Throw new filenotfoundexception (path. getfilename (PATH);} x509certificate2 clientcertificate = new x509certificate2 (PATH); // This is the client certificate thumbprint, in production, we can validate the certificate with Ca if (! Certificate. thumbprint. Equals (clientcertificate. thumbprint, stringcomparison. currentcultureignorecase) {Throw new securitytokenexception ("unknown Certificate ");}}}

The client authentication procedure is as follows:

Public class authorization: x509certificatevalidator {public override void validate (x509certificate2 Certificate) {// throw new notimplementedexception (); If (certificate = NULL) {Throw new argumentnullexception ("certificate");} string Path = path. getfullpath (webconfig. servicecertificate); If (! File. exists (PATH) {Throw new filenotfoundexception (path. getfilename (PATH);} x509certificate2 clientcertificate = new x509certificate2 (PATH); // This is the client certificate thumbprint, in production, we can validate the certificate with Ca if (! Certificate. thumbprint. Equals (clientcertificate. thumbprint, stringcomparison. currentcultureignorecase) {Throw new securitytokenexception ("unknown Certificate ");}}}

Both programs verify the fingerprint of the certificate.

Next, configure the server. First, create a new binding Configuration:

 
<Bindings> <wshttpbinding> <binding name = "testhttpbinding"> <security mode = "message"> <transport clientcredentialtype = "NONE"/> <message clientcredentialtype = "certificate"/> </Security> </binding> </wshttpbinding> </bindings>

Then modify the behavior Configuration:

<Servicebehaviors> <behavior name = "securitywcf. service. testservicebehavior "> <servicemetadata httpgetenabled =" true "/> <servicedebug certificate =" false "/> <servicecredentials> <clientcertificate> <authentication certificate =" Custom "Certificate =" securitywcf. core. servicex509certificatevalidator, securitywcf. core "/> </clientcertificate> </servicecredentials> </behavior> </servicebehaviors>

Finally, the binding configuration will be added to the current test service.

 
<Endpoint address = "" binding = "wshttpbinding" Contract = "securitywcf. Service. itestservice" bindingconfiguration = "testhttpbinding">

According to the normal situation, the program needs to configure the server certificate. However, because the file configuration is used in this article, the degree of dynamic processing must be used. Therefore, we have created our own servicehost. The program is as follows:

Public class wcfservicehostfactory: servicehostfactory {public override servicehostbase createservicehost (string constructorstring, Uri [] baseaddresses) {servicehostbase host; Uri baseuri; If (! String. isnullorempty (webconfig. serviceuri) & Uri. trycreate (webconfig. serviceuri, urikind. relativeorabsolute, out baseuri) {Host = base. createservicehost (constructorstring, new URI [] {baseuri});} else {Host = base. createservicehost (constructorstring, baseaddresses);} If (webconfig. enableservicecertificate) {string Path = system. web. hosting. hostingenvironment. mappath (webconfig. servicecertifi Cate); If (! File. exists (PATH) {Throw new filenotfoundexception (webconfig. servicecertificate);} host. credentials. servicecertificate. certificate = new x509certificate2 (path, webconfig. servicecertificatepassword, x509keystorageflags. machinekeyset) ;}return host ;}}

This part will automatically add certificate support to the service according to the configuration file. To use this part, you need to modify the SVC file of the service and configure this servicehost in the header, as shown below:

 
<% @ Servicehost Language = "C #" DEBUG = "true" service = "securitywcf. service. testservice "factory =" securitywcf. core. wcfservicehostfactory, securitywcf. core "codebehind =" testservice. SVC. CS "%>

Configure the certificate path in Web. config. on the server side, use testserver. pfx and testclient. Cer. The configuration files are as follows:

 
<Deleetask> <add key = "servicecertificate" value = "~ /Config/testserver. pfx "/> <add key =" servicecertificatepassword "value =" 123456 "/> <add key =" enableservicecertificate "value =" true "/> <add key =" clientcertificate "Value = "~ /Config/testclient. Cer "/> </appsettings>

Run the service. If no error message is displayed, the server has been successfully run,

Next, create a client program. Follow the prompts on the page to execute svcutil.exe http: // localhost: 2674/testservice. SVC? WSDL

In this way, we can get the client source code, add it to the client program, and copy the data in the output. config generated at the same time to the app. config in the project. To use security measures, the file center must be in the behavior section, which is as follows:

 
<Behaviors> <endpointbehaviors> <behavior name = "testclientbehavior"> <clientcredentials> <servicecertificate> <authentication certificatevalidationmode = "Custom" Principal = "securitywcf. core. clientx509certificatevalidator, securitywcf. core "/> </servicecertificate> </clientcredentials> </behavior> </endpointbehaviors> </behaviors>

Then configure the behavior on the client. The client can use the Certificate for verification. In the client program, we create a factory class and create a connection object,CodeAs follows:

Public static class serverclientfactory {public static testserviceclient createserverclient (string password) {testserviceclient client = new testserviceclient (); string Path = system. io. path. getfullpath ("config/testclient. pfx "); client. clientcredentials. clientcertificate. certificate = new x509certificate2 (path, password, x509keystorageflags. machinekeyset); Return client ;}}

In this way, we can easily use the connection object. The main program for testing is as follows:

 
Class program {static void main (string [] ARGs) {using (VAR context = serverclientfactory. createserverclient ("123456") {console. writeline (context. getsystemstring ());}}}

Run the command to obtain the test result ,:

in this way, we successfully configured the X509 message security-based WCF using the Certificate file, and finally provided the entire test project download:
click to download this file

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.