About WEB Service & amp; WCF & amp; WebApi identity authentication (1), WEBService

Source: Internet
Author: User
Tags visual studio 2010

About WEB Service & WCF & WebApi implementing identity authentication (1), WEBService

Generally, the following methods are used for WCF authentication:User name and password authentication, X509 Certificate authentication, ASP. NET member qualification (membership) authentication, SOAP Header authentication, Windows integrated authentication, and WCF Authentication Service (AuthenticationService)In fact, there are related articles on the internet for these verification methods. I would like to summarize them here. By the way, I would like to explain some details so that you can better master this knowledge.

First: user name and password verification (X509 Certificate required)

The verification token is used to create a certificate with the certificate x509. you can use the makecert.exe program of MS to create a test certificate. Use the following steps: Open start> Microsoft Visual Studio 2010 (VS menu, different versions, and different names) -> 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

In the above command, except for the rough parts, you can change the actual request (for the certificate name), the rest can remain unchanged.ZwjCertAdd the certificate to the trusted person area of the local computer.

To view the certificate, you can query the certificate on the MMC console. The procedure is as follows:

Run-> MMC. If you open Windows for the first time, there is no direct Certificate Management Portal for us. You need to add the certificate by yourself as follows:

1. In the console menu, choose File> Add/delete management unit> Add button> select certificate> Add> select my User Account> close> OK
2. In the console menu, choose File> Add/delete management unit> Add button> select certificate> Add> select computer account> close> OK

In this way, the menu is displayed on the left of the MMC, and then expanded in sequence: Certificate (Local Computer)-> trusted person-> certificate, finally, you can see your certificate in the certificate list on the right, as shown in:

 

After the certificate is created, we can start encoding. This article focuses on WCF, therefore, we first define a WCF Service Contract and service implementation class (the WCF Service is used for all subsequent verifications). Here we use the default code directly, as shown below:

namespace WcfAuthentications{    [ServiceContract]    public interface IService1    {        [OperationContract]        string 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 verify the user name and password, you need to define a username and password validators class CustomUserNameValidator inherited from UserNamePasswordValidator. The Code is as follows:

Namespace WcfAuthentications {public class CustomUserNameValidator: UserNamePasswordValidator {public override void Validate (string userName, string password) {if (null = userName | null = password) {throw new ArgumentNullException ();} if (userName! = "Admin" & password! = "Wcf. admin ") // the user name and password can be determined based on actual conditions {throw new System. identityModel. tokens. securityTokenException ("Unknown Username or Password ");}}}}

The code is very simple, just rewrite its Validate method. The following describes how to create a WCF host. Here I use the console Program

Code:

Namespace WcfHost {class Program {static void Main (string [] args) {using (var host = new ServiceHost (typeof (Service1) {host. opened + = delegate {Console. writeLine ("Service1 Host enabled! ") ;}; Host. Open (); Console. ReadKey ();}}}}

APP. CONFIG section (this is the focus, you can use the WCF Configuration tool for visualized 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" />          </security>        </binding>      </wsHttpBinding>    </bindings>    <services>      <service behaviorConfiguration="Service1Behavior" name="WcfAuthentications.Service1">        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="Service1Binding"          contract="WcfAuthentications.IService1">          <identity>            <dns value="ZwjCert" />          </identity>        </endpoint>        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />        

Note the following points:

1. The value in <dns value = "ZwjCert"/> and <serviceCertificate findValue = "ZwjCert"...> must be the name of the certificate, that is, ZwjCert;

2. The security node needs to be configured in the Binding node. The clientCredentialType in the message subnode must be set to UserName;

3. in the serviceBehavior node, configure the serviceCredentials subnode. The attributes in serviceCertificate must match the certificate. The userNamePasswordValidationMode of userNameAuthentication must be Custom, customUserNamePasswordValidatorType is the type and assembly of the user name and password validator class defined above

The last step is to use the service on the client. First, reference the service, then check App. Config, and modify it as follows:

    <system.serviceModel>        <bindings>            <wsHttpBinding>                <binding name="WSHttpBinding_IService1" >                    <security mode="Message">                        <transport clientCredentialType="Windows" proxyCredentialType="None"                            realm="" />                        <message clientCredentialType="UserName" negotiateServiceCredential="true"                            algorithmSuite="Default" />                    </security>                </binding>            </wsHttpBinding>        </bindings>        <client>            <endpoint address="http://localhost:8732/WcfAuthentications/Service1/"                binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"                contract="ServiceReference1.IService1" name="WSHttpBinding_IService1">                <identity>                    <dns value="ZwjCert" />                </identity>            </endpoint>        </client>    </system.serviceModel>

To highlight the key points, I have simplified the Binding node and removed many attribute configurations. Only important parts are retained, such as security nodes, modify <dns value = "ZwjCert"/> In the identity under its endpoint. The value here is the same as the node mentioned in the service, that is, the Certificate Name, then an error will be reported. You can try the specific error message on your own. I will not post the error message here.

The client uses the following service code:

Namespace WCFClient {class Program {static void Main (string [] args) {using (var proxy = new 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> /// serialize to a 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 running result is shown as follows:

  

If you do not enter the user name and password or enter an incorrect user name and password, an error is returned:

Type 2: X509 Certificate verification


First, create a certificate. Here I will use the certificate created above: ZwjCert. because both the server and client need to use this certificate, you need to export the certificate, import the certificate to the client computer so that the WCF can be verified.

The WCF Service Contract and service implementation class are the same as the first method, and no code is re-pasted.

The configuration of the WCF server is as follows:

  <system.serviceModel>    <bindings>      <wsHttpBinding>        <binding name="Service1Binding">          <security mode="Message">            <message clientCredentialType="Certificate" />          </security>        </binding>      </wsHttpBinding>    </bindings>    <services>      <service behaviorConfiguration="Service1Behavior" name="WcfAuthentications.Service1">        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="Service1Binding"          contract="WcfAuthentications.IService1">        </endpoint>        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />        

Note the following points:

1. <message clientCredentialType = "Certificate"/> set clientCredentialType to Certificate;

2. You need to configure the serviceCredentials node. The attributes in serviceCertificate must match the certificate. In clientCertificate, I Will authentication. certificateValidationMode = "None". You can also use the default value if not set;

The client references the service and automatically generates the following configuration information:

    <system.serviceModel>        <bindings>            <wsHttpBinding>                <binding name="WSHttpBinding_IService1">                    <security mode="Message">                        <transport clientCredentialType="Windows" proxyCredentialType="None"                            realm="" />                        <message clientCredentialType="Certificate" negotiateServiceCredential="true"                            algorithmSuite="Default" />                    </security>                </binding>            </wsHttpBinding>        </bindings>        <client>            <endpoint address="http://127.0.0.1:8732/WcfAuthentications/Service1/"                binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"                contract="ServiceReference1.IService1" name="WSHttpBinding_IService1" behaviorConfiguration="Service1Nehavior">                <identity>                    <certificate encodedValue="AwAAAAEAAAAUAAAAkk2avjNCItzUlS2+Xj66ZA2HBZYgAAAAAQAAAOwBAAAwggHoMIIBVaADAgECAhAIAOzFvLxLuUhHJRwHUUh9MAkGBSsOAwIdBQAwEjEQMA4GA1UEAxMHWndqQ2VydDAeFw0xNTEyMDUwMjUyMTRaFw0zOTEyMzEyMzU5NTlaMBIxEDAOBgNVBAMTB1p3akNlcnQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALfGfsiYpIVKu3gPJl790L13+CZWt6doePZHmcjMl+xPQKIR2fDvsCq9ZxzapDgiG4T3mgcVKUv55DBiuHcpXDvXt28m49AjdKwp924bOGKPM56eweKDCzYfLxy5SxaZfA9qjUhnPq3kGu1lfWjXbsp1rKI1UhKJg5b2j0V7AOC3AgMBAAGjRzBFMEMGA1UdAQQ8MDqAEH/MEXV8FHNLtxvllQ5SMbihFDASMRAwDgYDVQQDEwdad2pDZXJ0ghAIAOzFvLxLuUhHJRwHUUh9MAkGBSsOAwIdBQADgYEAdBtBNTK/Aj3woH2ts6FIU3nh7FB2tKQ9L3k6QVL+kCR9mHuqWtYFJTBKxzESN2t0If6muiktcO+C8iNwYpJpPzLAOMFMrTQhkO82gcdr9brQzMWPTraK1IS+GGH8QBIOTLx9zfV/iCIXxRub+Sq9dmRSQjKDeLeHWoE5I6FkQJg=" />                </identity>            </endpoint>        </client>      <behaviors>        <endpointBehaviors>          <behavior name="Service1Nehavior">            <clientCredentials>              <clientCertificate findValue="ZwjCert" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="TrustedPeople" />            </clientCredentials>          </behavior>        </endpointBehaviors>      </behaviors>    </system.serviceModel>

You can see the identity under the endpoint node. the encodedValue of certificate contains encrypted data. In addition, you need to manually add the clientCertificate configuration information, which indicates the location where the certificate is stored on the local computer. Of course, you can also specify it dynamically through code, for example: proxy. clientCredentials. clientCertificate. setCertificate ("ZwjCert", StoreLocation. localMachine, StoreName. my );

The client uses the following service code:

Static void Main (string [] args) {using (var proxy = new ServiceReference1.Service1Client () {// proxy. clientCredentials. clientCertificate. setCertificate ("ZwjCert", StoreLocation. localMachine, StoreName. my); // directly and dynamically specify the certificate storage 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 ();}

There is an alternative for X509 Certificate verification on the internet, mainly using a custom certificate validators class, interested can see this article: http://www.cnblogs.com/ejiyuan/archive/2010/05/31/1748363.html

Third: ASP. NET member qualification (membership) Verification

Because the X509 Certificate is required for this verification, you still need to create a certificate (the method for creating a certificate in the first method is the same): ZwjCert;

The hosts wizard creates databases and related tables. You can open the ASP. NET Website management tool (a built-in website management tool) and create roles and users for subsequent verification;

In particular, if VS2013 and VS are used without built-in GUI buttons to start the Management Tool website, you need to use the following command to dynamically compile the website:

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 during compilation: "System. Configuration. StringUtil" is not accessible because it is restricted by the protection level, modify the code in WebAdminPage. cs as follows:

// Cancel part: string appId = StringUtil. getNonRandomizedHashCode (String. concat (appPath, appPhysPath )). toString ("x", CultureInfo. invariantCulture); // added: 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 );

In this way, you can access the website generated by the command. If the operating system is WINDOWS 10 like me, sorry, even though the generated website can be opened, an error will still be reported:

An error occurred. Return to the previous page and try again.

No solution is found. ASP is available on the Internet. NET website management tools in WIN10 is not supported, in the end why there is no solution for the time being, if you know, please share it (CSDN has someone else's question: http://bbs.csdn.net/topics/391819719), thank you very much, I have to switch my computer to run ASP. NET Management Tool website.

The configuration of the WCF server is as follows:

  <connectionStrings>    <add name="SqlConn" connectionString="Server=.;Database=aspnetdb;Uid=sa;Pwd=www.zuowenjun.cn;"/>  </connectionStrings>  <system.web>    <compilation debug="true" targetFramework="4.5" />    

Note the following points:

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

2. Configure membership and add the SqlMembershipProvider attribute configuration;

3. Configure serviceCredential, which is basically the same as the first one. The difference is the configuration of userNameAuthentication: userNamePasswordValidationMode = "MembershipProvider", membershipProviderName = "SqlMembershipProvider ";

4. Configure the Binding node <message clientCredentialType = "UserName"/>, which is the same as the first one;

The client references the WCF Service to view the generated configuration file. Make sure that the Binding node has the following configuration information:

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

Finally, use the WCF Service. The Code is the same as the first one. The only thing you need to note is that the passed UserName and Password are the user information created in ASP. NET Website management tool.

In addition, we can also use membership + Form verification and ASP. NET authentication mechanism, to achieve this mode, is the need to use svc file, and host 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 cannot be fully written at one time. Please wait for the continuation of this article!

Related Article

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.