0 penilaian0% menganggap dokumen ini bermanfaat (0 suara)
21 tayangan38 halaman
.NET Framework includes a full-featured Web Services infrastructure. A Web Service can host an object on a computer using protocols that can pass across the Internet. Web Services communicate with their clients using a protocol named SOAP.
.NET Framework includes a full-featured Web Services infrastructure. A Web Service can host an object on a computer using protocols that can pass across the Internet. Web Services communicate with their clients using a protocol named SOAP.
.NET Framework includes a full-featured Web Services infrastructure. A Web Service can host an object on a computer using protocols that can pass across the Internet. Web Services communicate with their clients using a protocol named SOAP.
.NET Security Professional Skills Development 12-1
Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Web Services Objectives Understand security for Web services. Set authentication and authorization options for Web services. Pass credentials to a Web service.
The files associated with this chapter are located in the following folders: ! c:\Security.NET\WebServices ! {inetpub\wwwroot}\SecurityNET\OrderService ! {inetpub\wwwroot}\SecurityNetLabs\WebServicesLab ! {inetpub\wwwroot}\SecurityNetLabs\WindChillService Web Services 12-2 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Web Services Overview In this chapter, youll learn about your options for securing Web Services written using the .NET Framework. You may not have had a chance to experiment with Web services yet, so well start by giving you an overview of the Web services infrastructure and then build a sample Web Service and a client that can access it. The basic goal of a Web service is simple: to host an object on a computer using protocols that can pass across the Internet. Web services communicate with their clients using a protocol named SOAP, the Simple Object Access Protocol. SOAP messages are XML messages that are transported over HTTP. SOAP can cross most networks and firewalls without problems, making it an attractive protocol for universal communications. Web Services Features The .NET Framework includes a full-featured Web services infrastructure. Before you start looking at code, its helpful to have an overview of some of the features of this infrastructure: Standardized Protocols: Web services use SOAP and other Internet- standard protocols. These standards are widely agreed upon, making it possible for Web service clients and servers to communicate across language, component model, and platform boundaries. Interface Description: The Web Services Description Language (WSDL) protocol provides a standard means for a Web Service to identify the messages that it can process and the data that it accepts and returns. Loose Coupling: Clients of a Web service do not have any dependence on the internal implementation of a Web service. Any client that can implement the proper interface can use the Web service. ASP.NET: In the .NET universe, Web services are layered on top of the ASP.NET infrastructure. As youll see over the course of this chapter, this enables them to use the authentication and authorization features built into ASP.NET for security. Examining a Web Service Application Lets start by looking at a very simple Web service. This application allows a client to enter e-commerce orders; each order is characterized by an item name and a quantity. The Web service saves the incoming orders to a text file and returns an acknowledgement message to the client. The Web service could be running on any computer that the client can connect to via HTTP, either on the Open WebServices.sln Web Services Overview .NET Security Professional Skills Development 12-3 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Internet or on an intranet. For simplicity, well run them both on the same computer. The Sample Project In order to configure the sample application so that it works correctly, you will need to take the following actions: ". Launch Windows Explorer and right-click on the c:\InetPub\wwwroot\SecurityNet\OrderService folder. Select Properties and click on the Security tab. 2. Select the Everyone group. Verify that this group does not have write permissions on the folder. If the Everyone group does have Write permissions, select the Deny check box to remove them. 3. Click the Add button to add a new user account. Select the ASPNET user from the local computer. Click Add, and then OK. 4. Select the Allow CheckBox to grant Write permissions to give the ASPNET user write access to the folder and click OK. In an ASP.NET project, you define a Web service by creating a class that inherits from the System.Web.Services.WebService class and decorating it with the WebService attribute as shown in Figure ", where a fragment of the Order.asmx.vb file is displayed.
Figure ". Creating a Web Service class. The WebService attribute must specify a Namespace property for the Web Service. This property is a unique URI (Uniform Resource Identifier). It need not be an actual URL thats reachable over the Internet. You should choose a Namespace thats unlikely to be used by other developers; including the name of your company or Web site is normally a good idea. Marking a class with this attribute specifies that the Web service will allow clients to create instances of the class. But a class with no interface isnt very useful. Thats why in any useful Web service youll also find Web methods. Open Order.asmx in OrderService Web Services 12-4 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Defining a Web Method To define a Web method, decorate a method declaration with the WebMethod attribute. The Order class contains a single Web method named PlaceOrder that takes an ItemName and Quantity:
<WebMethod()> _ Public Function PlaceOrder( _ ByVal ItemName As String, _ ByVal Quantity As Integer) As String
The PlaceOrder method begins by starting a Try block, then uses classes from the System.IO namespace to write the incoming data to a disk file:
Try ' Add the order to our file of orders Dim fs As New FileStream( _ Server.MapPath("Orders.txt"), _ FileMode.Append, FileAccess.Write) Dim sw As New StreamWriter(fs) sw.WriteLine(DateTime.Now.ToLongTimeString) sw.WriteLine("Order for {0} of {1}", _ Quantity.ToString, ItemName) sw.WriteLine("-------------------------------") sw.Flush() sw.Close() fs.Close()
When all of the data is written, the method returns a message to the caller by setting it as the return value for the method:
' And let the user know it worked Return "Your order has been placed"
If anything goes wrong (for example, if the code does not have permission to write to a disk file on the server), the Catch block returns an error message to the caller. Youd replace the ex.Message call with a more generic and less informative message in the production version of your application. Web Services Overview .NET Security Professional Skills Development 12-5 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Catch ex As Exception ' Tell the user there was a problem Return "An error (" & ex.Message & ") " & _ "occurred when placing your order." End Try
Building the Web Service Client Thats all there is to the Web service, at least as far as code that you need to write yourself. Everything else (listening for incoming SOAP requests, generating SOAP responses, creating WSDL, and other infrastructure tasks) is performed by ASP.NET without your intervention. But like any server, a Web service isnt very useful without a client. So weve built a simple client project that can invoke the Web service. Setting a Web Reference The key to building a Web service client application in Visual Studio .NET is to create a Web Reference that points to the desired server. A Web Reference is just like a regular reference to a class library. They key difference is that a Web Reference points to a server via HTTP. Try It Out! Although weve already set up the Web Reference in the sample project, its worth seeing how easy Visual Studio .NET makes the process of creating one. Follow these steps to set a Web Reference to OrderService: ". Right-click on the project in the Solution Explorer and select Add Web Reference. This opens the Add Web Reference dialog box. 2. Type the address of the WSDL file in the Address box and press ENTER.
See OrderClient Web Services 12-6 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
3. This will connect to the Web service and display some details, as shown in Figure 2. Click Add Reference to add the Web Reference to the project.
Figure 2. Adding a Web Reference to a project. TIP: When youre using a Web service developed in ASP.NET, there isnt a separate WSDL file. Rather, you can cause the server to deliver the WSDL file by appending the ?wsdl string to the end of the URL for the Web Services main file. Using the Web Reference After youve added a Web Reference to your project, you can use objects from the Web service just as you can from any local class library. The sample client project contains a form that allows you to input an item name and a quantity, and then sends a SOAP request to the Web service. To do so, the client first creates an instance of the class provided by the Web service:
Dim wsOrd As New localhost.Order()
Open frmWebService Client.vb in OrderClient Web Services Overview .NET Security Professional Skills Development 12-7 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Here localhost is the namespace that Visual Studio .NET created for the Web service when you added the Web Reference. Theres nothing special about this name; it was created from the URL that you typed in the Add Web Reference dialog box. Theres no way to tell, just by inspecting the client code, that this name refers to an object supplied by a Web service. After creating the object, the client is free to invoke its public method:
The result of the Web service call is displayed in a Label control on the client user interface. Try It Out! To verify that the Web service and the client are working properly with no security, follow these steps: ". Set the OrderClient project as the startup project for the solution. 2. Click F5 to start the project. 3. Click the Web Service Client button on the Switchboard form. 4. Enter an item name and a quantity on the Web Service Client form. 5. Click the Send Request button. After a short delay, the confirmation message should appear at the bottom of the form as shown in Figure 3.
Figure 3. Placing an order with the Web service. Web Services 12-8 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
6. Stop the project. 7. Open the Orders.txt file c:\InetPub\wwwroot\OrderService\Orders.txt. Youll see the order you just placed, as shown in Figure 4.
Figure 4. An order saved by the Web service. The Proxy Class How can the client project possibly treat a remote object as though a local class library provided it? The answer lies in a proxy class that Visual Studio .NET automatically creates when you add a Web Reference to a project. When you create an object from the Web service in code, youre really creating an instance of the proxy class. Method calls to the proxy class are passed to the Web service, and return values from the Web Service are in turn forwarded to your calling code. To see the code in the proxy class, first click the Show All Files button on the Solution Explorer toolbar. Then drill into the Web References folder until you locate the Reference.vb file, as shown in Figure 5.
Figure 5. Adding a Web Reference builds a proxy class automatically. See Reference.vb Web Services Overview .NET Security Professional Skills Development 12-9 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
If you inspect the code in the proxy class, youll discover that it inherits from another of the Web Service classes in the .NET Framework:
Public Class Order Inherits System.Web.Services.Protocols. _ SoapHttpClientProtocol
This class includes wrapper methods for each Web Method that the Web service provides. For example, Figure 6 shows the wrapper for the PlaceOrder method:
Figure 6. The PlaceOrder method wrapper in Reference.vb. Without digging any more deeply into the plumbing that lies behind this method, you can see that it contains the Namespace URI that we declared for the Web service, as well as other parameters that control the SOAP conversation. In many cases you can just ignore the proxy class, because it will just work. But as youll see a bit later in this chapter, when youre working with secured Web services you may need to add your own code to the proxy. Web Services 12-10 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Disabling Unwanted Protocols Sometimes, the open protocol support in Web services is more than you want or need. In particular, you may wish to control two aspects of Web services that you develop using ASP.NET: Web service invocation via HTTP GET or HTTP POST Interface publication via WSDL Youll learn how to disable these facets of a Web service in this section of the chapter. Disabling GET and POST Although youll frequently find references to using SOAP to invoke a Web service, if you develop your Web service with Visual Studio .NET youll also receive HTTP GET and HTTP POST invocation for free. To see how these protocols work with a Web Service, you can explore the Add Web Reference dialog box a bit further: ". Right-click on the Web References node in the OrderClient project in the WebServices solution, and select Add Web Reference. 2. In the Address box, enter the following and then press ENTER.
Note that in this case youre not asking specifically for the WSDL file, but for all information that the page can provide about the Web service. See WebServices.sln Disabling Unwanted Protocols .NET Security Professional Skills Development 12-11 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
3. Click the PlaceOrder link in the left pane of the Add Web Reference dialog box. This opens an HTML page where you can test the Web service. If you scroll down this page, youll see the SOAP, HTTP GET, and HTTP POST messages that can be used to invoke the Web service, as shown in Figure 7.
Figure 7. You can use the HTTP GET and HTTP POST methods to invoke the Web service. 4. Click Cancel to dismiss the dialog box. NOTE You can view this page in any browser window, not only in the Add Web Reference dialog box. HTTP GET and POST Vulnerability This feature of the Add Web Reference dialog box depends on the ability to invoke an ASP.NET-developed Web service via HTTP GET rather than via SOAP. Although this is convenient during development, it can represent a security hole in some circumstances. Consider the case in which your company uses an internal Web server, behind a firewall, to deliver private Web services to an intranet. Now, suppose an attacker has knowledge of the interface to this internal Web service. That attacker could create a malicious Web page on an external server. If you browse to that Web page, it can use an HTTP redirect that causes your browser to send a call to the internal Web service. Web Services 12-12 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Editing the Machine.config File To avoid this scenario, you need to disable HTTP GET and HTTP POST for your Web service. You can do this easily by making the proper settings in the Machine.config file on the computer that hosts the Web service. Try It Out! To disable HTTP GET and HTTP POST for the OrderService Web service, follow these steps: ". Open the Machine.config file on your computer. By default, this file is installed in C:\WINNT\Microsoft.NET\Framework\ v1.0.3705\CONFIG where v".0.3705 is the current version of the .NET Framework installed on your computer. 2. Locate the <webServices> element in the file and edit the protocols to comment out the HTTP GET and HTTP POST protocols:
3. Save the Machine.config file. Disabling Unwanted Protocols .NET Security Professional Skills Development 12-13 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
4. Right-click on the Web References node in the OrderClient project and select Add Web Reference. 5. In the Address box, enter:
6. Press ENTER. 7. Click the PlaceOrder link in the left pane of the Add Web Reference dialog box. Youll see that you can no longer test the Web service; Figure 8 shows only the SOAP section.
Figure 8. OrderService details with HTTP GET and POST disabled. 8. Click Cancel to dismiss the dialog box. 9. Return the Machine.config file to its original state by removing the comments and saving the file. WARNING! Because these settings are in the Machine.config file, they apply to all Web services on the computer. If youd like to turn HTTP GET and HTTP POST back on for a specific Web service, you can add a Protocols section to the Web.config file for that particular Web service. Youll see in the next section how to leave a protocol in Machine.config but disable it for a specific Web service. Web Services 12-14 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Disabling WSDL In some cases you may also like to disable the automatic generation of WSDL for your Web services. For example, you might have a Web service deployed on the Internet that is designed for use only by specific business partners. In such a case, you might choose to disable WSDL to prevent non-partners from easily discovering the interface of the Web service. Again, you can do this by modifying the Web.config file for the Web service. Try It Out! Follow these steps to disable WSDL in the Web.config file for the Web service: ". Open the Web.config file for the OrderService Web service. 2. This time, instead of modifying the Machine.config file, youll override one of its settings in the Web.config file. Add a new section to the file, directly after the <system.web> element:
3. Save the Web.config file. 4. Right-click on the Web References node in the OrderClient project and select Add Web Reference. 5. In the Address box, enter:
6. Press ENTER. Disabling Unwanted Protocols .NET Security Professional Skills Development 12-15 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
7. Instead of the WSDL file, youll see an error message, as shown in Figure 9.
Figure 9. The effect of disabling automatic WSDL file generation. 8. Click Cancel. WARNING! Experienced developers will recognize this technique as a security through obscurity technique. If anyone knows the interface of your Web service, they can invoke its objects, whether you make a WSDL file available or not. So although disabling WSDL can provide a modicum of protection, its no substitute for authentication and authorization if you need to actually keep people from using objects. Web Services 12-16 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Secure Web Services with IIS and ASP.NET Because Web services run in ASP.NET, which is hosted on IIS, you can use the authentication features of IIS to associate an identity with the remoting client. After youve done that, you can use that identity to authorize (or deny) access to the objects provided by the Web service. Youll learn about both of these techniques in this section. Authentication with the Users Credentials To authenticate a client with a Web service, you need to take two steps: ". Tell IIS to require authentication for the Web application by setting the directory security properties. 2. Tell the client to reuse its credentials when making requests to the Web service object. Just authenticating with the IIS server isnt sufficient to pass the authenticated identity to the Web service. You must specify the credentials to be used for authentication via the Credentials property of the Web Service proxy class. If you neglect to do this, credentials wont be passed to the Web service, even if you successfully authenticate with ASP.NET. Fortunately, the code is simple, because you can extract the default cached credentials that were used to authenticate in the first place. Generally, youll want to place this code in the constructor of the proxy class:
Public Sub New() MyBase.New Me.Url = _ "http://localhost/SecurityNet/OrderService/Order.asmx" Me.Credentials = _ System.Net.CredentialCache.DefaultCredentials Me.PreAuthenticate = True End Sub
Secure Web Services with IIS and ASP.NET .NET Security Professional Skills Development 12-17 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Implementing Windows Authentication The code as shown extracts the default credentials that were used within the application to log on to the IIS server and passes them on to the Web Service when the proxy object is created. The PreAuthenticate property tells the proxy class to send the credentials with the initial request to the Web service, rather than waiting for rejection of an attempt without credentials. Try It Out! To require IIS to require authentication for your Web service application, follow these steps: ". Open Internet Services Manager. Right-click on the OrderService application and select Properties. 2. Select the Directory Security tab and click the Edit button. 3. Clear the Anonymous access check box. Make sure the Integrated Windows authentication check box is selected, as shown in Figure "0. Click OK twice to set the authentication method.
Figure "0. Setting a Remoting server to use IIS authentication. 4. Press F5 to start the client project. 5. Click the Web Service Client button on the Switchboard form. Web Services 12-18 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
6. Enter an item name and a quantity on the Web Service Client form. 7. Click Send Request. Youll see an error message, as shown in Figure "".
Figure "". Attempting to use a secured Web Service object. 8. Click OK. 9. Stop the project. "0. Open the Reference.vb file in OrderClient and add the following bolded statements to the constructor of the proxy class:
Public Sub New() MyBase.New Me.Url = _ "http://localhost/SecurityNet/OrderService/Order.asmx" Me.Credentials = _ System.Net.CredentialCache.DefaultCredentials Me.PreAuthenticate = True End Sub
"". Press F5 to start the client project. "2. Click the Web Service Client button on the Switchboard form. "3. Enter an item name and a quantity on the Web Service Client form and click Send Request. This time the form will display a confirmation message, because your authenticated credentials are passed to the Web service. "4. Stop the project and comment out the new lines of code. Secure Web Services with IIS and ASP.NET .NET Security Professional Skills Development 12-19 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Authentication over the Internet Although were demonstrating Web service authentication on a single computer, theres nothing to prevent you from using these same techniques over the Internet. A Web service piggybacks on ASP.NET and IIS, so it has access to the full range of authentication services offered by those layers of software. The simplest way to handle authentication over the Internet for a Web service is to create specific Windows accounts that have the desired privileges on the IIS server. Then you can turn off anonymous authentication on your IIS server and have external clients authenticate to those accounts by sending specific credentials, using the techniques that you just saw. Because Web services do not expose an ASP.NET user interface or cookies, you cant use Passport or Forms authentication directly with Web services. But you could develop an ASP.NET application that uses Passport or Forms authentication as a front end. The ASP.NET application could then call the Web service from the IIS server, using its own Windows identity to authenticate. Note that this workaround will not result in transfer of the Web Services objects all the way to the client; the ASP.NET application will need to extract, format, and forward the desired information. Authentication with Specific Credentials Youre not limited to using the same credentials with ASP.NET and the Web service. This is useful in cases where you want to allow a user with a low level of privilege to authenticate to the server and then impersonate an account with higher privileges for the purpose of the Web service call. To do this, you can create custom credentials in code and pass them to the Web service. To begin, add an Imports statement at the top of the Reference.vb file:
Imports System.Net
See Reference.vb in OrderClient Web Services 12-20 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Create a new NetworkCredential object with the login identity that you wish to use with the remote object. You can copy and paste the code from the ReferenceVbInserts.txt file within the OrderClient project.
' NOTE: Change the next line to use valid ' values for your Web server's domain Dim cred As New NetworkCredential( _ "username", "password", "domain")
Then you can build a Uri object that specifies the URI that will receive these credentials:
Dim objURI As New Uri(Me.Url)
Given the URI and a credential, you can create a new CredentialCache that uses that credential to access that URI. You can use Negotiate, Basic, Digest, Kerberos, or NTLM for authentication.
Dim cc As New CredentialCache() cc.Add(objURI, "NTLM", cred)
Apply this credential cache to the proxy class, set the PreAuthenticate property to True, and youre all set:
Me.Credentials = cc Me.PreAuthenticate = True
At this point, all method calls to the Web service through this proxy class will run in the specified user and domain security context. Test the application by pressing the F5 key and close when you are finished. Secure Web Services with IIS and ASP.NET .NET Security Professional Skills Development 12-21 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Authorization with the Web.config File ASP.NET Web services can use the same authorization tools as any other ASP.NET application. Specifically, you can configure a Web service to allow or deny users or groups with an <authorization> element in the Web.config file. The element has this syntax:
<authorization> <allow users="[comma separated list of users]" roles="[comma separated list of roles]"/> <deny users="[comma separated list of users]" roles="[comma separated list of roles]"/> </authorization>
In the lists of users and roles, you can use the asterisk (*) as a wildcard to specify all users, and the question mark (?) as a wildcard to specify the anonymous user. The default <authorization> element in a new Web.config file allows all users:
<authorization> <allow users="*" /> <!-- Allow all users --> </authorization>
Try It Out! Currently, the OrderService Web service accepts requests from any user who can authenticate with IIS. Follow these steps to change this so that only a particular user on the IIS computer can use the object. ". Edit the <authorization> element in the Web.config file for the OrderService Web service as follows. Substitute your own domain and username in the <allow> element, and deny all other users access in the <deny> element:
See Web.config in OrderService Web Services 12-22 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
2. Check to make sure that the code to pass login credentials to the Web Service object is still in place in References.vb. 3. Press F5 to start the client project. 4. Click the Web Service Client button on the Switchboard form. 5. Enter an item name and a quantity on the Web Service Client form. 6. Click Send Request. This should succeed. 7. Stop the client application. Edit the Web.config file to change your username to a nonexistent username in the <allow> element. 8. Press F5 to start the client project. 9. Click the Web Service Client button on the Switchboard form. "0. Enter an item name and a quantity on the Web Service Client form. "". Click Send Request. Youll get a 40" error message, as shown in Figure "2, because your account is not the (nonexistent) account that is authorized to use the object.
Figure "2. Authorization failure with Remoting server in IIS. "2. Edit the Web.config file back to its original state, allowing access from all users. Authorization with Principal Permission Demands If you prefer, you can also use role-based security within the actual classes that are being used as Web Service objects. When you use authentication with a Web service hosted in IIS, the authenticated identity is passed all the way to the object. This allows you to demand an appropriate PrincipalPermission to control access to the object. See Order.asmx.vb in OrderService Secure Web Services with IIS and ASP.NET .NET Security Professional Skills Development 12-23 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Try It Out! Follow these steps to demand appropriate PrincipalPermissions: ". Open the Order.asmx.vb file. Modify the declaration of the PlaceOrder method as follows, substituting your own domain and user name:
<WebMethod(), _ PrincipalPermission(SecurityAction.Demand, _ Name:="DOMAIN\Username")> _ Public Function PlaceOrder(ByVal ItemName As String, _ ByVal Quantity As Integer) As String
2. Right-click on the OrderService project and select Build. 3. Press F5 to start the client project. 4. Click the Web Service Client button on the Switchboard form. 5. Enter an item name and a quantity on the Web Service Client form. 6. Click Send Request. This should succeed, because you have authenticated as the user listed in the demand for permissions. 7. Stop the client application. Edit the PrincipalPermission attribute to change your username to a nonexistent username. Rebuild OrderService. 8. Press F5 to start the client project. 9. Click the Web Service Client button on the Switchboard form. "0. Enter an item name and a quantity on the Web Service Client form. "". Click Send Request. Youll get a security exception message, as shown in Figure "3, because the principal permission cannot be granted and the call will fail.
Figure "3. The Principal permission error message. Web Services 12-24 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
The Future: WS-Security Theres one important aspect of Web service security that you havent learned about yetbecause its not yet available in .NET. That is the use of the WS-Security protocol, which is coming with the .NET Framework "." and Visual Studio .NET ".". WS-Security is a part of GXA , the Global XML Web Services Architecture. GXA isnt a single protocol; its a scheme for building a whole family of protocols that can be used in many Web services applications. Some of the design principles for the GXA protocols include: XML-Based Data Models: The data within the GXA services is stored using XML InfoSets. Application Domain Neutrality: The GXA protocols are designed to be broadly useful, but extensible for specific application domains. Decentralization and Federation: GXA does not depend on central authorities to manage things; this makes these protocols more scalable. Modularity: GXA has a modular design, so you only need to learn the pieces that you want to use. The WS-Security protocol adds three security features to SOAP messages. First, it allows you to verify the identity of the sender of a message by adding a specification for digital tokens. Second, it lets you use digital signing to verify that a message was not altered in transit. Finally, it implements encryption, to ensure that no one can read the content of the message except the intended recipient. To learn more about GXA and WS-Security, start at http://msdn.microsoft.com/library/en-us/dngxa/html/gloxmlws500.asp. Secure Web Services with IIS and ASP.NET .NET Security Professional Skills Development 12-25 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Summary Web services allow you to build distributed applications that can access remote objects over the Internet. Web services use standardized protocols such as SOAP and WSDL to communicate across machines, platforms, and languages. You can disable particular protocols that are not necessary for your own Web services applications. Because Web services are hosted by ASP.NET, you can use IIS and ASP.NET security features for authentication and authorization. To have the security context from IIS authentication flow through to a Web service object, you must explicitly pass the authenticated credentials to the object. Web Services 12-26 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
(Review questions and answers on the following pages.) Secure Web Services with IIS and ASP.NET .NET Security Professional Skills Development 12-27 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Questions ". What are the benefits of using SOAP and WSDL as protocols for Web services? 2. How can you disable protocols such as HTTP GET, HTTP POST, and WSDL for a Web service? 3. Where should you implement authentication code for a Web service client written with Visual Studio .NET? 4. How can you limit the use of a Web service to particular users in your domain? 5. How can you implement authentication on the computer that is hosting a Web service?
Web Services 12-28 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Answers ". What are the benefits of using SOAP and WSDL as protocols for Web services? Using open protocols such as SOAP and WSDL with Web services allows these services to be used across machines, languages, and platforms. 2. How can you disable protocols such as HTTP GET, HTTP POST, and WSDL for a Web service? Edit the Machine.config file or the Web.config file to remove support for the protocols that you want to disable. 3. Where should you implement authentication code for a Web service client written with Visual Studio .NET? Client-side authentication code can be placed in the proxy class that is generated when you add a Web Reference to a project. 4. How can you limit the use of a Web service to particular users in your domain? You can add authorization tags to the Web.config file, or you can use the PrincipalPermission Attribute within the code of the Web service. 5. How can you implement authentication on the computer that is hosting a Web service? Authentication for Web services is handled by the authentication features built into IIS. Secure Web Services with IIS and ASP.NET .NET Security Professional Skills Development 12-29 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Lab 12: Web Services TIP: Because this lab includes code that you must type in, weve tried to make it simpler for you. Youll find all the code in Web Services.txt, in the same directory as the sample project. To avoid typing the code, you can copy/paste it from the text file instead. The ASP.NET Web projects associated with this lab are located in the following directories*: ! {inetpub\wwwroot}\SecurityNetLabs\WebServicesLab ! {inetpub\wwwroot}\SecurityNetLabs\WindChillService
*There is no lab completed project.
Lab 12: Web Services 12-30 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Lab 12 Overview In this lab youll learn how to build a Web service, and how to secure that Web service so that it cannot be used by unauthorized visitors. To complete this lab, youll need to work through two exercises: Build and Test a Web Service Secure the Web Service Each exercise includes an Objective section that describes the purpose of the exercise. You are encouraged to try to complete the exercise from the information given in the Objective section. If you require more information to complete the exercise, the Objective section is followed by detailed step-by- step instructions. Build and Test a Web Service .NET Security Professional Skills Development 12-31 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Build and Test a Web Service Objective In this exercise, youll work through the steps to build a Web service and to test it out. The Web service will allow the user to calculate the wind chill for a given temperature and wind velocity, using the standard equation from the National Weather Service:
Here WCT is the wind chill temperature, T is the air temperature in degrees Fahrenheit, and V is the wind velocity in miles per hour. Things to Consider How do you create a Web service? How do you create a client for the Web service? Step-by-Step Instructions ". Open the WebServicesLab.sln file. 2. View the code for the WindChill.asmx file in the WindChillService project. 3. In the WebService attribute, change the namespace:
4. Replace the commented sample code with this Web Method: Lab 12: Web Services 12-32 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
<WebMethod()> _ Public Function GetWindChill( _ ByVal T As Double, ByVal V As Double) As Double GetWindChill = 35.74 + (0.6215 * T) _ - (35.75 * (V ^ 0.16)) _ + (0.4275 * T * (V ^ 0.16)) End Function
5. Save and build the project. 6. Right-click on the References node in the WindChillClient project and select Add Web Reference. 7. In the Add Web Reference dialog box, enter the following URL in the Address box (without the line break):
8. Press ENTER to retrieve the details of the Web service, as shown in Figure "4. Build and Test a Web Service .NET Security Professional Skills Development 12-33 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Figure "4. Setting a Web reference to the WindChillService Web service. 9. Click the GetWindChill link. "0. On the test page, enter values for T and V and click the Invoke button to verify that the Web service is functioning. The results will be displayed in a browser window, as shown in Figure "5.
Figure "5. Verifying the Web service. "". Click the Add Reference button to add the Web reference to the client project. "2. Open the WindChill.vb form in code view. Lab 12: Web Services 12-34 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
"3. Add code to handle the buttons click event:
Private Sub btnGetWindChill_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnGetWindChill.Click
Dim wc As New localhost.WindChill() lblWindChill.Text = "Wind Chill Temperature: " & _ wc.GetWindChill(Double.Parse(txtTemperature.Text), _ Double.Parse(txtVelocity.Text)).ToString("##.#") End Sub
"4. Save the project and click F5 to run the solution. "5. Enter values for the temperature and wind speed and click the Get Wind Chill button. The form will display the calculated wind chill, as shown in Figure "6. Close the form.
Figure "6. Calculating the wind chill via a Web service. Secure the Web Service .NET Security Professional Skills Development 12-35 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
Secure the Web Service Objective In this exercise, youll secure the WindChillService Web service against unauthorized usage. To do this, youll take three actions: Block HTTP GET and HTTP POST access to the Web service. Authenticate users by supplying a specific set of credentials in the client code. Use a Principal Permission demand to authorize use of the Web service. Things to Consider How do you block HTTP GET and HTTP POST access to a Web service? How do you specify credentials for a Web service in the client code? How do you apply a Principal Permission demand to a Web service? Step-by-Step Instructions ". Open the Web.config file for the WindChillService Web service. 2. Add a new section to the file, directly after the <system.web> element:
3. Save the Web.config file. Lab 12: Web Services 12-36 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
4. Right-click on the Web References node in the WindChillClient project and select Add Web Reference. 5. In the Add Web Reference dialog box, enter the following URL in the Address box (without the line break) and press ENTER.
6. Click the GetWindChill link in the left-hand pane of the Add Web Reference dialog box. Youll see in Figure "7 that you can no longer test the Web service; this is one of the side effects of disabling HTTP POST access to the Web service.
Figure "7. You cant test the Web service if HTTP GET is disabled. 7. Click Cancel to close the page. 8. Select the WindChillClient project and click the Show All Files button in Solution Explorer. 9. Open the Reference.vb file, which youll find in the Web References section of the project under the Reference.map node. "0. Add an Imports statement at the top of the file:
Imports System.Net
Secure the Web Service .NET Security Professional Skills Development 12-37 Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
"". Modify the constructor of the proxy class as follows (be sure to substitute valid user credentials for username, password, and domain):
Public Sub New() MyBase.New() Me.Url = "http://localhost/SecurityNetLabs/WindChillService/WindChi ll.asmx" ' NOTE: Change the next line to use valid ' values for your Web server's domain Dim cred As New NetworkCredential( _ "username", "password", "domain") Dim objURI As New Uri(Me.Url) Dim cc As New CredentialCache() cc.Add(objURI, "NTLM", cred) Me.Credentials = cc Me.PreAuthenticate = True End Sub
"2. Edit the <authorization> element in the Web.config file for the OrderService Web service as follows. Substitute your own domain and username in the <allow> element, and deny all other users access in the <deny> element:
"3. Save the Web.config file. "4. Run the solution by clicking F5. Verify that you can still retrieve results from the Web service. This works because youve preauthenticated as a user who is authorized to use the service. "5. Close the client form. Edit the Web.config file to change the authorized user name. Dont change the name in the supplied credentials. Save the Web.config file. "6. Click F5 to run the solution. Enter temperature and wind speed figures and click the Get Wind Chill button. Youll receive a WebException due to the Lab 12: Web Services 12-38 .NET Security Professional Skills Development Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.
mismatch in credentials, which causes the Web service to return a 40" response, as shown in Figure "8.
Figure "8. An error caused by a credential mismatch. "7. Click Continue to close the session.