Microsoft SQL Server 2008 R2 Unleashed- P195 pdf

10 219 0
Microsoft SQL Server 2008 R2 Unleashed- P195 pdf

Đang tải... (xem toàn văn)

Thông tin tài liệu

ptg 1934 CHAPTER 48 SQL Server Web Services ALTER AUTHORIZATION ON ENDPOINT::EPT_SQL2008UnleashedExamples TO MyDomain\SomeOtherUser Next, the STATE keyword indicates the initial state of the endpoint. Much as in Windows services, the possible states are STOPPED, STARTED, and DISABLED. (For security’s sake, STOPPED is the default.) To change the state of any endpoint, you again invoke the ALTER ENDPOINT syntax. The following example stops the endpoint: ALTER ENDPOINT EPT_SQL2008UnleashedExamples STATE = STOPPED Again, don’t do this until you are done with the examples! The AS HTTP Keyword Group The AS HTTP statements describe the protocol, ports, virtual path, and TCP/IP bindings for the endpoint. This keyword group is of interest to security professionals because this is where you can implement IP restrictions, authentication, and other lockdown mechanisms. In the example shown in Listing 48.3, HTTP is the transport protocol. But you could just as easily use TCP if your application demands it: when creating a TCP endpoint, you specify AS TCP instead of AS HTTP. Then you add the following parameters: . LISTENER_PORT—Specifies an integer-valued port number on which the server listens for incoming requests. The default is 4022. . LISTENER_IP—Specifies an incoming IP address on which the TCP listener accepts connections. The default is the keyword ALL (that is, listening on all IP addresses). Next, you specify that the AUTHENTICATION method is INTEGRATED. Microsoft recommends INTEGRATED (which includes both KERBEROS and NTLM) and KERBEROS as the most secure ways of authenticating to endpoints, although they are not necessarily platform-indepen- dent ways. This approach is in contrast to using BASIC or DIGEST authentication. In case the endpoint consumer requires BASIC authentication, SQL Server requires that the HTTP port of the web service be secured via Secure Sockets Layer (SSL). NOTE Using BASIC authentication allows for the additional keyword DEFAULT_LOGON_DOMAIN to specify the domain under which users will authenticate. DIGEST authentication is also available, but only a domain-level account may be used in the AUTHORIZATION section for the endpoint to be successfully created. ptg 1935 Building Web Services 48 TIP The prerequisite of a domain-level account is also true for all other authentication methods ( KERBEROS, BASIC, INTEGRATED, and NTLM): SQL Server does not register the endpoint if authorization checks fail at DDL execution time. Using DIGEST allows for the additional keyword AUTH_REALM, whose string value represents the challenge hint required by this type of authentication. NOTE In contrast to SQLXML, there is no way for web anonymous users (such as IUSR_MACHINENAME) to access SQL Server 2008 endpoints. This is an uncommonly proactive security move for Microsoft, and database administrators will applaud it. Next, you specify the PATH (/opensql) to the web service. PATH is simply the part of the URL that follows the server and domain name portion of a URL (for example, http://ServerDomainName/PATH). Paths are sometimes also referred to as virtual names. Clients connecting to the HTTP endpoint thus access it via the URL http://ServerDomainName/opensql. This method of specifying the PATH is similar to the way virtual directories are used with IIS, and the reason is that IIS and SQL Server register their endpoints similarly with the HTTP API. When the web service is called by a client, the HTTP API responds by farming the request out to SQL Server. NOTE You cannot register a value for PATH that is already registered by SQL Server, IIS, or any other application that uses the HTTP API. If you attempt to do so, SQL Server raises the following error: The URL specified by endpoint ‘ENDPOINTNAME’ is already registered to receive requests or is reserved for use by another service. Next in the syntax, you specify the PORTS on which SQL Server listens for requests for this endpoint. The example in Listing 48.3 specifies both CLEAR (the unsecured standard HTTP port, which defaults to 80) as well as SSL (the standard SSL port, which defaults to 443). You can also specify nondefault numeric values for CLEAR_PORT and SSL_PORT, but this example simply restates the default for clarity. ptg 1936 CHAPTER 48 SQL Server Web Services Note that it is essential you do not use port numbers owned by other network services (such as email, telnet, and so on), although SQL Server may allow you to do so. Only one port can be specified each for CLEAR_PORT and SSL_PORT. In addition to specifying ports, you can restrict or grant endpoint access to specific IP addresses by using a combination of the keywords RESTRICT_IP and EXCEPT_IP. RESTRICT_IP defaults to NONE (that is, no IP addresses are restricted), but you can change this to ALL to prevent users from accessing the endpoint (which is useful during offline maintenance periods). For EXCEPT_IP, you can add specific client IP addresses in parenthe- ses. Here’s an example: CREATE ENDPOINT EPT_SQL2008UnleashedIPExample AUTHORIZATION [MyDomain\SQLWebServicesClient] STATE = STARTED AS HTTP ( AUTHENTICATION = (INTEGRATED), PATH = ‘/opensql2/’, PORTS = (CLEAR, SSL), CLEAR_PORT = 80, SSL_PORT = 443, SITE = ‘*’, COMPRESSION = ENABLED, RESTRICT_IP = ALL, EXCEPT_ID = 192.168.10.1 ) FOR SOAP ( WEBMETHOD ‘urn:www-samspublishing-com:examples’.’WM_GetEmployeeBasics2’ ( NAME = ‘AdventureWorks2008.dbo.GetEmployeeBasics’, SCHEMA = STANDARD, FORMAT = ALL_RESULTS ), WSDL = DEFAULT, BATCHES = DISABLED, SCHEMA = STANDARD, LOGIN_TYPE = WINDOWS, SESSION_TIMEOUT = 120, DATABASE = ‘AdventureWorks2008’, NAMESPACE = ‘urn:www-samspublishing-com:examples’, CHARACTER_SET = XML ); ptg 1937 Building Web Services 48 TIP It is assumed that for most endpoints, you want to implement some level of IP filtering. It is recommended that you use the modifiers described here to prevent broad access. Next, you use the SITE keyword to specify the hostname(s) used on the server hosting the endpoint. In this case, ’ *’ restates the default (that is, all hostnames reserved by the local machine), but you can use a specific host name (such as ’ hostname’) or all hostnames (that is, ’+’). This capability is useful (and necessary) when multiple host headers are in play for the same IP address. The NAMESPACE keyword indicates to clients that the web method originates from a specific organizational entity. This prevents confusion when comparing the XML generated by this web service with that of any other organization that might expose a web method of the same name on an endpoint of the same name (which is an entirely possible situation). TIP Specifying the company name in uniform resource name (URN) format is standard prac- tice for namespace naming. A URN differs from a uniform resource locator (URL) in that it specifies just the name of a resource, independent of its location. Using the URN is useful because the name of a resource is usually valid longer than the lifetime of any particular URL. COMPRESSION is an interesting optional keyword because, when specified, it tells SQL Server to decompress its incoming SOAP requests if they have been compressed using gzip; then, in turn, it tells SQL Server to use gzip on the outgoing responses. You might think that web services over SOAP are too slow for the average application because of the sheer byte count of SOAP XML documents. However, using gzip on an XML file usually results in a compression ratio of greater than 80%. When COMPRESSION is set to ENABLED, both the client and server must support gzip compres- sion for web service compression to work properly, although the web service can still process uncompressed requests with uncompressed responses even with the setting turned on. To enable compression on IIS 6 (on Windows 2003 Server, Standard Edition), you follow these steps: 1. Open the IIS Manager, expand the main tree, right-click the Web Sites node, and choose Properties. 2. When the Web Sites Properties dialog appears, click on the Service tab and check the Compress Application Files and Compress Static Files check boxes. ptg 1938 CHAPTER 48 SQL Server Web Services FIGURE 48.1 Enabling compression on IIS 6. 3. Add a web service extension for the .gzip file extension and edit the metabase appropriately, if necessary. The Web Sites Properties dialog box should look something like the one in Figure 48.1 when these steps are complete. The FOR SOAP Keyword Group The second major section of the DDL begins after the end parenthesis of the AS clause, with the FOR SOAP group, whose keywords appear in parentheses. First, you assign the namespaced-name ’urn:www-samspublishing- com:examples’.’WM_GetEmployeeBasics’ to WEBMETHOD. This name is specified in two parts to ensure its uniqueness: . A namespace as a string in URN format (followed by a period) . The string name of the web method NOTE In Listing 48.3, the naming convention WM_ is used simply to differentiate the web method from other database objects. Later in this chapter, you see how this convention makes objects easy to pick out in query results on the endpoint catalog views in the section “Using Catalog Views and System Stored Procedures.” The following keyword options are used inside the parenthetical group following WEBMETHOD: ptg 1939 Building Web Services 48 . NAME—The string value represents the SQL Server scalar-valued user-defined function (UDF) or stored procedure that will be executed via the web service. . SCHEMA—This keyword choice describes the quality of XML schema produced to describe the transmitted XML data. CAUTION The SCHEMA keyword occurs twice in the FOR SOAP group. This first occurrence of SCHEMA relates specifically to inline schema generation for the web method. It tells the compiler how to generate (or not generate) an XSD schema within the SOAP response envelope that describes the types used by this particular WEBMETHOD. These are the valid keyword values for SCHEMA: . NONE—Do not include web method–specific schema information in the SOAP response. . STANDARD—Generate a standard schema. . DEFAULT—Use the value of the SCHEMA keyword that is specified (somewhat confusingly, a second time) after the end of the WEBMETHOD clause. . FORMAT—This option specifies which kinds of objects are returned to the web method’s caller. Following are the valid keyword values for FORMAT: . ALL_RESULTS—Include two or more objects in the SOAP response, including the following: . The result set itself (in .NET, deserialized as DataSet; or, in the case of web methods that return XML, one or more sqlresultstream:SqlXml nodes deserialized as XmlElements) . A row count of the result set (in .NET, deserialized as a SqlRowCount object; or, in the case of XML results, a sqlresultstream:SqlRowCount node deserialized as an XmlElement) . A result code (in .NET, an integer; or, in the case of XML results, a sqlresultstream:SqlResultCode node deserialzed as an XmlElement) . Any SQL Server errors or warnings, if generated at runtime (in .NET, dese- rialized as SqlMessage objects) . ROWSETS_ONLY—Return just the result sets, if any. . NONE—Do not mark up the output data in SOAP-typed envelope data. NONE is an advanced setting and should be used with the following caveat: no output ptg 1940 CHAPTER 48 SQL Server Web Services parameters or UDFs are allowed with this option, and WSDL for the web method is not generated. . BATCHES—Setting this switch to ENABLED or DISABLED allows or disallows ad hoc T- SQL statements to be executed on the endpoint. This means that any number of SQL statements (with associated parameters) may be run via the special sqlbatch() web service proxy method, explained later in this chapter. TIP Although convenient, the BATCHES feature has some security implications because a wide range of T-SQL may be executed; thus, many administrators want it kept off. (It is disabled by default.) There are, however, some valid situations for using it, including .During the design and testing phases of a website .When implementing highly customized remote database administrative tools .For ad hoc-query–dependent features . LOGIN_TYPE—You use this setting to set the SQL Server Authentication mode for the endpoint to either MIXED (both Windows and SQL Server) or WINDOWS (the default). As with BASIC authentication, SSL is required to be both implemented on the server and specified after the PORTS keyword for the statement to compile. . WSDL—You use this setting to determine whether SQL Server will generate WSDL for methods on the endpoint. You specify DEFAULT to do so or NONE. When you require specific WSDL to be generated, you specify a string value corresponding to the name of the custom stored procedure that generates the home-grown WSDL. Here’s an example: WSDL ‘wsdl_generating_stored_procedure_name’ Note that for the C# web service client example later in this chapter to work, the value for WSDL must be DEFAULT. The reason is that the Visual Studio .NET IDE uses the generated WSDL to create web references as the basis for generating proxy classes used to call them. TIP The built-in system stored procedures that SQL Server uses to generate WSDL are sp_http_generate_wsdl_complex, sp_http_generate_wsdl_simple, sp_http_generate_wsdl_defaultcomplexorsimple, and sp_http_generate_wsdl_defaultsimpleorcomplex. You can test them by executing them with varying parameters to see how they work. For more information on generating custom WSDL, see the Books Online topic “Implementing Custom WSDL Support.” ptg 1941 Building Web Services 48 WSDL on SQL Server comes in two different flavors: the default and simple. To see an example of simple WSDL, try the following URL (after you create the sample endpoint by running the code in Listing 48.3): http[s]://ServerDomainName/opensql?wsdlsimple. . SESSIONS—You use this setting to specify whether SOAP sessions managed by SQL Server are ENABLED or DISABLED (the default). Managing SOAP sessions on the client side requires a fair amount of programming in an environment such as Visual Studio 2008 for successful implementation. Not all SOAP clients require sessions. . SESSION_TIMEOUT—You use this setting to specify how long (in seconds) before a SQL Server SOAP session times out. . DATABASE—You use this setting to specify the database (named with a string value) in whose context the web methods of this endpoint are executed. Note that the keyword DEFAULT is also an option. Using it tells SQL Server to execute the web methods in the context of the default database of the login accessing the endpoint. . SCHEMA—This is the second occurrence of this keyword in the CREATE ENDPOINT DDL. This time around, it applies to schema generation for all SOAP responses of all web methods on the endpoint, not merely of a particular web method. These are the possible values: . NONE—Do not generate an inline XML schema in the SOAP response. . STANDARD—Generate an inline schema. . CHARACTER_SET—The XML specification specifies a set of characters that are invalid in element and attribute values; they are <, >, ”, ’, and &. The reason for this is that XML parsers would have a hard time figuring out whether these characters represent markup or text values because they are used to delimit XML information items. For example, they are used in element tagging (for example, <element>), attribute naming (for example, attribute=”value”), and entity naming (for example, &entity;). The two keyword values for CHARACTER_SET treat these and other special characters (when found in markup) in distinct ways: . XML—If a SOAP response is sent and the special XML characters are not escaped into their valid entity equivalents ( &lt;, &gt;, &quot;, &apos;, and &amp;) the response generates an error. This is the default. . SQL—Any invalid XML characters are transformed into their respective entity representations (a process called entitization) before response transmission. Other special characters are not permitted in the names of XML attributes or elements (known formally as qualifying names, or QNames) but may nevertheless end up in XML documents. SQL Server automatically escapes them by taking their Unicode hexadecimal values and preceding them with the string #x[4-digit hex value] . The asterisk (*) character, for example, would be converted to the character string #x002A. ptg 1942 CHAPTER 48 SQL Server Web Services NOTE This character conversion may not be cross-platform compatible because not all parsers approve of it, but it is far better to convert characters than have your SQL connection closed due to an XML parsing error. One of the ways that such special character entitization may occur is when you use SQL column (or other object) aliases that, though legally named in T-SQL, are not valid QNames (for example, SELECT ColumnName AS ‘*’ FROM TableName FOR XML RAW). . MAX_SOAP_HEADERS_SIZE—Optionally, you can set the maximum size of the header section of each transmitted SOAP envelope. (The default is 8KB.) Transmitting a larg- er header than specified in this setting thus causes a server error. As you can see, the CREATE ENDPOINT syntax offers a feast of options. Thankfully, it is easy to choose the ones you need, depending on your application’s requirements. Examples: A C# Client Application After you execute the DDL in Listing 48.3, you can call your SOAP endpoint. In the following sections, you learn how to call the endpoint’s web methods using a simple C# client application. If you do not want to try your hand at C#, you can skip to the next section, but working through the following examples is recommended so that you have a complete understand- ing of both sides of the web service pattern. Example 1: Running a Web Method Bound to a Stored Procedure from C# Using Visual Studio 2008, create a new web application or website and name it SQLWebServicesClient. Next, add a web reference to the SQL Server web service created in Listing 48.3. To do this, you right-click the project name in the Server Explorer window and select Add Web Reference. In the dialog that appears, you type the following in the URL text box, replacing ServerDomainName with the server name of your SQL Server instance: http[s]://ServerDomainName/opensql?wsdl Next, you click the green Go arrow button. You may be required to Windows-authenticate to the machine hosting the SQL web service. Be sure to use an account that has a match- ing SQL Server login. After you do so, the Add Web Reference dialog should look some- thing like the one shown in Figure 48.2. Notice in the dialog that the browser box (directly below the URL text box) contains the endpoint name you used in the DDL ( EPT_SQL2008UnleashedExamples), located on top and in quotation marks. It is followed by the name of the web method you added ( WM_GetEmployeeBasics). ptg 1943 Examples: A C# Client Application 48 FIGURE 48.2 Adding a web reference by using Visual Studio 2008. Also note how on the right side of the dialog, under the heading Web Services Found at This URL, the value you specified for PATH (opensql) is displayed. You need to type opensql in the Web Reference Name text box and click the Add Reference button. Next, you open the automatically created default.aspx file in design mode and add GridView, TextBox, Label, and Button controls to the form. Using the Properties dialog, you should name the label lblResults, the text box txtEmployeeId, the grid view gvData, and the button btnGetValue. Next, you need to double-click btnGetValue. The IDE exits design mode and enters the code region of the C# partial class default.aspx.cs. The following empty event handler is autogenerated: protected void btnGetValue_Click(object sender, EventArgs e) {} At the top of this file, you type the following C# using statement: using SQLWebServicesClient.opensql; This statement tells the compiler to import the names culled from the WSDL of the web service into this C# class. The namespace contains a C# stub class with the same name as the endpoint ( EPT_SQL2008UnleashedExamples); the .NET runtime (CLR) uses this name to call the SQL Server HTTP endpoint. At this point, you need to type the code in Listing 48.4 inside the empty body of btnGetValue_Click(). . out to SQL Server. NOTE You cannot register a value for PATH that is already registered by SQL Server, IIS, or any other application that uses the HTTP API. If you attempt to do so, SQL Server. authentication. NOTE In contrast to SQLXML, there is no way for web anonymous users (such as IUSR_MACHINENAME) to access SQL Server 2008 endpoints. This is an uncommonly proactive security move for Microsoft, and. sqlresultstream:SqlXml nodes deserialized as XmlElements) . A row count of the result set (in .NET, deserialized as a SqlRowCount object; or, in the case of XML results, a sqlresultstream:SqlRowCount node

Ngày đăng: 05/07/2014, 02:20

Từ khóa liên quan

Mục lục

  • Table of Contents

  • Introduction

  • Part I: Welcome to Microsoft SQL Server

    • 1 SQL Server 2008 Overview

      • SQL Server Components and Features

      • SQL Server 2008 R2 Editions

      • SQL Server Licensing Models

      • Summary

      • 2 What’s New in SQL Server 2008

        • New SQL Server 2008 Features

        • SQL Server 2008 Enhancements

        • Summary

        • 3 Examples of SQL Server Implementations

          • Application Terms

          • OLTP Application Examples

          • DSS Application Examples

          • Summary

          • Part II: SQL Server Tools and Utilities

            • 4 SQL Server Management Studio

              • What’s New in SSMS

              • The Integrated Environment

              • Administration Tools

              • Development Tools

              • Summary

              • 5 SQL Server Command-Line Utilities

                • What’s New in SQL Server Command-Line Utilities

                • The sqlcmd Command-Line Utility

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan