WSE 3.0 UsernameToken Application

Source: Internet
Author: User
Through the steps in this article, you can learn in detail how to use the UsernameToken of WSE 3.0 in Web Service. Through this example, you can also get a general idea of how WSE 3.0 works.
1. Define the security Policy in the configuration, and then use the security Policy in the Web Service is very simple and convenient. After the product is released, you can modify the security policy configuration file to meet different security application requirements without modifying the code.
The following example defines a security policy named "ServerPolicy" on the Web Service end.
Service class MyService add Attribute
[Policy ("ServerPolicy")] applies this security Policy. The name defined on the client is ClientPolicy.
ServiceProxy. SetPolicy ("ClientPolicy"); this statement applies this security policy on the client. In the development process, WSE
3.0 of applications are that simple.
2. WSE 3.0 is integrated with the. Net Framework Web Service.
Use the Proxy with the Wse suffix on the client. Client sends Web
When the Service calls a request, WSE inserts some filters to process the SOAP message to be sent, such as signature and encryption. Server Web
After the Service calls the request, WSE also inserts some filters to decrypt the message and verify the signature. These are all automatically completed by WSE.
Service Development does not have any impact, bring additional code work, and enjoy the security brought by WSE.
3. other features, such as convenient addition of custom security assertions, support for large data volumes of MTOM, and transmission of SOAP messages using TCP, so that Web services can be separated from Http Server; the routing of SOAP messages.

Test environment:
One Server machine A is used for Host Web Service, and one Client machine B is used for Client call. Both machines are in the Windows Domain environment (Intranet). Proxy and domain identity authentication are required to access the Internet. The security policies in the domain are strict.
To use WSE 3.0, both machine A and machine B must have. Net Framework 2.0 and SDK installed. On Machine A, add the \ v2.0 \ Bin Path of the Framework 2.0 SDK installation directory to the Path environment variable of Windows.
WSE 3.0. Download and install WSE 3.0. Tools and Samples must be installed on machine A. If you are A development environment, you 'd better choose to integrate with Visual Studio 2005 (machine A is my development environment, the development in the following example is completed on machine A. In this way, it is easier to configure WSE 3.0 during the development process. You can install WSE 3.0 Runtime on machine B.

1. CA certificate Installation
In WSE 3.0, UsernameToken must be used with an X.509 Certificate Server. The following steps create the server Certificate on machine.
The following batch processing script creates A test certificate MyServiceCert on machine A and makes some configuration. Save the script to A. bat file, copy the file to the C: \ Program Files \ Microsoft WSE \ v3.0 \ Samples Directory, and run it. After running the command, make sure that the makecert.exe statement is successfully executed. If the hard disk partition is FAT32, it does not matter if the winhttpcertcfg fails to be executed. If it is NTFS, make sure that the operation is successful.
Winhttpcertcfg is ensured. net Running Account has the permission to access the private key file of the certificate to read the private key information, you can also use C: \ Program Files \ Microsoft WSE \ v3.0 \ Tools \ WseCertificate3.exe for configuration. Run wsecertificate3.exe, select Local Machine for Certificate Location, set Store Name to Personal, click Open Certificate, select MyServiceCert, and confirm the Certificate. At this time, wsecertificate3.exe will load information about the MyServiceCert certificate, click the View Private Key File Properties button, the pop-up is actually the Private Key File Properties dialog box, if it is a disk in NTFS format, in the file Properties dialog box, there will be a Security Attribute page to ensure that the ASPNET account or Network Service account (or you are in ASP. NET machine. the account configured in config or Application Pool) has the permission to access this file.
Set CERTNAME = MyServiceCert
Certmgr-del-r LocalMachine-s My-c-n % CERTNAME %
Makecert.exe-sr LocalMachine-ss My-a sha1-n CN = % CERTNAME %-sky exchange-pe
Set WP_ACCOUNT = NETWORK SERVICE
(Ver | findstr "5.1") & set WP_ACCOUNT = % COMPUTERNAME % \ ASPNET
Winhttpcertcfg-g-c LOCAL_MACHINE \ My-s % CERTNAME %-a "% WP_ACCOUNT %"
Iisreset
Pause

The next step is to export the server certificate of machine A and install it on client machine B.
On Machine A, run the command line mmc to open the console and add A Certificate (the English version should be Certificate) to the management unit. When adding A management unit, select the Computer account option (the English version should be Local Computer ). In Personal> Certificate (Personal-> Certificate), right-click MyServiceCert and choose "all tasks"> "Export". During the export process, select "do not export private keys, you can select the export format DER and Base64 to export the certificate to mss. cer file.
Put mss. copy the cer file to machine B and add the Certificate Management Unit to the mmc console of machine B. Note that when adding the management unit this time, select Current User ). Right-click Personal and choose import from the shortcut menu. Select the mss. cer file.

2. Write UsernameTokenManager
UsernameTokenManager is used to help the server verify the user name and password submitted by the client.
The client creates a UsernameToken object with username, password, and other information. WSE sends the relevant information to the Web Service through the Soap Header. After the Web Service receives the request, WSE can obtain information about UsernameToken from the Soap Header and construct this object. The UsernameTokenManager written in this step is to obtain the user password on the Web Service end based on the user name and return the password to WSE 3.0, WSE 3.0 verifies that the password is consistent with the password submitted by the client to complete client authentication.
Create a project UsernameTokenManager for the Class Library and add the project UsernameTokenManager to Microsoft. web. reference of Services3.dll (because the dll has been registered to the global assembly when WSE 3.0 is installed. and add a class MyUsernameTokenManager. The class code is as follows. Using System;
Using System. Xml;
Using System. Security. Permissions;

Using Microsoft. Web. Services3.Security;
Using Microsoft. Web. Services3.Security. Tokens;

Namespace WSETest
{
Public class MyUsernameTokenManager: UsernameTokenManager
{
Public MyUsernameTokenManager ()
{
}

Public MyUsernameTokenManager (XmlNodeList nodes)
: Base (nodes)
{
}

/// <Summary>
/// Returns the password or password equivalent for the username provided.
/// </Summary>
/// <Param name = "token"> The username token </param>
/// <Returns> The password (or password equivalent) for the username </returns>
Protected override string AuthenticateToken (UsernameToken token)
{
// In this example, the Server and Client only use a simple convention to verify the password: Password = User Name
// In the actual project, the common practice is to query the user's password from the database. This function returns
// WSE 3.0 use the password returned by this function to verify the password submitted by the Client
Byte [] password = System. Text. Encoding. UTF8.GetBytes (token. Username );
Array. Reverse (password );
Return Convert. ToBase64String (password );
}
}
}

Compile and generate UsernameTokenManager. dll.

3. Test Web Service development and WSE 3.0 Configuration
A) Write a Web Service. Use VS2005 New Web Site: WSEServer to add a Web Service entry: MyService. We directly use the HelloWorld () method generated by VS for testing. Add a reference for UsernameTokenManager. dll to the Web project.

B) enable WSE 3.0. Right-click WSEServer in the Web Project and choose WSE Settings 3. 0 ..., in the displayed dialog box, select Enable this project for Web Services Enhancements and Enable Microsoft Web Services Enhancement Soap Protocol Factory. This step enables WSE 3.0 on the WSEServer project, and adds Microsoft. Web. Services3.dll to the reference of the project.
C) Configure UsernameTokenManager. Right-click the WSE Server project and choose WSE Settings 3. 0 ..., add a Security Tokens Manager on the Security properties page. First Select User Name Token Manager In Built In Token Manager, and then replace Type with WSETest. myUsernameTokenManager and UsernameTokenManager.
Add using WSETest; to the MyService. cs code ;.
D) Create a server security policy. Right-click the WSE Server project and choose WSE Settings 3. 0 ..., on the Policy property page, select Enable Policy, add a Policy named ServerPolicy, and click "OK" to enter WSE Security Settings Wizard. Select Secure a service application and Client Authentication Method select Username. In the following dialog box, do not select Perform Authorization. The subsequent screen is as follows:


E) Apply server-side security policies. Add using Microsoft. Web. Services3; to the MyService. cs code ;.
Add an Attribute for the Web Service class to apply the security policy defined above.

F) configure the Web Service virtual directory. In IIS, create and configure A virtual directory where WSEServer points to the Web Service directory to ensure that http: // machine a ip/WSEServer/MyService can be accessed on machine B. asmx Web Service. Possible settings: virtual directory settings, firewall settings, and Guest account enabling.

4. Client development and WSE 3.0 Configuration
A) create a client project. Create a Console Application WSEClient as the client. Right-click the project and choose WSE Settings 3. 0...
Select Enable this project for Web Services Enhancements and click OK. Add the following namespace reference. Using Microsoft. Web. Services3;
Using Microsoft. Web. Services3.Design;
Using Microsoft. Web. Services3.Security;
Using Microsoft. Web. Services3.Security. X509;
Using Microsoft. Web. Services3.Security. Tokens;

B) add a Web Service reference. The reference address is http: // machine a ip/WSEServer/MyService. asmx. You must never use localhost. Otherwise, it cannot be accessed on machine B. The Web Reference Name is named MyServiceRef.
C) Main Function Code. Static void Main (string [] args)
{
Try
{
MyServiceRef. MyServiceWse serviceProxy = new WSEClient. MyServiceRef. MyServiceWse ();
ServiceProxy. SoapVersion = SoapProtocolVersion. Default;

// User name token
String userName = Environment. UserName;
Byte [] midPassword = System. Text. Encoding. UTF8.GetBytes (userName );
Array. Reverse (midPassword );
String password = Convert. ToBase64String (midPassword );
UsernameToken token = new UsernameToken (userName, password );
ServiceProxy. SetClientCredential (token );

// Apply policy
ServiceProxy. SetPolicy ("ClientPolicy ");

// Use the domain proxy for credential
ServiceProxy. Proxy = new System. Net. WebProxy ("proxy server", true );
ServiceProxy. Proxy. Credentials = new System. Net. NetworkCredential ("domain account", "password", "domain name ");

// Call web service
Console. WriteLine ("Calling {0}", serviceProxy. Url );
String result = serviceProxy. HelloWorld ();
Console. WriteLine ("Result: {0}", result );
}
Catch (Exception e)
{
Console. WriteLine (e. Message );
}

Console. WriteLine ("");
Console. WriteLine ("");
Console. ReadLine ();
}


ServiceProxy. the Proxy object settings are as follows: request failed due to HTTP status 407, The ISA Server requires authorization to fulfill the request. access to the Web Proxy service is denied.
If both the Web Service and Client are local, or the proxy is not required in the LAN, the two lines of code are not required.
D) create a security policy. A ClientPolicy is used in the preceding step, but it has not yet been defined. The next step is to define this security policy.
First, run the following command on the command line of machine A (Development Environment): certmgr.exe-add-r LocalMachine-s My-c-n MyServiceCert-r CurrentUser-s AddressBook, this command copies the certificate created on Machine A in step 1 from the Personal of the Local Machine to the Others of the Current User, this is to select this certificate when defining the Client Security Policy below.
Right-click the project and choose WSE Settings 3. 0...
On the Policy property page, select Enable Policy and add a Policy named ClientPolicy. After confirming, enter WSE Security.
Settings Wizard. Select Secure a client application and Client Authentication
Select Username for Method. Check Specify Username Token in code. Next, the Message Protection is selected exactly the same as that of the Web Service. Then Select the Certificate and click Select Certificate to view the Certificate of MyServiceCert, in this step, the list of Certificates displayed in Current User-> Others-> Certificates of the Certificate Management Unit is listed. The certificate Copy command above allows you to select the certificate here.
E) Local test. Up to now, when running the Client on development machine A, you should be able to see the result of successfully calling the Hello World of Web Service in the Console window.

5. Deploy the Client to machine B for testing.
Copy the following files to the test directory of machine B: wseclient.exe?wseclient.exe. config, wse3policyCache. config, open wse3policyCache with Notepad on machine B. in the config file, set the following node: <x509 storeLocation = "CurrentUser" storeName = "AddressBook "... /> modify it to <x509 storeLocation = "CurrentUser" storeName = "My "... />, save.
After logging on to machine B, run wseclient.exe. The running result is as follows.

First, the deployment on client machine B should include the import of the server certificate. I put this in step 1.
Second, the WSE 3.0 Configuration tool integrated in VS2005, When you select an X.509 Certificate for the client, only the Others (Others) from the Local Machine or Current User) select the certificate in the Store Name, but I can see that the Store Name of this Others cannot be seen by default on some machines, and there is no place in the console to add it in, you can only execute some command line operations to make it appear. In the preceding example, when developing and configuring A Client on machine A, run the command to copy the certificate to Others of the Current User, this allows you to select a certificate during the configuration process. When the test client is deployed on machine B, the certificate is imported to the Personal (Personal) of the Current User of machine B, and the configuration file is modified to allow the WSE to read the certificate information from the Personal.

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.