1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft SQL Server 2008 R2 Unleashed- P195 pdf

10 219 0
Tài liệu đã được kiểm tra trùng lặp

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 278,72 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

This method of specifying the PATHis 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

Trang 1

TO MyDomain\SomeOtherUser

Next, the STATEkeyword indicates the initial state of the endpoint

Much as in Windows services, the possible states are STOPPED,STARTED, and DISABLED (For

security’s sake, STOPPEDis the default.)

To change the state of any endpoint, you again invoke the ALTER ENDPOINTsyntax 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

TheAS HTTPstatements 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

specifyAS TCPinstead 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 AUTHENTICATIONmethod is INTEGRATED Microsoft recommends

INTEGRATED(which includes both KERBEROSandNTLM) and KERBEROSas the most secure

ways of authenticating to endpoints, although they are not necessarily

platform-indepen-dent ways This approach is in contrast to using BASICorDIGESTauthentication In case

the endpoint consumer requires BASICauthentication, SQL Server requires that the HTTP

port of the web service be secured via Secure Sockets Layer (SSL)

NOTE

UsingBASICauthentication allows for the additional keyword DEFAULT_LOGON_DOMAIN

to specify the domain under which users will authenticate

DIGESTauthentication is also available, but only a domain-level account may be used in

theAUTHORIZATIONsection for the endpoint to be successfully created

Trang 2

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

UsingDIGESTallows 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 PATHis 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 PATHis 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 PATHthat 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 PORTSon 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_PORTandSSL_PORT, but this

example simply restates the default for clarity

Trang 3

(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_PORTandSSL_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_IPandEXCEPT_IP

RESTRICT_IPdefaults to NONE(that is, no IP addresses are restricted), but you can change

this to ALLto 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

);

Trang 4

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 SITEkeyword 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

TheNAMESPACEkeyword 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

COMPRESSIONis 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%

WhenCOMPRESSIONis set toENABLED, both the client and server must support gzip

compres-sion for web service comprescompres-sion 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 Sitesnode, 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

Trang 5

FIGURE 48.1 Enabling compression on IIS 6

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 ASclause,

with the FOR SOAPgroup, whose keywords appear in parentheses

First, you assign the namespaced-name

’urn:www-samspublishing-com:examples’.’WM_GetEmployeeBasics’toWEBMETHOD 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 followingWEBMETHOD:

Trang 6

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

TheSCHEMAkeyword occurs twice in the FOR SOAPgroup This first occurrence of

SCHEMArelates 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 theSCHEMAkeyword that is specified (somewhat

confusingly, a second time) after the end of theWEBMETHODclause

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:SqlResultCodenode deserialzed as an XmlElement)

Any SQL Server errors or warnings, if generated at runtime (in NET,

dese-rialized as SqlMessageobjects)

ROWSETS_ONLY—Return just the result sets, if any

NONE—Do not mark up the output data in SOAP-typed envelope data NONEis

an advanced setting and should be used with the following caveat: no output

Trang 7

method is not generated

BATCHES—Setting this switch to ENABLEDorDISABLEDallows or disallows ad hoc

T-SQL statements to be executed on the endpoint This means that any number of T-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 BATCHESfeature 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 BASICauthentication, SSL is required to be both implemented on the server

and specified after the PORTSkeyword for the statement to compile

WSDL—You use this setting to determine whether SQL Server will generate WSDL for

methods on the endpoint You specifyDEFAULTto do so orNONE 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.”

Trang 8

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 ENABLEDorDISABLED(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

keywordDEFAULTis 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 ENDPOINTDDL

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_SETtreat 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

Trang 9

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 headlarg-er than specified in this setting thus causes a slarg-ervlarg-er larg-error

As you can see, the CREATE ENDPOINTsyntax 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)

Trang 10

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

opensqlin the Web Reference Name text box and click the Add Reference button Next,

you open the automatically created default.aspxfile in design mode and add GridView,

TextBox,Label, and Buttoncontrols to the form Using the Properties dialog, you should

name the label lblResults, the text box txtEmployeeId, the grid view gvData, and the

buttonbtnGetValue

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# usingstatement:

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()

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

TỪ KHÓA LIÊN QUAN