■ Integrated Windows authentication This authentication is based on theconsumer having a Windows account that can be used for authentication.The strength of integrated Windows authentica
Trang 1Security and Unmanaged Code
CERTIFICATION OBJECTIVES
8.01 Implement Security 8.02 Access Unmanaged code
✓ Two-Minute Drill
Q&A Self Test
Trang 2In this chapter, you will learn about two topics: security for the Windows services, NET
Remoting objects, and XML Web Services and how to access legacy COM+ components
The security implementation will cover how to configure and use the differentsecurity mechanisms available through the NET Framework, and how to integratethe Windows authentication systems as well as the authorization needed to accessresources
A large number of existing COM and COM+ applications are in use today—
it will take a long time to move beyond the use of them in all but total rewritesituations You will look at how to make use of these components from a VisualBasic NET application
CERTIFICATION OBJECTIVE 8.01
Implement Security
You need to consider security for XML web services just as you do for any othersoftware product on a network As with other software products, there are threeaspects of security that you must consider: authentication, authorization, andsecure communication
Authentication
Authentication is the process of verifying that the client is truly who he or she claims
to be—this is done by collecting credentials (name and password) from the user
The credentials are validated against an authority like a database—if the credentialsare valid, the client is an authenticated identity
The authorization configuration is performed on IIS because IIS is the servicethat the consumer will interact with to get access to an XML web service Internet
Trang 3that is widely supported by browsers It transmits the security credentials
in clear text, resulting in a possible security breach unless the transmissionchannel is encrypted using Secure Sockets Layer (SSL)
■ Digest authentication The W3C has introduced digest authentication as areplacement for the basic authentication method In digest authentication,
a binary hash is built from the name, password, requested resource, HTTPmethod, and some random values generated from the server
To generate a hash, the browser applies an algorithm that is consideredone-way, meaning that there is no known way of getting back to the cleartext from the binary hash This hash is then sent to the IIS server, whichverifies that the hash is the same as it received when performing the samehash calculation on the user information as stored in the active directory
Digest authentication is supported starting in HTTP 1.1
■ Integrated Windows authentication This authentication is based on theconsumer having a Windows account that can be used for authentication.The strength of integrated Windows authentication is that the username andpassword are not sent across the network Rather, a hash of the credentials isused In addition, the method can make use of the Kerberos V5 protocol totake advantage of the secret-key cryptography provided in Active Directoryand Kerberos V5 The biggest problem with integrated Windows authentication
is that the server and the client must have network communication overTCP/IP ports for the authentication—these ports are normally never leftopen on any devices that are used on the Internet because of the risk ofintrusion into the system from Internet hackers
You can also use custom SOAP headers, to add your own authenticationmechanism instead of using the built-in solutions An XML web service consumercan add credentials to the SOAP header that are then retrieved by the XML webservice, which can use the credentials to authenticate the consumer For a refresher
on SOAP, see Appendix D
IIS Authentication
In order to configure authentication for an XML web service, you need to configureIIS through the Internet Services Manager To start the Internet Services Manager,
Trang 4select Start | Settings | Control Panel | Administrative Tools | Internet ServicesManager The program is shown in the following illustration.
Remember that the authentication method for Windows authentication
is set in IIS.
In the Tree view, expand first the server and then the Default Web Site; you willsee several entries, as shown in Figure 8-1
Select the web site you want to configure, right-click it, and select Properties
This will open the Default Web Site properties dialog box Click the DirectorySecurity tab as shown in Figure 8-2
Security settings are configured under the Anonymous Access And AuthorizationControl section Click Edit to open the Authentication Methods dialog box shown
in the following illustration
Trang 5You can configure authentication in this dialog box The default setting is thatanonymous access is permitted You can change the anonymous authenticationconfiguration with the proxy account in the Anonymous User Account dialog box,
Trang 6brought up when you click Edit in the Anonymous Access section The proxyaccount must be given the most restrictive access to the site possible.
FIGURE 8-2
The Properties
dialog box
Trang 7If you configure Digest Authentication For Windows Domain Servers, thedomain controls must have a reversible encrypted (clear-text) copy of the account’spassword to be used when comparing against the hash the consumer sends in.
You will be requested to agree to the clear-text passwords when you select digestauthentication
If you configure integrated Windows authentication, the user will not beprompted for credentials unless the integrated Windows authentication fails
Integrated Windows authentication cannot pass a firewall unless the administrator opens additional ports It is highly unlikely that the administrator will do so because of the security risk involved.
Once the IIS configuration is complete, the XML web service must be configured
to use the required authentication This is done by editing the Web.config file that
is located in the root directory for the XML web service This file is also called theapplication configuration file To enable the Windows-based authentication method(basic, digest, or integrated Windows) that was configured with IIS, add the following
to the Web.config file:
To access the user credentials programmatically, you can use the Context object
as in this demo web method from Visual Studio NET:
<WebMethod()> _ Public Function HelloWorld() As String return "Hello World " + Context.User.Identity.Name
Trang 8The result of this web method is shown here:
When you consume an XML web service by using the wsdl tool or by adding
a web reference in Visual Studio NET, the proxy class will inherit from theSoapHttpClientProtocolclass Through this class, you have access to theCredentialsproperty that is used to read or set security credentials In order
to control the authentication process, you can use the NetworkCredentialclass as shown in the following code segment:
' instantiate the XML Web Service proxy Dim ws As WService = New WService() ' get a NetworkCredential object Dim cred As ICredentials
cred = New NetworkCredential("Ken", "password", "nop.com") ' configure the client credentials
ws.Credentials = cred Dim s As String Try
s = ws.HelloWorld() Catch
Console.WriteLine("Authentication Failed!") End Try
Use theNetworkCredentialclass to pass the authentication when calling
an XML web service.
Trang 9EXERCISE 8-1
Using Network Credentials
In this exercise, you will build an XML web service and configure the authenticationfor it You will also learn about how to create authentication accounts for the localserver
The second part of this exercise deals with the consumer of the web service, andhow to use the NetworkCredential class to send authentication information
to an XML Web Service
1 Create a new Visual Basic NET project based on the ASP.NET Web Service
template Name the project HelloSecure.
2 Open the code module and change the namespace of the Web service from
http://temuri.org to http://secure.ws.
Trang 103 Change the name of the class to SHello.
<WebService(Namespace:="http://secure.ws/")> _ Public Class SHello
Inherits System.Web.Services.WebService
End Class
4 Implement a web method named HelloWorld() that returns a string
<WebMethod()> Public Function HelloWorld() As String
6 Save and build the Web Service
7 To test the web service, run the XML Web Service help application bypressingF5 The result of running the HelloWorld() web methodshould look like this:
Trang 11change that to Windows integrated authentication, and the next few stepsshow how you do that.
8 Open the Internet Services Manager console from Control Panel |Administrative Tools
9 Expand the localhost server
10 Expand the Default Web Site
11 Select the HelloSecure web site
12 Right-click the HelloSecure web site, and select Properties from the contextmenu This will open the HelloSecurity properties dialog
Trang 1213 Select the Directory Security tab in the dialog.
14 Click Edit in the Anonymous Access And Authentication Control section
This will open the Authentication Method dialog
15 Clear the check box next to Anonymous access
Trang 1316 Make sure that the check box next to Integrated Windows Authentication ischecked as shown here:
17 Click OK to close the Authentication Method dialog
18 Click OK to close the HelloSecure properties dialog
19 Close the Internet Services Management console To test that the securitysettings are in effect, you need to run the HelloSecure web service again
20 Switch to the HelloSecure project If you closed Visual Studio NET earlier,you will need to start it first
Trang 1421 Execute the HelloSecure web service by pressingF5.
22 Invoke the HelloWorld() web method The result should be similar tothis image, apart from the username:
The addition of the security information indicates in this case that user ken from the NOPCOMP domain is the one that is currently authenticated to the web
service
The next step is to build a client that allows the user to select the login informationneeded—you will build a login form that uses the HelloSecure web service
EXERCISE 8-2
Building a Security Client
For this exercise, you will build a Windows Form that will ask the user for logincredentials You will the call the HelloSecure web service and use the returninformation to determine if the credentials you authenticated were valid
1 Create a new Visual Basic NET project based on the Windows Applicationtemplate Name the project HelloTest
Trang 152 When the project is built, add two TextBox controls to the form Change the
name of the first to txtUserName and the second to txtPassword.
3 Position the txtUserName control and txtPassWord controls centered
in the form
4 Change the PasswordCharacter property of txtPassword to *
5 Position a Button control directly under the txtPassword control
6 Rename the Button control to btnHello.
7 Change the Text property of the btnHello control to "Click Me!"
8 Position a Label control directly under btnHello; size the Label control tospan the form
9 Change the TextAlign property to MiddleCenter
10 Clear the Text property of the Label control
Trang 1611 Change the name of the Label control to lblHello The resulting form should
look like this:
In order to be able to use the XML web service, you will need to add a webreference to the web service Steps 12–16 show how you do that
12 Select Add Web Reference from the Project menu to open the Add WebReference dialog
Trang 1713 In the Address field, enter the URL of the HelloSecure XML web service youbuilt in Exercise 8-1 (http://localhost/HelloSecure/Service1.asmx).
14 Press theENTERkey, or click the Enter button The result is that the webservice is shown in the Add Web Reference dialog
15 Click Add Reference to complete the action
16 Expand the Web Reference tree in the Solution Explorer to ensure that theweb service has been added
17 Open the code editor and add an import statement in the first line forSystem.Net to give access to the security classes
Imports System.Net
18 Add an event handler for the btnHello control's click event
Trang 1819 In the click event handler, you will need to declare a variable (ws) that will
be a reference to the web service and instantiate that service
' instantiate the XML Web Service proxy Dim ws As localhost.SHello
ws = New localhost.SHello()
20 Declare a variable to represent the security credentials (cred); it should
be of type ICredentials Instantiate the object as belonging to theNetworkCredentialclass Pass two string parameters to theconstructor; they should be the Text properties from the txtUsernameand txtPassword controls
' get a NetworkCredential object Dim cred As ICredentials
cred = New NetworkCredential(txtUserName.Text, txtPassword.Text)
21 Assign the credentials to the web services Credentials property
' configure the client credentials ws.Credentials = cred
At this point, you have instantiated the web service and built networkcredentials that will be used when you execute the web service The nextstep is to call the web method of the web service to see if it all works Thecall to any web methods must be in Try Catch blocks to ensure thatyou handle authentication exceptions
22 Declare a variable for a String
23 Declare a Try block, call the web method, and assign the return data to thestring variable
24 In the Catch block, assign the string literal "AuthenticationFailure, try again"to the String variable
25 After the End Try statement, assign the string variable to the Textproperty of the lblHello control The following code listing is thecomplete click event handler for the btnHello control:
Trang 19' instantiate the XML Web Service proxy Dim ws As localhost.SHello
ws = New localhost.SHello() ' get a NetworkCredential object Dim cred As ICredentials
cred = New NetworkCredential(txtUserName.Text, txtPassword.Text) ' configure the client credentials
ws.Credentials = cred Dim s As String Try
s = ws.HelloWorld() Catch
s = "Authentication Failure, try again"
End Try lblHello.Text = s End Sub
26 Save and execute the application Enter a random user name and password,click the button, and you should get the authentication error messageshown next:
Before you can test the authentication, you will need to create some accounts thatyou can test against
Trang 20EXERCISE 8-3
Adding Accounts to the Server
In this exercise, you will create a number of security accounts for your server sothat you can test the client for the HelloSecure web service Note that computerand account names will vary because the servers will have different names For anin-depth discussion on how to create accounts in different environments, please seeAppendix E
1 Open the Computer Management console from Control Panel |Administrative Tools
2 Expand the System Tools
3 Expand Local Users and Groups
4 Click Users
5 Review the users defined for your computer
6 Right-click the Users folder; select New User from the context menu
7 Fill in the information to create a new user account The only mandatorypiece of information needed is the login name; it must be unique within theserver This image shows the New User dialog filled in:
Trang 21The password should be entered at this time, and as you will never log in toWindows with this account, you must clear the check box beside User MustChange Password At Next Logon.
8 Click Create, and the user account has been created
9 Create the following user accounts: User1, User2, and User3 Set thepassword to be "password."
10 Close the Computer Management console
11 Open the HelloTest project in Visual Studio NET
12 Run the program
Trang 2213 Use the username User1 and password The result is shown here:
The application you built through the three preceding exercises provides a goodskeleton on which to build other secured applications
The Windows authentication methods work well in intranets, but because of theadditional ports that need to be opened to communicate through a firewall, thesemethods are not recommended for use on the Internet The next section will dealwith SOAP headers and how to customize them for authentication
Custom SOAP Headers
For authenticating users on the Internet, you will most likely want to use a databasethat stores the account information of authorized users—there will potentially betoo many users that need to be authenticated and that do not need to be maintainedusing an internal solution (Active Directory) Your authentication implementationthen passes these credentials from the user to the XML web service so that theservice can authenticate the user
Trang 23passwords in the SOAP header, you need to be concerned about the security of theinformation, and the best solution is to use strong encryption on the header only.
To customize the SOAP headers, you need to derive a class from SoapHeader
as in the following code segment:
Imports System.Web.Services Imports System.Web.Services.Protocols Public Class AuthenticationHeader
Inherits SoapHeader ' declare storage for username and password Public username As String
Public password As String End Class
' declare the XML Web Service Public Class HelloService
Inherits WebService ' declare a reference to the header public AuthenticationHeader m_header;
<WebMethod()> _
<SoapHeader("m_header", Required=false)> _ Public Function HelloWorld() As String ' do something interesting
Return "Hello World"
End Function End Class
Because you are implementing a custom authentication method, you need toturn off the authentication in the XML web service’s Web.config file, as shown inthe following code segment Otherwise, the settings in the Web.config file wouldoverride the custom authentication:
Authentication ensures that you know the identity of the entity that is accessing
the service The other side of the coin is authorization—ensuring that the entity
has been granted the right to perform the actions requested Authorization is yournext topic
Trang 24The Three Amigos in the authorization game are ASP.NET, the NET Framework,and the Windows operating system These three provide many techniques thatcombine to build a secure environment When an XML web service consumer wants
to access a resource, the effective permissions for that resource are the combination
of the authenticated consumer’s Windows permissions, the assembly’s declarativeaccess security, and the role-based security for the XML web service These are thekey factors to remember about this combination:
■ The Windows operating system's security is based on the ability of theadministrator to control access to resources All resources in the Windowsoperating system have Discretionary Access Control Lists (DACLs)associated with them Only administrators can modify these DACLs tocontrol the access for the users (consumers)
One of the vexing issues with Windows native
authentication is that it is based on protocols
that require the use of additional TCP/IP
ports Depending on the client and if Active
Directory is installed, these ports might be
the ones used by NTLM authentication or
Kerberos V5 authentication
The biggest problem using Windows
authentication is on the Internet where the
additional ports must be made available
through any firewalls The existence of ports
that are used solely for authentication is an
invitation to would-be hackers This iswhy there is a global rule that Windowsauthentication never is used on the Internet
Any of the authentication modes thattransmit their traffic via HTTP (port 80)are considered when needing authentication
on the Internet You must always rememberthat some of these authentication modes sendthe credentials in clear text, whereas othersuse SSL or digest authentication to encryptthe transmission of the credentials
FROM THE CLASSROOM