Use WSE to verify user identity in Web Services (2)

Source: Internet
Author: User
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.MethodReturns the password of the specified user. The idea is that you canUseAny mechanism you want to use to save valid user name/password pairs, and then provide a class that implements the ipasswordprovider interface to allow WSE to access your specific PasswordStorageMechanism. 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. Add a Microsoft. Web. Services ElementApplicationThe configuration element in the configuration file of the program. 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, and then passNetworkTo the web service.

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 (BinarySecurityToken ). In addition, you can configure the input and output filters for the WSE pipeline on other tabs.RoutingTo enable the diagnosis function. 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); } } }}

The code above 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.

Webmethod] public dataset custorderhist (string custid) {// only accept requests in the soap format soapcontext requestcontext = httpsoapcontext. requestcontext; If (requestcontext = NULL) {Throw new applicationexception ("non-SOAP request! ");} Bool valid = false; try {foreach (securitytoken tkn in requestcontext. security. tokens) {If (tkn is userNameToken) Valid = true ;}} catch (exception ex) {Throw new exception (ex. message + ":" + ex. innerexception. message);} 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 canServerTo verify the user name/password. 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 Button1_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) {DataGrid1.Visible=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 NORTHWINDGOALTER TABLE [dbo]. 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 GOINSERT INTO EMPLOYEES (Firstname, Lastname,Username, [Password], roles)VALUES('User','One', 'user1', 'pass1', 'user')GO

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.