WCF Articles about Web SERVICE&WCF&WEBAPI implementation Authentication (1)

Source: Internet
Author: User
Tags connectionstrings

WCF authentication is generally common in the following ways: custom user name and password authentication, X509 certificate validation, ASP. NET Membership (membership) validation, SOAP header validation, Windows Integrated authentication, WCF Authentication Service (AuthenticationService), which are actually available on the Web with relevant introductory articles, I am a summary here, by the way some attention to the details of the description, so that everyone can better grasp the knowledge.

First: Custom username and password verification (with X509 certificate required)

Since this verification requires the use of X509 certificate, we need to create a certificate, you can use the MS comes with the Makecert.exe program to create a test certificate, using the steps: Open the start->microsoft Visual Studio (vs Menu , different versions, names differ)->visual Studio tools->visual Studio Command prompt, and then execute the following command:

Makecert-r-pe-n "cn=zwjcert"-ss trustedpeople-sr Localmachine-sky Exchange

The above command, in addition to my bold part can be changed to your actual request (for the certificate name), the rest can remain unchanged, the command means: Create a certificate named Zwjcert will be added to the local computer's trusted people zone.

If you need to view the certificate, you can query the certificate from the MMC console by following these steps:

Running->MMC, opening windows for the first time without giving us a direct access to the management certificate, you need to add it yourself, adding the method as follows:

1. In the console menu, file → add/remove Snap-in → add button → select "certificate" → add → select "my user account" → Close → OK
2. In the console menu, file → add/remove Snap-in → add button → select "certificate" → add → select "computer account" → Close → OK

In this way, the left side of the MMC has a menu, then expand: Certificate (local computer), trusted people, and finally you can see your certificate in the list of certificates on the right, as shown in:

The certificate is created, we can start coding, this article is mainly about WCF, so we first define a WCF service contract and service implementation class (the following various validations adopt the WCF service), I directly use the default code, as follows:

namespace wcfauthentications{[ServiceContract] public interface IService1 {[OperationContract] St        Ring GetData (int value);        [OperationContract]    Compositetype getdatausingdatacontract (Compositetype composite);        } [DataContract] public class Compositetype {bool Boolvalue = true;        String stringvalue = "Hello";            [DataMember] public bool Boolvalue {get {return boolvalue;}        set {boolvalue = value;}            } [DataMember] public string StringValue {get {return stringvalue;}        set {stringvalue = value;}        }}}namespace wcfauthentications{public class Service1:iservice1 {public string GetData (int value) {return string.        Format ("you entered: {0}", value);             Public Compositetype getdatausingdatacontract (Compositetype composite) {if (composite = = null)        {        throw new ArgumentNullException ("composite"); } if (composite. Boolvalue) {composite.            StringValue + = "Suffix";        } return composite; }    }}

To implement user name and password authentication, you need to define a username and password validator class Customusernamevalidator that inherits from Usernamepasswordvalidator, as follows:

namespace wcfauthentications{public    class Customusernamevalidator:usernamepasswordvalidator    {        public override void Validate (string userName, string password)        {            if (null = = UserName | | null = = password)            {                thr ow new ArgumentNullException ();            }            if (userName! = "Admin" && password! = "Wcf.admin")//the user name and password can be determined in accordance with the actual situation            {                throw new System.IdentityModel.Tokens.SecurityTokenException ("Unknown Username or Password");}}}    

The code is very simple, just rewrite its validate method, here is the WCF host that will be created, I use the console program here

Code section:

Namespace wcfhost{    class program    {        static void Main (string[] args)        {            using (var host = new ServiceHost (typeof (Service1)))            {                host. Opened + = Delegate                {                    Console.WriteLine ("Service1 host is turned on! ");                };                Host. Open ();                Console.readkey ();}}}    

APP. Config section (this is the focus, you can use the WCF Configuration tool for visual operation configuration, see: http://www.cnblogs.com/Moosdau/archive/2011/04/17/2019002.html):

  <system.serviceModel> <bindings> <wsHttpBinding> <binding name= "service1binding" > <security mode= "Message" > <message clientcredentialtype= "UserName"/> </secur ity> </binding> </wsHttpBinding> </bindings> <services> <service Beha viorconfiguration= "Service1behavior" name= "Wcfauthentications.service1" > <endpoint address= "binding=" WsHtt Pbinding "bindingconfiguration=" service1binding "contract=" Wcfauthentications.iservice1 "> <identit y> <dns value= "Zwjcert"/> </identity> </endpoint> <endpoint add            Ress= "Mex" binding= "mexHttpBinding" contract= "IMetadataExchange"/> 

Here are a few points to note:

1.<dns value= "Zwjcert"/> with <servicecertificate findvalue= "Zwjcert". The value in > must be the name of the certificate, that is: Zwjcert;

The security node needs to be configured in the 2.Binding node, and the clientCredentialType in the message child node must be set to: UserName;

In a 3.serviceBehavior node, you need to configure the ServiceCredentials child node, where each attribute in the Servicecertificate needs to match the certificate. Usernameauthentication's usernamepasswordvalidationmode must be custom, Customusernamepasswordvalidatortype the type of user name and password validator class for the above custom and its assembly

The end is to use the client, first referencing the service, then look at the App. Config, and make the appropriate changes, as follows:

    <system.serviceModel> <bindings> <wsHttpBinding> <binding name= " Wshttpbinding_iservice1 "> <security mode=" Message "> <transport clie Ntcredentialtype= "Windows" proxycredentialtype= "None" realm= ""/> &lt ; Message clientcredentialtype= "UserName" negotiateservicecredential= "true" algorithmsuite= "Defa Ult "/> </security> </binding> </wsHttpBinding> & lt;/bindings> <client> <endpoint address= "http://localhost:8732/WcfAuthentications/Service1/ "Binding=" Wshttpbinding "bindingconfiguration=" Wshttpbinding_iservice1 "contract=" Servicere Ference1. IService1 "name=" Wshttpbinding_iservice1 "> <identity> <dns value=" Zwjcert "/           >     </identity> </endpoint> </client> </system.serviceModel> 

In order to highlight the key, I am here to simplify the binding node, remove a lot of property configuration, only the important parts, such as: Security node, modify its endpoint under the identity of <dns value= "Zwjcert"/> Here the value of the same node as said in the service, that is, the certificate name, if not the same, then will be error, the specific error message you can try, I am limited to the length of the content is not posted out.

The client uses the service code as follows:

Namespace wcfclient{class Program {static void Main (string[] args) {using (var proxy = n EW servicereference1.service1client ()) {Proxy.                ClientCredentials.UserName.UserName = "admin"; Proxy.                ClientCredentials.UserName.Password = "Wcf.admin"; string result = Proxy.                GetData (1);                Console.WriteLine (result); var compositeobj = proxy.                Getdatausingdatacontract (New Compositetype () {Boolvalue = true, stringvalue = "Test"});            Console.WriteLine (Serializertojson (Compositeobj));        } console.readkey (); }///<summary>///serialization into JSON string///</summary> static string serializertojson<t            > (t obj) where T:class {var serializer = new DataContractJsonSerializer (typeof (T));            var stream = new MemoryStream (); Serializer.            WriteObject (Stream,obj); byte[] Databytes =New Byte[stream.            Length]; Stream.            Position = 0; Stream. Read (databytes, 0, (int) stream.            Length);            String datastring = Encoding.UTF8.GetString (databytes);        return datastring; }    }}

The results of the operation are as follows:

  

If you do not pass in your username and password or pass in an incorrect username and password, you will get an error:

The second type: X509 certificate validation


First create a certificate, I use a certificate created above: Zwjcert; Because the certificate is required by both the server side and the client, you need to export the certificate and import the certificate on the client computer so that WCF can authenticate.

The WCF service contract and the service implementation class are the same as the first method and no longer re-pasting the code.

The WCF server is configured as follows:

  <system.serviceModel> <bindings> <wsHttpBinding> <binding name= "service1binding" > <security mode= "Message" > <message clientcredentialtype= "Certificate"/> </se curity> </binding> </wsHttpBinding> </bindings> <services> <service b ehaviorconfiguration= "Service1behavior" name= "Wcfauthentications.service1" > <endpoint address= "" binding= "ws Httpbinding "bindingconfiguration=" service1binding "contract=" Wcfauthentications.iservice1 "> </endpo          int> <endpoint address= "Mex" binding= "mexHttpBinding" contract= "IMetadataExchange"/> 

Here are a few points to note:

1.<message clientcredentialtype= "Certificate"/>clientcredentialtype set as: Certificate;

2. The ServiceCredentials node needs to be configured, where each attribute in the Servicecertificate needs to match the certificate. ClientCertificate inside I will authentication.certificatevalidationmode= "None", do not set the default value can actually also;

The Client reference service automatically generates the following configuration information:

    <system.serviceModel> <bindings> <wsHttpBinding> <binding name= " Wshttpbinding_iservice1 "> <security mode=" Message "> <transport clien Tcredentialtype= "Windows" proxycredentialtype= "None" realm= ""/> < Message clientcredentialtype= "Certificate" negotiateservicecredential= "true" algorithmsuite= "De        Fault "/> </security> </binding> </wsHttpBinding> </bindings> <client> <endpoint address= "Http://127.0.0.1:8732/WcfAuthentications/Service 1/"binding=" Wshttpbinding "bindingconfiguration=" Wshttpbinding_iservice1 "contract=" Service Reference1.iservice1 "Name=" Wshttpbinding_iservice1 "behaviorconfiguration=" Service1nehavior "> <ident                 Ity>   <certificate encodedvalue= "awaaaaeaaaauaaaakk2avjncitzuls2+ Xj66za2hbzygaaaaaqaaaowbaaawgghomiibvaadagecahaiaozfvlxluuhhjrwhuuh9makgbssoawidbqawejeqma4ga1ueaxmhwndqq2vyddaefw0xnteym Duwmjuymtrafw0zoteymzeymzu5ntlambixedaobgnvbamtb1p3aknlcnqwgz8wdqyjkozihvcnaqebbqadgy0amigjaogbalfgfsiypivku3gpjl790l13 +czwt6doepzhmcjml+ xpqkir2fdvscq9zxzapdgig4t3mgcvkuv55dbiuhcpxdvxt28m49ajdkwp924bogkpm56ewekdczyflxy5sxazfa9qjuhnpq3kgu1lfwjxbsp1rki1uhkjg5b 2j0v7aoc3agmbaagjrzbfmemga1udaqq8mdqaeh/ mexv8fhnltxvllq5smbihfdasmrawdgydvqqdewdad2pdzxj0ghaiaozfvlxluuhhjrwhuuh9makgbssoawidbqadgyeadbtbntk/ aj3woh2ts6fiu3nh7fb2tkq9l3k6qvl+kcr9mhuqwtyfjtbkxzesn2t0if6muiktco+ c8inwypjppzlaomfmrtqhko82gcdr9brqzmwptrak1is+ggh8qbiotlx9zfv/icixxrub+sq9dmrsqjkdelehwoe5i6fkqjg= "/> &L t;/identity> </endpoint> </client> <behaviors> <endpointbehaviors&gt          ; <behavior name= "Service1nehavior" > <clientCredentials> &LT;clientcertificate findvalue= "Zwjcert" x509findtype= "Findbysubjectname" storelocation= "LocalMachine" StoreName= "      Trustedpeople "/> </clientCredentials> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel>

As you can see, the encodedvalue of identity.certificate under the endpoint node contains encrypted data, and you need to add ClientCertificate configuration information manually, which indicates where the certificate resides in the local computer, and of course it can be specified dynamically by code. such as: Proxy. ClientCredentials.ClientCertificate.SetCertificate ("Zwjcert", Storelocation.localmachine, storename.my);

The client uses the service code as follows:

        static void Main (string[] args)        {            using (var proxy = new Servicereference1.service1client ())            {                //proxy . ClientCredentials.ClientCertificate.SetCertificate ("Zwjcert", Storelocation.localmachine, storename.my); Directly dynamically specifies the certificate store location                string result = Proxy. GetData (1);                Console.WriteLine (result);                var compositeobj = proxy. Getdatausingdatacontract (New Compositetype () {Boolvalue = true, stringvalue = "Test"});                Console.WriteLine (Serializertojson (Compositeobj));            }            Console.readkey ();        }

On the internet there is another alternative for X509 certificate verification, mainly using a custom certificate validator class, interested in this article: http://www.cnblogs.com/ejiyuan/archive/2010/05/31/1748363.html

Third type: ASP. NET membership (membership) validation

Because the validation requires the use of the X509 certificate, you still need to create a certificate (the method is the same as in the first method of creating the certificate): Zwjcert;

Since this verification method is based on the membership of the ASP, you need to create the corresponding database and create the account, create the database, by running the Aspnet_regsql.exe Wizard to create the database and its related tables, by opening the ASP. Web site management tool (is a self-administered web site), and create roles and users on the above for subsequent validation;

In particular, if you use a GUI button on Vs2013,vs to launch the Admin tool site, you need to dynamically compile the site by using the following command:

CD C:\Program Files\IIS expressiisexpress.exe/path:c:\windows\microsoft.net\framework\v4.0.30319\asp. Netwebadminfiles/vpath:/webadmin/port:12345/clr:4.0/ntlm

If an error occurs at compile time: "System.Configuration.StringUtil" is not accessible because it is protected by the level of protection, please change the code in WebAdminPage.cs as follows:

Cancel part: String appId = Stringutil.getnonrandomizedhashcode (String.Concat (AppPath, Appphyspath)). ToString ("x", CultureInfo.InvariantCulture);//New additions: Assembly sysConfig = Assembly.loadfile (@ "C:\Windows\ Microsoft.net\framework\v4.0.30319\system.configuration.dll "); Type Sysconfigtype = Sysconfig.gettype ("System.Configuration.StringUtil"); string appId = ((int) Sysconfigtype.getmethod ("Getnonrandomizedhashcode"). Invoke (NULL, new object[] {String.Concat (AppPath, Appphyspath), true})). ToString ("x", CultureInfo.InvariantCulture);

This allows you to follow the command-generated URL to access it. If, like me, the operating system is: WINDOWS 10, then I am sorry, the generated Web site can open, but will still error:

Encountered an error. Please go back to the previous page and try again.

There is no solution, online has said that the ASP. NET site management tools under the WIN10 is not supported, in the end why no solution, if you have to know also please share (Csdn have someone else's ask stickers: http://bbs.csdn.net/topics/ 391819719), thank you very much, I have to change the computer to run the ASP.

The WCF service-side configuration is as follows:

  <connectionStrings> <add name= "sqlconn" connectionstring= "server=.;D Atabase=aspnetdb; Uid=sa; pwd=www.zuowenjun.cn; " /> </connectionStrings> <system.web> <compilation debug= "true" targetframework= "4.5"/> 

Here are a few things to note:

1. Configure the ConnectionString to connect to the database required by the membership;

2. Configure membership, add SqlMembershipProvider property configuration;

3. Configure the servicecredential, the same as the first, the difference is the configuration of usernameauthentication: Usernamepasswordvalidationmode= " MembershipProvider ", membershipprovidername=" SqlMembershipProvider ";

4. Configure the binding node <message clientcredentialtype= "UserName"/> this is the same as the first;

The client references the WCF service to view the generated configuration file contents, ensuring that the binding node has the following configuration information:

<security mode= "Message" >        <message clientcredentialtype= "UserName"/> </security>

Finally, using the WCF service, the same code as the first one, the only thing to note is that the incoming username and password are user information created in the ASP. NET Web Site Administration tool.

In addition, we can use Membership+form authentication, using the ASP. NET authentication mechanism, to implement this mode, it is necessary to use the Svc file, and hosted on IIS, the specific implementation method, see: http://www.cnblogs.com/ Danielwise/archive/2011/01/30/1947912.html

Due to the many verification methods of WCF, this article can not write all at once, please look forward to the sequel!

WCF articles about Web SERVICE&WCF&WEBAPI implementation Authentication (1)

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.