[Reprint] Use WSE to verify user identity in Web Services

Source: Internet
Author: User

Use WSE to verify user identity in Web Services
From sellon'sUse WSE to verify user identity in Web Services
1. Web Service Security and WS-Security

There is no doubt that soap and XML Web Services have completely changed the pattern of e-commerce in terms of interaction operations and standards.

However, until recently, there are still some defects in the Web Service technology field, that is, the ability to handle message-level security, authentication, encryption, digital signature, routing, attachments, and other issues. To address these security issues, companies and organizations such as IBM, Microsoft, and VeriSign are taking the lead in developing unified web service security specifications, in order to use their original web service interactive operation concepts and business models, they have introduced WS-Security and other specifications. It can be said that since the formation of the SOAP specification, the WS-Security Specification and its subsequent work may be one of the most important advances in the Web Service technology field.

With the finalization of WS-Security specifications, major software vendors began to seriously consider providing their products with interfaces and programming toolboxes using the same Web Service Security language, web Service developers will also be able to use the tools provided by these vendors to enhance the security of the web services they develop.

Ii. WSe security performance Overview

Microsoft launched Web Services enhancements 1.0. net (WSE) is a class library used to implement advanced Web service protocols. This is also the company's first tool suite to implement SOAP message security using WS-Security and other specifications.

An important part of protecting the security of web services is to protect the security of SOAP message transmission.

After WSE is used, soap messages can verify their integrity by themselves and can be encrypted using mechanisms defined in the WS-Security Specification.

All WS-Security features supported by wse1.0 are implemented through the security Input and Output filters of securityinputfilter and securityoutputfilter objects. They support the following security features:

1. Digital Signature

2. Encryption

3. Sign and encrypt with the user name token

4. Use X.509 Certificate Signature and Encryption

5. Use a custom binary token for signature and Encryption

Wse1.0 does not support Security Assertion Markup Language (SAML), but Microsoft is actively implementing the SAML architecture in its. NET Server. Of course, developers can freely implement SAML. The only drawback is that the WS-Security interface of the web service that follows the WS-Security Specification cannot be used.

The WSE architecture model is based on the filter pipeline that processes inbound and outbound soap messages. It is based on the existing soapextension class. developers who have used the soapextension class traveling compression, encryption, record and other operations will find that they are very familiar with WSE.

WSe provides a Microsoft. web. services. the soapcontext class allows us to process WS-Security SOAP Headers and other inbound SOAP Headers, and add WS-Security headers for outbound soap messages. WSe also has a packaging class to add soapcontext for SOAP requests and responses (similar to httpcontext), and the server uses a soapextension class "Microsoft. web. services. webservicesextension "allows us to verify the SOAP message of the inbound, and also provides the request and response soapcontext that we can access from our webmethod.

The biggest obstacle to learning to use WSE is that it is sometimes difficult to understand Microsoft's technical documentation and relatedArticleEven for experienced senior developers, there are few articles about this. In this article, I will give a simple example to introduce how to use WSE to verify the basic user name token to ensure the security of web services.

3. Set the WSE Environment

To set the basic WSE environment, we need to configure the ASP. NET applicationProgramTo enable WSE soapextension. The simplest way is to add the/configuration/system. Web/WebServices/soapextensiontypes/Add element to Web. config in your web service virtual directory, as shown below:

<WebServices>
<Soapextensiontypes>
<Add type = "Microsoft. web. services. webservicesextension, Microsoft. web. services, version = 1.0.0.0, culture = neutral, publickeytoken = 31bf3856ad364e35 "priority =" 1 "group =" 0 "/>
</Soapextensiontypes>
</WebServices>

Note that the type attribute must be written in one row, but the length of the attribute must be divided into several lines. Therefore, please pay more attention to it. Note that before using WSE, we must add a reference to Microsoft. Web. Services. DLL to the project.

4. basic user name Token Authentication

Before we digitally sign a SOAP message, we must first figure out who is signing the message. Therefore, we will discuss the concept of userNameToken and how WSE allows us to verify the user name token.

To use WSE to verify the user name/password in web services, we need to know what WSE provides for us in this respect? WS-Security defines a userNameToken element, which provides the basic username/password verification method. If you have experience using HTTP, you will find that userNameToken is very similar to basic authentication. There are three user name tokens, but we are usually only interested in the last two:

<! -- Plaintext password -->
<UserNameToken>
<Username> user1 </username>
<Password type = "wsse: passwordtext"> suangywang </password>
</UserNameToken>

This method uses the plaintext password. It is hard to imagine that a database will be checked on the server, the user name and password will be verified, and whether there is a matching user name/password for this series of verification operations.

<! -- Password summary -->
<UserNameToken>
<Username> user1 </username>
<Password type = "wsse: passworddigest">
Qsmako67 + vzynu9tcmsqofxy14u =
</Password>
</UserNameToken>

This method sends a password Digest (Digest) instead of the plaintext password. With the password digest, the password will not be sent over the network, so that hackers are unlikely to calculate the Web Service password. The password digest is calculated using hash functions. This process is only one-way, meaning that it is impossible to reverse the function and find the message corresponding to the abstract, because this process is implemented in this way, therefore, it is difficult to calculate the two passwords that are hashed to the same abstract. However, hackers can send hash passwords and then impersonate the original sender for verification. To avoid this problem, Web Services Security addendum (Web Service Security Addendum) has added an auxiliary protection measure. The addendum specifies that the digest version of the password must be sent, not just the hash password. The summary contains a password hash that identifies the unique nonce and creation time of the request. Therefore, two identical passwords are not hashed. The modified username token userNameToken is shown as follows.

<! -- Modified username token -->
<Wsse: userNameToken
Xmlns: wsu = "http://schemas.xmlsoap.org/ws/2002/07/utility"
Wsu: Id = "SecurityToken-59845323-5dcb-4a6b-a7fb-94a0d7357a20">
<Wsse: username> user1 </wsse: username>
<Wsse: password type = "wsse: passworddigest">
Gpbdxjx79eutcxdtlulilcrssi =
</Wsse: Password>
<Wsse: nonce>
H52si9pkv0bvrpuolqc7cg =
</Wsse: nonce>
<Wsu: created> 2003-6-20t21: 16: 50z </wsu: created>
</Wsse: userNameToken>

Although each legal request has a different hash, you must also prevent malicious users from dropping the entire userNameToken in the legitimate request of other users into their own illegal requests. You can use timestamp (timestamp header) to minimize this risk. The timestamp header indicates the message creation time and expiration time, indicating the message cycle and when the message can be considered invalid. For example, you may want to specify that the message will expire after 40 seconds, and the server will not receive the userNameToken after 40 seconds. However, clock synchronization between machines may result in the rejection of valid requests. Therefore, using timestamps is not a perfect solution. To solve this problem, the Web service can save a table with the nonce value of the recently received userNameToken. If the nonce value of the received request has been used, this request will never be accepted. If you receive several requests that use the same nonce, you should consider dropping all these requests, because it is very likely that the first request is illegal. We also need to learn that the nonce check technology does not prevent malicious users from intercepting valid input information, and add userNameToken in the original information to our own message and then send it to the destination. In this case, you need to add a digital signature or security certificate to the message to protect it from attacks. Knowledge about digital signatures and security certificates is not covered in this article. Please refer to the relevant documents.

All hash protection requires the message sender and receiver to know the user's password. On the client, people expect the system to prompt the user to enter the password. On the server side, you need to save a table with a valid user name/password pair for the system to search. The following describes how WSE uses a password provider mechanism to solve these two problems.

V. ipasswordprovider Interface

WSe defines a Microsoft. Web. Services. Security. ipasswordprovider interface class. We must implement this class to register a password provider. This interface has a method GetPassword, which receives a Microsoft. Web. Services. Security. userNameToken as the input parameter. This method returns the password of the specified user. The idea is that you can use any mechanism you want to use to save valid user name/password pairs, and then provide a class to implement the ipasswordprovider interface, to allow WSE to access your specific Password Storage Mechanism. You can even execute the combination of your own userNameToken Digest (Digest) and hash, or even use a shared password to further control your Authentication Infrastructure.

To inform WSE of your specific password provider, you must configure the appropriate WSE settings. First, add a Microsoft. Web. Services element to the configuration element in the configuration file of the application. You also need to specify the WSE class that can read specific configuration information. You can add the following configsections to machine. config or a separate web. config.

<Configsections>
<Section name = "Microsoft. Web. Services"
Type = "Microsoft. Web. Services. configuration. webservicesconfiguration,
Microsoft. Web. Services, version = 1.0.0.0, culture = neutral,
Publickeytoken = 31bf3856ad364e35 "/>
</Configsections>

In this example, a modified version of the Employees table of the northwind database is used for query tasks. Because the passwordprovider interface needs to return an actual password that matches the password of the userNameToken object, we usually only need to use WSE to encrypt our user name and password, then, it is transmitted to the Web service over the network.

If you select your project in Solution Explorer and right-click it, you will see a new menu "WSE Settings" added at the bottom ", you can set all important configurations and other WSE-based configurations:

This makes it easy to set the password provider implementation element, decryption key provider implementation element, And X.509 Certificate (X.509 Certificate) settings, even the binary security tokens we want to use ). In addition, other tabs can also be used to configure the input and output filters for the WSE pipeline, configure routes, and enable diagnostic functions. Although it cannot do everything we want to do, it is a good start for WSE's ease of use.

The passwordprovider security element is a child element of the <configuration> parent element in Web. config. It tells WSE which class you use to implement the passwordprovider interface:

<Microsoft. Web. Services>
<Security>
<! -- Namespace. classname, assemblyname -->
<Passwordprovider type = "wsesecurity. wsepasswordprovider, wsesecurity"/>
</Security>
</Microsoft. Web. Services>

Let's see how to implement it in this example:

Namespace wsesecurity
{
Public class wsepasswordprovider: ipasswordprovider
{
Public String GetPassword (userNameToken token)
{
Try
{
Sqlconnection Cn = new sqlconnection (system. configuration. configurationsettings. appsettings ["sqlconn"]. tostring ());
CN. open ();
Sqlcommand cmd = new sqlcommand ("select username, password from employees where username = '" + token. username + "'", CN );
Sqldatareader DR = cmd. executereader (commandbehavior. closeconnection );
Dr. Read ();
Return Dr ["password"]. tostring ();
}
Catch (exception ex)
{
Throw new exception (ex. Message );
}
}
}
}

TheCodeYou can fully implement the ipasswordprovider interface and verify a user by using the user name/password. Of course, you can also make it more complex, which should be done by the readers themselves. In fact, in the programming process, we basically did not write much user verification code, and most of the work was secretly handled by WSE.

6. Compile a webmethod using WS-Security

now we need to create a webmethod using WS-Security. Here, I implemented a simple method, which runs the custorderhist stored procedure of the northwind database, receives a string userid as a unique parameter, and returns a dataset. If the client that calls the Web service can pass message-level userNameToken verification, the dataset can be retrieved. If the verification fails, the client will receive an exception notifying it that the verification fails. The advantage of WSE is that you only need to pay a little effort, and most of the work has been done by WSE for you, so you can spend most of your time building Web service content, instead of being exhausted in order to build a secure web service mechanism.

[webmethod]
Public dataset custorderhist (string custid)
{< br> // only accept requests in the soap format
soapcontext requestcontext = httpsoapcontext. requestcontext;
If (requestcontext = NULL)
{< br> throw new applicationexception ("non-SOAP request! ");
}< br> bool valid = false;
try
{< br> foreach (securitytoken tkn in requestcontext. security. tokens)
{< br> If (tkn is userNameToken)
valid = true;
}< BR >}< br> catch (exception ex)
{< br> throw new exception (ex. message + ":" + ex. innerexception. message);
}< br> If (valid = false)
throw new applicationexception ("invalid or missing security token. ");
sqlconnection CN;
sqldataadapter da;
dataset Ds;
Cn = new sqlconnection (system. configuration. configurationsettings. appsettings ["sqlconn"]. tostring ();
CN. open ();
da = new sqldataadapter ("custorderhist '" + custid + "'", CN);
DS = new dataset ();
da. fill (DS, "custorderhist");
return Ds;
}

Using the webmethod above, we can verify the user name/password on the server. Webmethod must reference the Microsoft. Web. Services and Microsoft. Web. Services. security domain names. Now, we need to build an ASP. Net client that can send the SOAP header required for verification and call our web service method.

7. Construct the wse asp. NET Client

For clients, WSE provides the Microsoft. Web. Services. Protocols. soaphttpclientprotocol class inherited from the system. Web. Services. webservicesclientprotocol class. When you select "add web referencecelistener" in Visual Studio. NET, you need to use the wsdl.exe program to create the WSDL-based client code. What you can do is to use the "add web reference” wsdl.exe program in Visual Studio. NET to generate a proxy class for your client, and then inherit the proxy class from soaphttpclientprotocol to webservicesclientprotocol. In this way, the proxy class has the requestsoapcontext and responsesoapcontext attributes. You can use them to access the WS-Security header you send or receive. In the C # project, if you have used the "add web reference" option, you can click "show all files" in Solution Explorer, click this button to display the reference in the web references node of Solution Explorer. CS file, allowing you to edit this file.

To create a correct userNameToken and call the Web Service proxy method at the message level, use the following code:

Private void button#click (Object sender, system. eventargs E)
{
Localhost. securityservicewse WSE = new localhost. securityservicewse ();
UserNameToken tkn = new userNameToken (txtusername. Text, txtpassword. Text, passwordoption. sendhashed );
WSe. requestsoapcontext. Security. tokens. Add (tkn );
Try
{
Dataset DS = WSE. custorderhist (txtcustid. Text );
Datagrid1.datasource = Ds;
Datagrid1.databind ();
}
Catch (exception ex)
{
Maid = false;
Lblmessages. Text = ex. message;
}
}

What we need to do is to obtain the input string from the two text input boxes txtusername and txtpassword on the client, and then use passwordoption. sendhashed to combine them to create a valid userNameToken. When a Web Service is called, The WSE soap extension verifies the general format of the request, then checks the password hash and obtains the password from our passwordprovider method. If the two match, we can call the Web service method. The client returns the dataset and displays it in a grid.

We have now created a complete Web service that uses WSE in combination with the database to verify the sha1 digest hash username/password, it is hoped that the readers will learn the basic measures and methods for using WSE to ensure the security of web services and apply them rationally in their actual work.

At the end of the article, we will provide an SQL script for modifying the table employees of the northwind database, add the username and password columns required for this table, and insert a new record in this table, the firstname, lastname, username, password, and roles fields are respectively "user", "one", "user1", "pass1", and "user ".

Use northwind
Go
Alter table [DBO]. [employees]
Add [username] [varchar] (100) Collate SQL _latin1_general_cp1_ci_as null,
[Password] [varchar] (100) Collate SQL _latin1_general_cp1_ci_as null,
[Roles] [varchar] (250) Collate SQL _latin1_general_cp1_ci_as null
Go
Insert into employees (firstname, lastname, username, [Password], roles)
Values ('user', 'one', 'user1', 'pass1', 'user ')
Go

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.