Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
175
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 11: Internet Access

29

 

 

 

Web Proxy

Topic Objective

To show how to use a Web proxy to communicate with the Internet.

Lead-in

If your Web site uses a proxy to provide access to the Internet, you must configure a proxy instance to enable your application to communicate with the Web proxy.

!Global Proxy for All Web Requests

"Proxy named webproxy using port 80

WebProxy proxyObject = new WebProxy( WebProxy proxyObject = new WebProxy(

"http://webproxy:80/");

"http://webproxy:80/"); GlobalProxySelection.Select = proxyObject; GlobalProxySelection.Select = proxyObject;

! Overriding the Global Proxy Setting

" Request uses proxy named alternateproxy and port 80

WebRequest req = WebRequest.Create( WebRequest req = WebRequest.Create(

"http://www.contoso.com/");

"http://www.contoso.com/"); req.Proxy = new WebProxy( req.Proxy = new WebProxy(

"http://alternateproxy:80/");

"http://alternateproxy:80/");

*****************************ILLEGAL FOR NON-TRAINER USE******************************

If your Web site uses a proxy to provide access to the Internet, you must configure a proxy instance to enable your application to communicate with the Web proxy.

Creating a Global Proxy Instance

The following example shows how to create a global proxy instance that enables any WebRequest to use a proxy to communicate with the Internet. The example assumes that the proxy server is named webproxy and that it communicates on port 80, the standard HTTP port.

WebProxy proxyObject = new WebProxy("http://webproxy:80/");

GlobalProxySelection.Select = proxyObject;

Overriding the Global Proxy Selection

You can override the global proxy selection by assigning an instance that implements the IWebProxy interface to the Proxy property of the WebRequest. The following code sends a WebRequest to http://www.contoso.com. The WebRequest overrides the global proxy selection with a proxy server that is named alternateproxy on port 80.

WebRequest req = WebRequest.Create("http://www.contoso.com/"); req.Proxy = new WebProxy("http://alternateproxy:80/");

30

Module 11: Internet Access

Secure Sockets Layer

Topic Objective

To explain how SSL is used for secure network communication.

Lead-in

The WebRequest and WebResponse classes use SSL automatically.

! SSL Is Used Automatically If the URI Begins with https

String MyURI = "https://www.contoso.com/";

String MyURI = "https://www.contoso.com/";

WebRequest wReq = WebRequest.Create(MyURI);

WebRequest wReq = WebRequest.Create(MyURI);

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The WebRequest and WebResponse classes use SSL automatically. The WebRequest object decides to use SSL on the basis of the URI that it is assigned. If the URI begins with https:, SSL is used. If the URI begins with http:, SSL is not used.

The following example illustrates the use of SSL:

String MyURI = "https://www.contoso.com/";

WebRequest wReq = WebRequest.Create(MyURI);

Module 11: Internet Access

31

 

 

 

Internet Authentication

Topic Objective

To introduce the client authentication mechanisms that are supported by the

System.Net classes.

Lead-in

The System.Net classes support a variety of client authentication mechanisms, including the standard Internet authentication methods: basic, digest, negotiate, NTLM, and Kerberos authentication, and custom methods that you can create.

!.NET Supports Various Kinds of Authentication

"Basic, digest, negotiate, NTLM, and Kerberos authentication

"Users can also create their own authentication

!Credentials Stored in Classes

"NetworkCredential – for a single Internet resource

"CredentialCache – for multiple Internet resources

!Authentication Managed by the AuthenticationManager

!Some Schemes Allow Pre-Authentication to Save Time

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The System.Net classes support a variety of client authentication mechanisms, including the standard Internet authentication methods: basic, digest, negotiate, NTLM, and Kerberos authentication, and custom methods that you can create.

Classes and Interfaces Used for Authentication

Authentication credentials are stored in the NetworkCredential and

CredentialCache classes, which implement the ICredentialLookup interface.

When one of these classes is queried for credentials, it returns an instance of the

NetworkCredential class.

The AuthenticationManager class manages the authentication process, while an authentication module class that implements the IAuthenticationModule interface performs the actual authentication process. You must register a custom authentication module with the AuthenticationManager before it can be used. Modules for the basic, digest, negotiate, NTLM, and Kerberos authentication methods are registered by default.

The NetworkCredential Class

The NetworkCredential class stores a set of credentials, which is associated with a single Internet resource and that is identified by a URI, and returns them in response to any call to the GetCredential method. The NetworkCredential class is typically used by applications that access a limited number of Internet resources or by applications that use the same set of credentials in all cases.

The CredentialCache Class

The CredentialCache class stores a collection of credentials for various Internet resources. When the GetCredential method is called, CredentialCache returns the proper set of credentials, as determined by the URI of the Internet resource and the requested authentication scheme. Because the CredentialCache class stores all of the credentials and provides them as requested, applications that use a variety of Internet resources with different authentication schemes benefit from using the CredentialCache class.

32

Module 11: Internet Access

The Authentication Process

When an Internet resource requests authentication, the

WebRequest.GetResponse method sends the WebRequest and the request for credentials to the AuthenticationManager. The request is then authenticated according to the following procedure:

1.The AuthenticationManager calls the Authenticate method on each of the registered authentication modules in the order that they were registered.

2.The AuthenticationManager uses the first module that does not return null to carry out the authentication process.

The details of the process vary depending on the type of authentication module involved.

3.When the authentication process is complete, the authentication module returns an Authorization instance to the WebRequest that contains the information that is needed to access the Internet resource.

Some authentication schemes can authenticate a user without first making a request for a resource. An application can save time by pre-authenticating the user with the resource, thus eliminating at least one roundtrip to the server.

Alternatively, the application can perform authentication during program startup to be more responsive to the user later. Authentication schemes that can use pre-authentication set the CanPreAuthenticate property to true.

Basic and Digest Authentication

The System.Net implementation of basic and digest authentication complies with RFC2617, “HTTP Authentication: Basic and Digest Authentication,” which is available on the World Wide Web Consortium (W3C) Web site at http://www.w3c.org.

To use basic and digest authentication, an application must provide a user name and password in the Credentials property of the WebRequest object that it uses to request data from the Internet, as shown in the following example:

Caution String literals in an application are stored and transported as clear text. Therefore, you should avoid putting sensitive information such as passwords in string literals.

//variables named username and password

//of type string have been previously assigned String MyURI = "http://www.contoso.com/"; WebRequest wReq = WebRequest.Create(MyURI); wReq.Credentials = new NetworkCredential(

username, password);

Module 11: Internet Access

33

 

 

 

NTLM and Kerberos Authentication

Default NTLM authentication and Kerberos authentication use the Microsoft Windows NT® user credentials that are associated with the calling application to attempt authentication with the server to pass the username, password, and domain to the host, as in the following example:

//variables named username, password, and domain

//of type string have been previously assigned String MyURI = "http://www.contoso.com/"; WebRequest wReq = WebRequest.Create(MyURI); wReq.Credentials =

new NetworkCredential(username, password, domain);

Applications that need to connect to Internet services by using the credentials of the application user can do so with the user’s default credentials, as in the following example:

String MyURI = "http://www.contoso.com/";

WebRequest wReq = WebRequest.Create(MyURI);

wReq.Credentials = CredentialCache.DefaultCredentials;

The negotiate authentication module determines whether the remote server is using NTLM or Kerberos authentication and sends the appropriate response.

Note NTLM authentication does not work through a proxy server.

Passport Authentication

Passport authentication is a centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites. This benefits the user because it is no longer necessary to log on to access new protected resources or sites. If you want your site to be compatible with Passport authentication and authorization, this is the provider you should use. For more information, see the Passport documentation located at http://www.passport.com/business.

34

Module 11: Internet Access

Permissions

Topic Objective

To explain which permission classes best suit which application types.

Lead-in

The WebPermissions and

SocketPermissions classes provide Internet security for applications that use System.Net.

!WebPermissions

"Controls an application's right to request data from a URI or to serve a URI to the Internet

!SocketPermissions

"Controls an application's right to accept data on a local port or to contact applications

!Choose Permission Class Based on Application Use

"WebRequest and its descendents use WebPermissions

"Socket-level access uses SocketPermissions

!Both Classes Support Two Kinds of Permissions

"Accept – application can answer an incoming connection

"Connect – application can initiate a connection

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The WebPermissions and SocketPermissions classes provide Internet security for applications that use System.Net. The WebPermissions class controls an application’s right to request data from a URI or to serve a URI to the Internet. The SocketPermissions class controls an application’s right to accept data on a local port or to contact applications through a transport protocol at another address that is based on the host, port number, and transport protocol.

You should choose the permission class on the basis of your application type. Applications that use WebRequest and its descendents should use the WebPermissions class to manage permissions. Applications that use socket-level access should use the SocketPermissions class to manage permissions.

WebPermissions and SocketPermissions define two permissions: accept and connect. Accept grants the application the right to answer an incoming connection from another party. Connect grants the application the right to initiate a connection to another party.

For WebPermissions, accept means that an application can export a particular URI anywhere on the Internet. Connect means that an application can access that URI, whether it is remote or local.

For SocketPermissions, accept means that an application can accept incoming connections on a local transport address. Connect means that an application can connect to a remote, or potentially local, transport address.

Module 11: Internet Access

35

 

 

 

Best Practices

Topic Objective

To introduce best practices that will help students use the System.Net classes more effectively.

Lead-in

The following recommendations will help you use the classes that are contained in System.Net more effectively.

!When Possible, Use WebRequest and WebResponse, Instead of Protocol-Specific Subclasses

!For Better Performance, Use Asynchronous Methods

!Tune Performance by Adjusting the Number of Connections

"ConnectionLimit property in the ServicePoint instance

!When Possible, Use TcpClient or UdpClient, Instead of Writing Directly to a Socket

!Use the CredentialCache Class If Credentials Are Required

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The following recommendations will help you use the classes that are contained in System.Net more effectively:

!Whenever possible, use WebRequest and WebResponse, instead of typecasting to descendent classes.

Applications that use WebRequest and WebResponse can take advantage of new Internet protocols without extensive code changes.

!When writing ASP.NET applications that run on a server that uses the System.Net classes, it is often better, from a performance standpoint, to use the asynchronous methods for GetResponse and GetResponseStream.

!Set the ConnectionLimit property in the ServicePoint instance for your application.

The number of connections opened to an Internet resource can have a significant effect on network performance and throughput. By default, System.Net uses two connections per application for each host. Setting the ConnectionLimit property in the ServicePoint instance for your application can increase this number.

!When writing socket-level protocols, try to use the TcpClient or UdpClient classes, instead of writing directly to a socket.

The TcpClient and UdpClient classes encapsulate the creation of TCP and UDP sockets without requiring you to handle the details of the connection.

!When accessing sites that require credentials, use the CredentialCache class to create a cache of credentials, rather than supplying them with every request.

The CredentialCache class will search the cache to find the appropriate credential to present with a request, thus relieving you of the responsibility of creating and presenting credentials based on the URI.

36

Module 11: Internet Access

Lab 11: Creating a DateTime Client/Server Application

Topic Objective

To introduce the lab.

Lead-in

In this lab, you will create a client application that uses the System.Net.Sockets

.TcpClient class to connect to and obtain date and time information from a server.

You will also create a server application that uses the

System.Net.Sockets

.TcpListener class to accept requests from and provide date and time information to clients.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Objectives

After completing this lab, you will be able to:

!Create a client application that uses the System.Net.Sockets.TcpClient class to connect to and obtain date and time information from a server.

!Create a server application that uses the System.Net.Sockets.TcpListener class to accept requests from and provide date and time information to clients.

Lab Setup

Only solution files are associated with this lab. The solution files for this lab are in the folder <install folder>\Labs\Lab11\Solution.

Scenario

In this lab, you will create two Microsoft Visual Studio® .NET console applications: DateTimeClient and DateTimeServer. The DateTimeClient application will make a TCP connection to the DateTimeServer application and obtain a stream that contains date and time information. The DateTimeClient will read the stream and convert the stream’s ASCII data into a string that is then output to the console.

Estimated time to complete this lab: 45 minutes

Module 11: Internet Access

37

 

 

 

Exercise 1

Creating the DateTime Server

In this exercise, you will create a server application that will provide date and time information to clients through TCP.

! Create the server application

1.In Visual Studio .NET, create a new C# console application project named

DateTimeServer in <install folder>\Labs\Lab11.

2.Rename the starting C# source file Datetimeserver.cs.

3.Add the following using statements:

using System.Net;

using System.Net.Sockets; using System.Text;

4.Rename the wizard generated Class1 to Server.

5.Modify the Main method in the following steps.

6.In the try section of a try/catch block:

a.Instantiate a TcpListener object to listen on port 14.

b.Start the TcpListener object.

c.Write out the following message to the console:

Waiting for clients to connect

Press Ctrl+c to Quit...

d.Enter an infinite loop that will:

i.Accept TCP client connections using the AcceptSocket method.

ii.Call a DateTime method to get the current date and time.

iii.Create a string that consists of the short version of the date, followed by the long version of the time.

iv.Convert the string to an ASCII-encoded byte array.

v.Send this byte array to the TCP client.

vi.Close the socket.

vii.Write out to the console a message that contains the string that was just sent.

7.In the catch section of the try/catch block:

Catch any exceptions of type SocketException and if the exception’s ErrorCode property has a value of 10048, then write to the console a message that states “Connection to this port failed. There is another server is listening on this port.”

8.Build the server application.

38

Module 11: Internet Access

Exercise 2

Creating the DateTime Client

In this exercise, you will create a client application. The client application takes as its runtime argument the name of the computer on which the server is running. The client connects to the server to obtain date and time information through TCP. The client then displays the date and time information on the console.

!Create the client application

1.In Visual Studio .NET, create a new C# console application project named

DateTimeClient in <install folder>\Labs\Lab11.

2.Rename the starting C# source file Datetimeclient.cs.

3.Add the following using statements:

using System.Net;

using System.Net.Sockets; using System.IO;

using System.Text;

4.Rename the wizard generated Class1 to Client.

5.Make the static Main method capable of handling runtime-supplied arguments.

6.In the Main method, add code to:

a.Create a TcpClient object.

b.Create a byte array object of size 32 bytes.

c.Check the number of runtime arguments. If the number of arguments is not one, print out an error message to the console, and exit. The message should state:

Please specify a server name in the command line

d.In a try/catch block, verify that the named server computer exists by calling the GetHostByName method of the Dns class. Catch any SocketException exceptions and write out to a console window the message “Cannot find server: ”, followed by the name of the server and the exception’s data. Then exit the application.

e.Connect to the named server using port 14.

f.Declare a variable of type Stream.

g.In a try/catch block, get the stream and assign it to the variable declared in the preceding step. Catch any InvalidOperationException exceptions and write out to a console window the message “Cannot connect to server ”, followed by the server’s name, and then exit the application.

h.Read all of the bytes in the stream into the byte array that you created in step 6b, and store the number of bytes that are read in an integer.

i.Convert the ASCII-encoded byte array into a string.

j.Write out to a console window a message that states the number of bytes received and the current date and time string retrieved from the server.

Соседние файлы в папке c#