This process involves an initialamount of overhead, but once the channel is established, the client and serviceexchange a lightweight, signed security context token, which optimizes mess
Trang 1CHAPTER 8 Establish Trusted Communication with WS-Secure Conversation
T HE WS-S ECURE C ONVERSATIONspecification allows Web services and clients toestablish a token-based, secure conversation for the duration of a session It isanalogous to the Secure Sockets Layer (SSL) protocol that provides on-demand,secure communications over the HTTP transport channel Secure conversationsare well suited to participants that do not inherently trust each other, eitherbecause they have no ongoing relationship, or, for example, because they havenot established certificate-based public-private keys to secure their conversa-tions In Chapters 6 and 7, you saw how the WS-Security and WS-Policy family
of specifications combine to provide a comprehensive approach to securing Webservices Together these specifications provide an assortment of security options,including digital signatures, encryption algorithms, and custom authorizationschemes
In previous chapters, I discussed these technologies in the context of tive security, meaning that they protect messages in transit and keep unwantedeyes from discovering sensitive information This is certainly an important appli-cation of these technologies, and it needs no further explanation But for thepurpose of this chapter, I need to expand the context within which to view thesetechnologies They are no longer needed just for protective security; in a broadercontext, they are needed for establishing trusted communications
protec-In the discussions so far, we have made the big assumption that the clientand Web service automatically trust each other By this, I mean the assumptionthat they both have an equivalent confidence in the integrity of the security tokensthey are using to sign, encrypt, and otherwise secure their communications Forexample, if a client and a Web service agree to encrypt their messages using adigital X.509 certificate, then they must both trust the source of the certificate,and must be comfortable using the private and public keys that are generatedfrom the certificate In a sense, both the client and the Web service have come to
a mutual agreement that they will offload the burden of proving trust to a party (trusted!) source, which issues a digital certificate to act as the tangible record
third-of that trust
Trang 2Of course, the issue is more complex than this When it comes to certificates,for many of us they are a necessary requirement for trusted communication As
a client, I may have all the trust in the world for a service provider, but I still need
to use a digital certificate for the mechanics of signing and encrypting shared sages I happen to be comfortable with digital certificates for most communicationrequirements because it represents certified trust However, other client-servicecommunications may be just as well off using a simpler UsernameToken securitytoken, which is based on a simple username-password combination that getshashed during transit Luckily, the WSE implementation of the WS-Securityspecification is flexible, and you have a choice of security token types to use forconducting trusted communication
mes-The point is that your preferred security tokens and your preferred hashingand encryption algorithms are simply a means to a bigger goal of establishing
trusted communication, otherwise known in the Web services world as secure
conversation There is no single correct choice of technologies that you should
always use Instead, you need to be using those technologies that are appropriatefor establishing a trusted, secure conversation between a given client and Webservice The rules can change depending on who is doing the communicating.This chapter focuses on how you establish session-oriented, trusted communi-cations using the WS-Secure Conversation specification The great thing about theWS-Specifications is that many of the concepts complement each other and build
on each other The understanding that you now have about Security and Policy will translate directly into the concepts behind WS-Secure Conversation
WS-By the end of this chapter, you will have a good understanding of what tutes secure conversation, and a broader appreciation for the usefulness of theWS-Security family of specifications
consti-Overview of Secure Conversation
The WS-Secure Conversation (and WS-Trust) specifications provide the meansfor a client and a service to establish an optimized secure communication chan-nel for a limited duration of time Secure conversation is based on security tokensthat are procured by a service token provider This process involves an initialamount of overhead, but once the channel is established, the client and serviceexchange a lightweight, signed security context token, which optimizes messagedelivery times compared with using regular security tokens The security contexttoken enables the same signing and encryption features that you are used to withregular security tokens
Secure conversation is analogous to communications over the HTTPS col HTTPS establishes a secure channel for the duration of a session, and ceases
proto-to be in effect once that session is over The classic example is an eCommerce
Trang 3transaction, in which you browse a catalog over an unsecured channel, but thenyou establish a secure channel for the purpose of completing a sales transactionwith the vendor The communication needs to be secure because sensitive pay-ment and order information is being exchanged, and so the client and thevendor need to establish a secured channel for as long as it takes to complete thetransaction For performance reasons, the client does not need or even want toestablish a continuous secure session for every interaction with the vendor
HTTPS is useful for providing on-demand secure communication for exactly aslong as it is needed
NOTE HTTPS and WS-Secure Conversation differ in one important way:
HTTPS is not typically used for client authentication, whereas secure versation is.
con-A secure conversation has the following characteristics:
• It is based on established security tokens, including UsernameTokens andX.509 certificates
• It uses a dedicated service token provider to generate a signed servicecontext token, which is a lightweight security proxy
• It provides a secure communication channel for the duration of the session
• It provides optimized performance for session-oriented communicationswith multiple round-trips (by using the security context token)
The difference between secure conversation and standard secure messageexchange (with WS-Security and WS-Policy) is that a standard security policyframework establishes a fixed security policy that all service clients must adhere
to However, secure conversation has a more dynamic aspect The client and vice can initiate a secure channel as needed, rather than based on an establishedpolicy framework Secure conversation uses security tokens that are issued for thepurpose of a specific communication The service itself can act as the provider ofthese security tokens Alternatively, this responsibility can be offloaded to a third-party service token provider, which is a dedicated resource that acts as a trustedintermediary between clients and services, and the issuer of security tokens fortheir secure conversations Figure 8-1 provides an architecture diagram for typicalsecure conversation solutions
Trang 4ser-(1) The Client issues a signed request to the STS for a Security Context Token
SERVICE TOKEN PROVIDER (STS)
CLIENT
SERVICE
(2) The STS responds by issuing a Security Context Token
(3) The Client issues a secured Web service request using the Security Context Token
(4) The Web service issues
a secured response using the Security Context Token
Note: The Web Service and the Service Token Provider may be accessed through the same virtual directory; or may be deployed on separate servers.
Note: The Client retrieves a Security Context Token from the STS prior to initiating the first request to the Web service.
DOMAIN BOUNDARY
DOMAIN BOUNDARY
(only applies if the
STS and the Web
service are deployed
on separate servers)
Figure 8-1 Architecture diagram for a secure conversation solution
A secure conversation is initiated by a client that requires an on-demandsecure communication session with a Web service The session may be requiredfor the duration of one request, or for several back-and-forth requests andresponses between the client and Web service
The workflow for establishing and conducting a secure conversation is sented in Figure 8-1, and typically follows four steps:
pre-Step 1: The client issues a signed request to the security token service provider for a security context token.
The client initiates the secure conversation by issuing a signed request
to the security token service (STS) provider for a security context token.The client may sign the request with any standard security token,including UsernameToken and X.509 certificates The sample solutionwill demonstrate using a UsernameToken security token
Trang 5gen-Steps 3 and 4: The client and the Web service use the security context token for further communication.
The client and Web service use the security context token to secureback-and-forth request and response communications with each other
The security context token can be used like any standard security token
It inherits from the same base classes and its usage is no different fromthe security tokens you learned how to work with in Chapter 6 Securitycontext tokens may be cached in a global cache for future retrieval, forexample, when the client will be issuing multiple requests over a period
of time We will look at how to do this later in the chapter
Programming-wise, Web Services Enhancements (WSE) 2.0 makes it veryeasy to implement a service token provider because the WSE infrastructure willautomatically issue security context tokens This feature is enabled by simplyadding a configuration element to the service token provider’s configuration file
The STS provider can be incorporated into the client’s target Web service, or theSTS provider can be implemented as a dedicated Web service There is little dif-ference in the code between a “hosted” service token provider (that resides in theclient’s target Web service) and a dedicated service token provider (that resides
on a separate domain) There are some significant configuration and ment differences between the two models, but code-wise they are very similar
deploy-NOTE The feature you know as Secure Conversation uses several WS-Specifications, including WS-Trust, WS-Secure Conversation, and WS-Security In addition, you can reduce code listings (and potential errors!) by implementing policy frameworks for the participating services and clients This chapter does not focus on when particular WS-Specifications come into play Instead, the focus is on understanding the concepts, and discussing practical code samples.
Trang 6Figure 8-2 The Visual Studio NET Solution Explorer for the WSSecureConversation
How to Implement a Secure Conversation Solution
It is time to dust off the familiar StockTrader service-oriented application andretrofit it to participate in a secure conversation I will discuss how to constructboth the client and the Web service In the solution, the Web service is both a ser-vice provider and a secure token service provider This means that the Web service
is responsible for supplying its clients with the security token for establishing asession-oriented secure conversation
Figure 8-2 shows the Solution Explorer for a new sample solution calledWSSecureConversation.sln, which you will see how to build in this section
It includes three projects, which represent the following four components:
1 The Web service provider: WSSecureConvService.csproj
2 The Security Token Service provider: WSSecureConvService.csproj
3 The Web service client: WSSecureConvClient.csproj
4 Interface definition assembly: StockTraderTypes.csproj
Trang 7As noted earlier, the Web service hosts the security token service provider, so
it is playing double duty in this project All that the Web service actually does is
to provide an endpoint for clients to access the STS HTTP handler
The References nodes are expanded so you can see dependencies However,the complexity is not in the project structure; rather, it lies in the nature of thecommunication pathways between the client and service The sample solutionfollows the architecture that is presented in Figure 8-1 Before I present the solu-tion, let’s review the required implementation steps for both the Web service andthe client who are participating in the secure conversation
Before we look at how to build the sample solution, let’s review the tual steps that are required to implement the Web service, the Security TokenService provider, and the client projects
concep-How to Implement the Web Service and the Security Token Service Provider
The implementation for the Web service requires the following four steps:
Step 1: Configure the Web service to use WSE 2.0.
Verify that the web.config file includes the standard WSE elementsfor the WebServicesConfiguration and WebServicesExtension classes
Remember to use the WSE 2.0 Configuration Settings Editor to avoidhaving to manually type these entries
Step 2: Configure the security token service provider in the web.config file.
The WSE class framework provides a ready-to-use handler for menting the STS provider All you have to do is register it correctly inthe web.config file, as outlined in more detail later in this chapter Thehandler will automatically generate a security token for use in the secureconversation
imple-Step 3: Create a custom token manager.
This step is required in order to process the signature of the client requestthat initiates the secure conversation If the client’s signature cannot beverified, then the rest of the workflow cannot proceed Recall that this sig-nature will later be used to sign the security context token
Step 4: Implement policy verification.
In the Web service itself, implement code to verify policy requirementsprogrammatically, including digital signature and encryption require-ments Alternatively, you can create a policy framework file
Trang 8How to Implement the Client
The client application requires a fair amount of custom code, although it sharesmany similarities with what you have seen in previous chapters The biggest dif-ference from before is that the client now implements the workflow for initiatingthe request to the security token service provider This code is in addition to anycode that the client already implements for interfacing with the target Web service.The implementation for the client requires the following six steps:
Step 1: Generate a security token for signing the upcoming service token request.
This security token has nothing to do with the security context tokenthat you will ultimately use to secure the conversation between serviceand client Instead, this security token is only used by the client to gen-erate a signed request to receive a security context token from the STSprovider In turn, the STS provider will sign its response when it delivers
a security context token back to the client In this example, I will showyou how to use a simple UsernameToken security token to sign the ini-tial request and response for the security context token Note that therequest to the STS provider must be signed, otherwise the request will
be rejected
Step 2: Set a proxy reference to the security token service provider.
Clients communicate with standard Web services using a proxy class
In the same way, they also communicate with a Security Token Serviceprovider using a proxy class, called SecurityContextTokenServiceClient,which is a member of the Microsoft.Web.Services2.Security namespace
Step 3: Issue a signed request to the provider for a security context token.
The request for a security context token is issued by the client via aspecialized proxy class called the SecurityContextTokenServiceClientclass, which is initialized with a URI reference to the security tokenservice provider The specialized proxy class provides a method calledIssueSecurityContextTokenAuthenticated for issuing the request andfor receiving the response back from the STS provider Note that thismethod may be called synchronously or asynchronously However, youwill usually call the method synchronously because no further com-munication is typically possible between the service and client if thismethod fails to return a valid security context token So you may pre-fer to wait for a synchronous call to return, and to thereby hold off onexecuting additional code until you know that you can proceed
Trang 9Step 4: Retrieve the security context token from the provider.
The IssueSecurityContextTokenAuthenticated method will return a validSecurityContextToken object if the call is successful You are now ready
to make secured Web service requests using this security context token
Step 5: Add security elements to sign and encrypt upcoming Web service requests using the new security context token.
The security context token is no different from other security tokensthat you worked with in Chapter 6, including the UsernameToken andX509SecurityToken classes You add the security context token to theSOAP request message header, just as you would any other securitytoken If you need to make multiple service requests over an extendedperiod of time, then you may wish to add the security context token to
a global cache for future retrieval You will also then need to store thetoken ID for future reference because it is possible that the global cachewill contain other security tokens, and you will need a way to retrievethe correct token from the cache
Step 6: Proceed to call the Web service methods as usual.
After all this work, nothing much changes The Web service methods arecalled as usual, and the only difference is that the requests and
responses are being secured with the security context token for theduration of the session
Build a Secure Conversation Solution
I will now review the detailed steps for building the Web service and the client in
a secure conversation solution This section follows the outlines of the previoussections on how to implement the Web service and the client
Build the Web Service and the Security Token Service Provider
The Web service and STS provider are contained within the projectWSSecureConvService.csproj, and are built as described in the followingsections
Trang 10Step 1: Configure the Web Service to Use WSE 2.0
This step will add registration information to the web.config file for the standardWebServicesConfiguration and WebServicesExtension classes Use the WSE 2.0Configuration Settings Editor, or else manually add the required configurationsettings
Step 2: Configure the Security Token Provider
The WSE 2.0 infrastructure will automatically issue security context tokens withthe simple configuration entry shown in Listing 8-1
Listing 8-1 Configure the Security Token Service Provider
Trang 11installed the Chapter 6 sample solutions, then you will already have the cates and keys properly configured If you have not done so, then please refer toChapter 5 for information on how to configure the test certificates that are pro-vided with WSE 2.0
certifi-Of course, you can only use the <tokenIssuer> and <serverToken> elements
if the Web service and the security token service are installed in the same virtualdirectory If this is not the case, then your secure conversation architecture must
be using a stand-alone security token service
Step 3: Create a Custom Token Manager
The custom token manager verifies the digital signature on the original requestfrom a client to the security token service provider Recall that this request must
be signed by the client, or it will be rejected by the STS provider The custom tokenmanager verifies UsernameToken signing tokens It should be implemented as
a separate class in the Web service, although you should provide it with the samenamespace as the Web service asmx file Listing 8-2 shows the code listing forthe custom token manager
Listing 8-2 The Custom Token Manager
[SecurityPermissionAttribute(SecurityAction.Demand, ➥ Flags=SecurityPermissionFlag.UnmanagedCode)]
public class CustomUsernameTokenManager : UsernameTokenManager {
protected override string AuthenticateToken( UsernameToken token ) {
// Retrieve the password from the token password = ( token.Password );
// Optional: Validate the password with custom code // Add code here (e.g., perform database lookup)
Trang 12// Return the validated password return Convert.ToBase64String( password );
} } }
In addition, you must register the custom token manager in the web.configfile, as shown in Listing 8-3 Look at the <securityTokenManager> element, andnotice that the custom token manager class is registered using the namespace
of the STS provider (WSSecureConvService)
Listing 8-3 Register the Custom Token Manager in the web.config File
</security>
</configuration>
As an alternative to a custom token manager, you can implement a policyfile which states that incoming requests to the service token provider must bedigitally signed The WSE 2.0 infrastructure will automatically enforce the policywithout requiring you to write custom code
By this point you may have lost track of all the edits to the web.config file thatare required in order to implement support for secure conversation Listing 8-4shows the full listing for the web.config file
Listing 8-4 The web.config Configuration Settings for the Security Token Service Provider (Implemented in the WSSecureConvService Sample Solution)
PublicKeyToken=31bf3856ad364e35" />
</configSections>
Trang 14NOTE If your custom token manager does not work correctly, verify that it is properly registered in web.config, with correct type and assembly information This is the most common reason issues may occur with the manager.
Step 4: Implement Policy Requirements in the Business Web Service
In the sample solution, the security token service provider is implemented in thesame Web service project as the business Web service itself, which contains theservice methods that are of interest to the client
All of the work to obtain a security context token will be wasted if you do notimplement and enforce a policy requirement in the business Web service to ensurethat all incoming requests are signed and encrypted You also have to ensure thatoutgoing responses back to the client are properly signed and encrypted In thecase of a secure conversation, the signing and encryption is accomplished with asecurity context token However, the implementation code is generically writtenfor all security scenarios, so you will be covered for standard security tokens, aswell as secure context tokens (Recall that all security tokens derive from the samebase class.)
Listing 8-5 demonstrates how to implement checks for digital signaturesand encryption on incoming service requests to a business Web method calledRequestQuote It also shows how to implement digital signing and encryption
on outgoing responses back to the client
Listing 8-5 The RequestQuote Method with Request and Response Encryption
public Quote RequestQuote(string Symbol) {
// Reject any requests which are not valid SOAP requests SoapContext requestContext = RequestSoapContext.Current;
if (requestContext == null) {
throw new ApplicationException("Only SOAP requests are permitted."); }
// Check if the Soap Message is Signed.
SecurityContextToken sct = GetSigningToken(requestContext) as ➥ SecurityContextToken;
if (sct == null) {
throw new ApplicationException("The request is not signed with an SCT."); }