Build Secure Web Services with Soap Headers and Extensions

zhaozj2021-02-16  64

Build Secure Web Services with Soap Headers and Extensions

Rating:

Jeff Prosise (View Profile) April 17, 2003

Environment: .NET: .NET

Using Soap Headers and SOAP Extensions to Build Secure Web Services with the microsoft .net framework

Programming Insights ...

(Continued)

By Jeff Prosise of Wintelle

Legions of Web developers have built Web services using the Microsoft .NET Framework and have learned how easy it is to get a basic Web service up and running. Just create an ASMX file, add a class, decorate its methods with the [WebMethod] attribute And Presto! Instant Web Service. The Framework Do Class Methods, Leaving You To Concentrate On The Business Logic That Makes your Web Service Unique.

Building Web services with the .NET Framework is easy-easy, that is, unless the Web services are secure. There is no standard, agreed-upon method for exposing Web services over the Internet in such a way that only authorized users can call them . WS-Security will one day change that, but for now, you're on your own. One Microsoft sample published last year demonstrates how to secure Web services by passing user IDs in method calls. While functional, that approach is less than optimal because it mixes real data with authentication data and, to first order, requires each and every Web method to perform an authorization check before rendering a service. A better solution is one that passes authentication information out-of-band (that is, outside the Web methods' parameter lists) and this "front-ends" Each Method Call with an automation module That Operates Independently of the Web Methods Themselves.

SOAP headers are the perfect vehicle for passing authentication data out-of-band. SOAP extensions are equally ideal for examining SOAP headers and rejecting calls that lack the required authentication data. Combine the two and you can write secure Web services that cleanly separate business logic from security logic. In this column, I'll present one technique for building secure Web services using SOAP headers and SOAP extensions. Until WS-Security gains the support of the .NET Framework, it's one way to build Web services whose security infrastructure is Both Centralized and Protocol-Independent.The Quotes1 Web Service

Let's start with the Web service in Figure 1. Called "Quote Service," it publishes a single Web method named GetQuote that takes a stock symbol (for example, "MSFT") as input and returns the current stock price.

Figure 1: quotes1.asmx

<% @ WebService Language = "C #" Class = "QuoteService"%> using System; using System.Web.Services; using System.Web.Services.Protocols; [WebService (Name = "Quote Service", Description = "Provides instant stock quotes to registered users ")] public class QuoteService {[WebMethod (Description =" Returns the current stock price ")] public decimal GetQuote (string symbol) {if (symbol.ToLower () ==" msft ") return 55.0m ELSE IF (Symbol.Tolower () == "INTC") Return 32.0m; Else Throw new soapexception ("unrecognized symbol", soapexception.clientfaultcode;}}

You can test Quotes1.asmx with the console application in Figure 2. First, use the .NET Framework SDK's Wsdl.exe utility to generate a Web service proxy If Quotes1.asmx is stored in the local machine's wwwroot directory, the commandwsdl http.: //localhost/quotes1.asmx

GENERATES A Source Code File Named Quote Service.cs Containing A Proxy Class Named QuoteService. Next, Compile Client1.cs and quote service.cs:

CSC Client1.cs "quote service.cs"

Finally, Test The Resulting Executable by Issuing The Following Command:

Client1 MSFT

The Application Should Respond by Reporting A Current stock Price of 55.

Figure 2: Client1.cs

Using system; class client {static void main (string [] args) {if (args.length == 0) {console.writeline ("please support symbol"); return;} quoteservice (); Decimal price = qs.getquote (args [0]); console.writeline ("The Current Price of" Args [0] "IS" Price);}}

The quotes2 Web Service

Quotes1.asmx's GetQuote method is simple enough that anyone can call it And that's just the problem:.. Anyone can call it Assuming you'd want to charge for such a service, you would not want for it to be available to everyone. Rather, You'D Want To Identify The Caller On Each Call to getQuote and throw a soapexception if the caller is not authorized.

Figure 3 lists a revised version of Quote Service that uses a custom SOAP header to transmit user names and passwords A SOAP header is a vehicle for passing additional information in a SOAP message The general format of a SOAP message is..:

... ... SOAP Headers Are Optional. Here's A SOAP MESSAGE THAT LACKS A HEADER:

Jeff < / Username> Imbatman

makes AuthHeader a required header for calls to GetQuote and transparently maps user names and passwords found in AuthHeaders to the corresponding fields in Credentials.Calls lacking AuthHeaders will not even reach GetQuote. Calls that do reach it can be authenticated by reading Credentials' UserName and Password Fields. GetQuote Checks the user name and password and fails the call if each is invalid:

IF (credentials.username.tolower ()! = "jeff" || Credentials.password.tolower ()! = "Imbatman") Throw new soapexception ("unauthorized", soapexception.clientfaultcode;

In the real world, of course, you'd check the caller's credentials against a database rather than hard-code a user name and password. I took the easy way out here to keep the code as simple and understandable as possible.

Figure 2: quotes2.asmx

<% @ WebService Language = "C #" Class = "QuoteService"%> using System; using System.Web.Services; using System.Web.Services.Protocols; [WebService (Name = "Quote Service", Description = "Provides instant stock quotes to registered users ")] public class QuoteService {public AuthHeader Credentials; [SoapHeader (" Credentials ", Required = true)] [WebMethod (Description =" Returns the current stock price ")] public decimal GetQuote (string symbol) { // Fail the call if the caller is not authorized if (Credentials.UserName.ToLower ()! = "jeff" || Credentials.Password.ToLower ()! = "imbatman") throw new SoapException ( "Unauthorized", SoapException. ClientFaultCode); // Process the request if (symbol.ToLower () == "msft") return 55.0m; else if return 32.0m (symbol.ToLower () == "intc"); else throw new SoapException ( "Unrecognized Symbol ", soapexception.clientfaultcode);}} public class authhead;}} public string password;} to call the quotes2.asmx version of getquo te, a client must include a SOAP header containing the user name "Jeff" and the password "imbatman." Figure 4 demonstrates how. Because AuthHeader is defined in Quotes2.asmx and is therefore described in the Web service's WSDL contract as a complex type , a proxy file generated by wsdl.exe contains an authheader definition, too. in Client2.cs, The Statements

Authheader Credentials = new authheader (); credentials.username = "jeff"; credentials.password = "objectman"; QS.AuthHeaderValue = Credentials;

Create An Authheader and Associate It With The Proxy named qs. The .NET Framework Turns Authheaders Into Soap Headers Each Time The Proxy's getQuote Method Is Called.figure 4: Client2.cs

Using system; class client {static void main (string [] args) {if (args.length == 0) {console.writeline ("please support symbol"); return;} quoteservice (); AuthHeader Credentials = new AuthHeader (); Credentials.UserName = "jeff"; Credentials.Password = "imbatman"; qs.AuthHeaderValue = Credentials; decimal price = qs.GetQuote (args [0]); Console.WriteLine ( "The current Price of " args [0] " IS " price);}}

The Quotes3 Web Service

Quotes2.asmx is a step in the right direction because it transmits authentication data in every request. Using SOAP headers for transport means the information is passed out-of-band and that it is not tied to any particular protocol, such as HTTP. But Quotes2.asmx still leaves room for improvement. Currently, every Web method has to check user names and passwords. The next logical step is to get the authorization code out of the Web methods and into a module that examines incoming requests as they arrive and REJECTS Those Lacking Valid Credentials.

A SOAP extension is the perfect tool for the job. Physically, a SOAP extension is a class derived from System.Web.Services.Protocols.SoapExtension. Logically, it's an object that sits in the HTTP pipeline and enjoys access to the SOAP messages entering and leaving. Quotes3.asmx (Figure 5) demonstrates how to use a SOAP extension to extract user names and passwords from SOAP headers. Observe that GetQuote no longer performs any checking of its own. Instead, it's attributed with [AuthExtension], which associates it with the SOAP extension class named AuthExtension. [AuthExtension] is an instance of AuthExtensionAttribute, which is a custom attribute class derived from the Framework's SoapExtensionAttribute class. In AuthExtensionAttribute, the following override ensures that AuthExtension will be called for any method attributed with [AuthExtension ]: Public override type extensionType {get {return type;}}

The SOAP extension class AuthExtension derives from SoapExtension Its heart is its ProcessMessage method, which is called four times every time GetQuotes is invoked:. Once before the message is deserialized by the Framework, once after it's deserialized but before QuoteService.GetQuote is called, again after QuoteService.GetQuote has executed but before the response is serialized into a SOAP message, and a final time after the response is serialized. AuthExtension checks the message after it is deserialized by the .NET Framework. If the message contains no AuthHeader or if it contains an AuthHeader with invalid credentials, AuthExtension rejects it by throwing a SoapException Significantly, GetQuote no longer has to do any authentication itself, because it never sees a message that has not been authenticated already.Figure 5:. Quotes3.asmx

<% @ WebService Language = "C #" Class = "QuoteService"%> using System; using System.Web.Services; using System.Web.Services.Protocols; [WebService (Name = "Quote Service", Description = "Provides instant stock quotes to registered users ")] public class QuoteService {public AuthHeader Credentials; [AuthExtension] [SoapHeader (" Credentials ", Required = true)] [WebMethod (Description =" Returns the current stock price ")] public decimal GetQuote (string Symbol) {if (Symbol.tolower () == "MSFT") Return 55.0m; Else IF (Symbol.Tolower () == "INTC") Return 32.0m; Else Throw new soapexception ("Unrecognized Symbol", SOAPException. ClientFaultCode);}} public class AuthHeader: SoapHeader {public string UserName; public string Password;} [AttributeUsage (AttributeTargets.Method)] public class AuthExtensionAttribute: SoapExtensionAttribute {int _priority = 1; public override int Priority {get {return _priority;} Set {_priority = value;}} public override type extensiontype {get {return type (AuthExtension);}}} public class AuthExtension: SoapExtension {public override void ProcessMessage (SoapMessage message) {if (message.Stage == SoapMessageStage.AfterDeserialize) {// Check for an AuthHeader containing valid // credentials foreach (SoapHeader header in message.Headers) {if (header is AuthHeader) {AuthHeader credentials = (AuthHeader) header; if (credentials.UserName.ToLower () == "jeff" && credentials.Password.ToLower () == "imbatman") return; // allow call to execute break;

}} // Fail the call if we get to here Either the header // is not there or it contains invalid credentials throw new SoapException ( "Unauthorized", SoapException.ClientFaultCode);..}} Public override Object GetInitializer (Type type ) {return GetType ();} public override Object GetInitializer (LogicalMethodInfo info, SoapExtensionAttribute attribute) {return null;} public override void Initialize (Object initializer) {}} For an added touch, you could move AuthHeader, AuthExtensionAttribute, and AuthExtension to a Separate Source Code File, Compile The DLL in The Web Service's Bin Directory. Then, The Asmx File Would Reduce To this:

<% @ WebService Language = "C #" Class = "QuoteService"%> using System; using System.Web.Services; using System.Web.Services.Protocols; [WebService (...)] public class QuoteService {public AuthHeader Credentials [Authextension] [SOAPHEADER ("Credentials", Required = true)] [WebMethod (Description = "Returns The Current stock price")] public decimal getquote (string symbol) {...}}

IF you add more methods to the Web service, Simply Decorate Theme with [automatic] attributes and the, too, will be authenticated by the soap extension.

Summary

Quotes3.asmx demonstrates how to combine SOAP headers and SOAP extensions to authenticate callers to Web services and to do so without explicitly authenticating in the Web methods themselves. Do be aware that authenticating callers by encoding plaintext user names and passwords in SOAP headers is not secure unless you encrypt the message traffic. One way to encrypt SOAP messages is to write a SOAP extension that unencrypts requests and encrypts responses. Another way to do it is to use SSL-that is, to publish the Web service at an HTTPS address. How You Do It Isn't Important; What's Important Is To Avoid Passing Unencrypted Credentials Over Unsecured Connections.about The Author ...

Jeff Prosise is a cofounder of Wintellect, a consulting, debugging, and education firm that specializes in .NET. His latest book, Programming Microsoft .NET, was published last year by Microsoft Press. Jeff is also a columnist for MSDN Magazine and asp. Netpro Magazine.

转载请注明原文地址:https://www.9cbs.com/read-19084.html

New Post(0)