Skip navigation.
Downloads | Product Documentation | Support

Programming Web Services for WebLogic Server

# Configuring Security

The following sections describe how to configure security for your Web Service:

- Overview of Web Services Security
- What Type of Security Should You Configure?
- Configuring Message-Level Security (Digital Signatures and Encryption)
- Configuring Transport-Level Security
- Configuring Access Control Security: Main Steps

# Overview of Web Services Security

To secure your WebLogic Web Service, you configure one or more of three different types of security:

- Message-level security, in which data in a SOAP message is digitally signed or encrypted.

See Configuring Message-Level Security (Digital Signatures and Encryption).

- Transport-level security, in which SSL is used to secure the connection between a client application and the Web Service.

See Configuring Transport-Level Security.

- Access control security, which specifies which roles are allowed to access Web Services.

See Configuring Access Control Security: Main Steps.

# What Type of Security Should You Configure?

Access control security answers the question "who can do what?" First you specify the security roles that are allowed to access a Web Service; a security role is a privilege granted to users or groups based on specific conditions. Then, when a client application attempts to invoke a Web Service operation, the client authenticates itself to WebLogic Server, and if the client has the authorization, it is allowed to continue with the invocation. Access control security secures only WebLogic Server resources. That is, if you configure only access control security, the connection between the client application and WebLogic Server is not secure and the SOAP message is in plain text.

With transport-level security, you secure the connection between the client application and WebLogic Server with Secure Sockets Layer (SSL). SSL provides secure connections by allowing two applications connecting over a network to authenticate the other's identity and by encrypting the data exchanged between the applications. Authentication allows a server, and optionally a client, to verify the identity of the application on the other end of a network connection. Encryption makes data transmitted over the network intelligible only to the intended recipient.

Transport-level security, however, secures only the connection itself. This means that if there is an intermediary between the client and WebLogic Server, such as a router or message queue, the intermediary gets the SOAP message in plain text. When the intermediary sends the message to a second receiver, the second receiver does not know who the original sender was. Additionally, the encryption used by SSL is "all or nothing": either the entire SOAP message is encrypted or it is not encrypted at all. There is no way to specify that only selected parts of the SOAP message be encrypted.

Message-level security includes all the security benefits of SSL, but with additional flexibility and features. Message-level security is end-to-end, which means that a SOAP message is secure even when the transmission involves one or more intermediaries. The SOAP message itself is digitally signed and encrypted, rather than just the connection. And finally, you can specify that only parts of the message be signed or encrypted.

# Configuring Message-Level Security (Digital Signatures and Encryption)

Message-level security specifies whether the SOAP messages between a client application and the Web Service it is invoking should be digitally signed or encrypted or both.

WebLogic Web Services implement the following OASIS Standard 1.0 Web Services Security specifications, dated April 6, 2004:

- Web Services Security: SOAP Message Security
- Web Services Security: Username Token Profile
- Web Services Security: X.509 Certificate Token Profile
- Web Services Security: SAML Token Profile

These specifications provide security token propagation, message integrity, and message confidentiality. These mechanisms can be used independently (such as passing a username token for user authentication) or together (such as digitally signing and encrypting a SOAP message and specifying that a user must use X.509 certificates for authentication).

You configure message-level security for a Web Service by attaching one or more WS-Policy files that contain security policy statements, as specified by the WS-Policy (dated September 2004) specification. See Using WS-Policy Files for Message-Level Security Configuration for detailed information about how the Web Services runtime environment uses these files.

See Configuring Simple Message-Level Security: Main Steps for the basic steps you must perform to configure simple message-level security. This section discusses configuration of the Web Services runtime environment, as well as configuration of message-level security for a particular Web Service and how to code a client application to invoke the service.

You can also configure message-level security for a Web Service at runtime, after a Web Service has been deployed. See Associating WS-Policy Files at Runtime Using the Administration Console for details.

Note: You cannot digitally sign or encrypt a SOAP attachment.

## Main Use Cases of Message-Level Security

The BEA implementation of the Web Services Security: SOAP Message Security specification supports the following use cases:

- Use X.509 certificates to sign and encrypt a SOAP message, starting from the client application that invokes the message-secured Web Service, to the WebLogic Server instance that is hosting the Web Service and back to the client application.
- Specify the SOAP message targets that are signed or encrypted: the body, specific SOAP headers, or specific elements.
- Include a username, SAML, or X.509 token in the SOAP message for authentication.

## Using WS-Policy Files for Message-Level Security Configuration

You specify the details of message-level security for a WebLogic Web Service with one or more WS-Policy files. The WS-Policy specification provides a general purpose model and XML syntax to describe and communicate the policies of a Web Service.

Note: WebLogic Server includes three simple WS-Policy files that BEA recommends for most use cases. See WebLogic Server WS-Policy Files. However, if you use SAML tokens for authentication, or you want to specify that particular parts of a SOAP message rather than the entire body be encrypted or digitally signed, you must create your own WS-Policy files. See Creating and Using a Custom WS-Policy File.

The WS-Policy files used for message-level security are XML files that describe whether and how the SOAP messages resulting from an invoke of an operation should be digitally signed or encrypted. They can also specify that a client application authenticate itself using a username, SAML, or X.509 token.

Note: The policy assertions used in the WS-Policy file to configure message-level security for a WebLogic Web Service are based on the assertions described in the December 18, 2002 version of the Web Services Security Policy Language (WS-SecurityPolicy) specification. This means that although the exact syntax and usage of the assertions in WebLogic Server are different, they are similar in meaning to those described in the specification. The assertions are not based on the latest update of the specification (13 July 2005.)

You use the `@Policy` and `@Policies` JWS annotations in your JWS file to associate WS-Policy files with your Web Service. You can associate any number of WS-Policy files with a Web Service, although it is up to you to ensure that the assertions do not contradict each other. You can specify a WS-Policy file at both the class- and method-level of your JWS file.

## WebLogic Server WS-Policy Files

WebLogic Server includes three simple WS-Policy files that you can specify in your JWS file if you do not want to create your own WS-Policy files: `Auth.xml, Encrypt.xml`, and `Sign.xml`. BEA recommends that unless you have specific security needs, you use these pre-packaged files as often as possible.

### Auth.xml

The WebLogic Server `Auth.xml` file, shown below, specifies that the client application invoking the Web Service must authenticate itself with one of the tokens (username or X.509) that support authentication.

>     <?xml version="1.0"?>

>     <wsp:Policy
>       xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
>       xmlns:wssp="http://www.bea.com/wls90/security/policy"

>       >

>       <wssp:Identity/>

>     </wsp:Policy>

### Sign.xml

The WebLogic Server `Sign.xml` file specifies that the body and WebLogic-specific system headers of the SOAP message be digitally signed. It also specifies that the SOAP message include a Timestamp, which is digitally signed, and that the token used for signing is also digitally signed. The token used for signing is included in the SOAP message.

The following headers are signed when using the `Sign.xml` WS-Policy file:

- `SequenceAcknowledgement`
- `AckRequested`
- `Sequence`
- `Action`
- `FaultTo`
- `From`
- `MessageID`
- `RelatesTo`
- `ReplyTo`
- `To`
- `SetCookie`
- `Timestamp`

The WebLogic Server Sign.xml file is shown below:

>     <?xml version="1.0"?>

>     <wsp:Policy
>       xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
>       xmlns:wssp="http://www.bea.com/wls90/security/policy"
>       xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
>       xmlns:wls="http://www.bea.com/wls90/security/policy/wsee#part"
>       >

>       <wssp:Integrity>

>         <wssp:SignatureAlgorithm URI="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>

>         <wssp:CanonicalizationAlgorithm
>               URI="http://www.w3.org/2001/10/xml-exc-c14n#"/>

>         <wssp:Target>
>           <wssp:DigestAlgorithm URI="http://www.w3.org/2000/09/xmldsig#sha1" />
>           <wssp:MessageParts
>               Dialect="http://www.bea.com/wls90/security/policy/wsee#part">
>               wls:SystemHeaders()
>           </wssp:MessageParts>
>         </wssp:Target>

>         <wssp:Target>
>           <wssp:DigestAlgorithm URI="http://www.w3.org/2000/09/xmldsig#sha1" />
>           <wssp:MessageParts
>               Dialect="http://www.bea.com/wls90/security/policy/wsee#part">
>               wls:SecurityHeader(wsu:Timestamp)
>           </wssp:MessageParts>
>         </wssp:Target>

>         <wssp:Target>
>           <wssp:DigestAlgorithm URI="http://www.w3.org/2000/09/xmldsig#sha1" />
>           <wssp:MessageParts
>               Dialect="http://schemas.xmlsoap.org/2002/12/wsse#part">
>               wsp:Body()
>           </wssp:MessageParts>
>         </wssp:Target>

>       </wssp:Integrity>

>       <wssp:MessageAge/>

>     </wsp:Policy>

### Encrypt.xml

The WebLogic Server `Encrypt.xml` file specifies that the entire body of the SOAP message be encrypted. By default, the encryption token is not included in the SOAP message.

>     <?xml version="1.0"?>

>     <wsp:Policy
>       xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
>       xmlns:wssp="http://www.bea.com/wls90/security/policy"
>       >

>       <wssp:Confidentiality>
>         <wssp:KeyWrappingAlgorithm URI="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
>         <wssp:Target>
>           <wssp:EncryptionAlgorithm
>              URI="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/>
>           <wssp:MessageParts
>              Dialect="http://schemas.xmlsoap.org/2002/12/wsse#part">
>              wsp:Body()
>           </wssp:MessageParts>
>         </wssp:Target>
>         <wssp:KeyInfo/>
>       </wssp:Confidentiality>

>     </wsp:Policy>

## Abstract and Concrete WS-Policy Files

The WebLogic Web Services runtime environment recognizes two slightly different types of WS-Policy files: abstract and concrete. The pre-packaged WS-Policy files `Auth.xml`, `Encrypt.xml`, and `Sign.xml` are all abstract.

Abstract WS-Policy files do not explicitly specify the security tokens that are used for authentication, encryption, and digital signatures, but rather, the Web Services runtime environment determines the security tokens when the Web Service is deployed. Specifically, this means the`<Identity>` and `<Integrity>` elements (or assertions) of the WS-Policy files do not contain a `<SupportedTokens><SecurityToken>` child element, and the `<Confidentiality>` element WS-Policy file does not contain a `<KeyInfo><SecurityToken>` child element.

If your Web Service is associated with only these pre-packaged WS-Policy files, then client authentication requires username tokens. Web Services support only one type of token for encryption and digital signatures (`X.509`), which means that in the case of the `<Integrity>` and `<Confidentiality>` elements, concrete and abstract WS-Policy files end up being essentially the same.

If your Web Service is associated with an abstract WS-Policy file and it is published as an attachment to the WSDL (which is the default behavior), the static WSDL file packaged in the Web Service archive file (JAR or WAR) will be slightly different than the dynamic WSDL of the deployed Web Service. This is because the static WSDL, being abstract, does not include specific `<SecurityToken>` elements, but the dynamic WSDL does include these elements because the Web Services runtime has automatically filled them in when it deployed the service. For this reason, in the code that creates the JAX-RPC stub in your client application, ensure that you specify the dynamic WSDL or you will get a runtime error when you try to invoke an operation:

>     HelloService service = new HelloService(Dynamic_WSDL);

You can specify either the static or dynamic WSDL to the `clientgen` Ant task in this case. See Browsing to the WSDL of the Web Service for information on viewing the dynamic WSDL of a deployed Web Service.

Concrete WS-Policy files explicitly specify the details of the security tokens at the time the Web Service is programmed. Programmers create concrete WS-Policy files when they know, at the time they are programming the service, the details of the type of authentication (such as using `x509` or `SAML` tokens); whether multiple private key and certificate pairs from the keystore are going to be used for encryption and digital signatures; and so on.

# Configuring Simple Message-Level Security: Main Steps

The following procedure describes how to configure simple message-level security for the Web Services security runtime, a particular WebLogic Web Service, and a client application that invokes an operation of the Web Service. In this document, simple message-level security is defined as follows:

- The message-secured Web Service uses the pre-packaged WS-Policy files (`Auth.xml`, `Sign.xml`, and `Encrypt.xml`) to specify its security requirements, rather than a user-created WS-Policy file. See Using WS-Policy Files for Message-Level Security Configuration for a description of these files.
- The Web Service makes its associated WS-Policy files publicly available by attaching them to its deployed WSDL, which is also publicly visible.
- The Web Services runtime uses the out-of-the-box private key and X.509 certificate pairs, store in the default keystores, for its encryption and digital signatures, rather than its own key pairs. These out-of-the-box pairs are also used by the core WebLogic Server security subsystem for SSL and are provided for demonstration and testing purposes. For this reason BEA highly recommends you use your own keystore and key pair in production. To use key pairs other than out-of-the-box pairs, see Using Key Pairs Other Than the Out-Of-The-Box SSL Pair.

Warning: If you plan to deploy the Web Service to a cluster in which different WebLogic Server instances are running on different computers, you must use a keystore and key pair other than the out-of-the-box ones, even for testing purposes. The reason is that the key pairs in the default WebLogic Server keystore, `DemoIdentity.jks`, are not guaranteed to be the same across WebLogic Servers running on different machines. If you were to use the default keystore, the WSDL of the deployed Web Service would specify the public key from one of these keystores, but the invoke of the service might actually be handled by a server running on a different computer, and in this case the server's private key would not match the published public key and the invoke would fail. This problem only occurs if you use the default keystore and key pairs in a cluster, and is easily resolved by using your own keystore and key pairs.

- The client invoking the Web Service uses a username token to authenticate itself, rather than an X.509 token.
- The client invoking the Web Service is a stand-alone Java application, rather than a module running in WebLogic Server.

Later sections describe some of the preceding scenarios in more detail, as well as additional Web Services security uses cases that build on the simple message-level security use case.

It is assumed in the following procedure that you have already created a JWS file that implements a WebLogic Web Service and you want to update it so that the SOAP messages are digitally signed and encrypted. It is also assumed that you use Ant build scripts to iteratively develop your Web Service and that you have a working `build.xml` file that you can update with new information. Finally, it is assumed that you have a client application that invokes the non-secured Web Service. If these assumptions are not true, see:

- Programming the JWS File
- Iterative Development of WebLogic Web Services
- Invoking Web Services

To configure simple message-level security for a WebLogic Web Service:

1. Update your JWS file, adding WebLogic-specific `@Policy` and `@Policies` JWS annotations to specify the pre-packaged WS-Policy files that are attached to either the entire Web Service or to particular operations.

See Updating the JWS File with @Policy and @Policies Annotations, which describes how to specify any WS-Policy file. For this basic procedure, follow only the instructions for specifying the pre-packaged WS-Policy files: `Auth.xml`, `Sign.xml` and `Encrypt.xml`.

2. Recompile and redeploy your Web Service as part of the normal iterative development process.

See Iterative Development of WebLogic Web Services Starting From Java: Main Steps.

3. Create a keystore used by the client application. BEA recommends that you create one client keystore per application user.

You can use the Cert Gen utility or Sun Microsystem's keytool utility to perform this step. For development purposes, the `keytool` utility is the easiest way to get started.

See Obtaining Private Keys and Digital Signatures.

4. Create a private key and digital certificate pair, and load it into the client keystore. The same pair will be used to both digitally sign the client's SOAP request and encrypt the SOAP responses from WebLogic Server.

Make sure that the certificate's key usage allows both encryption and digital signatures. Also see Ensuring That WebLogic Server Can Validate the Client's Certificate for information about how WebLogic Server ensures that the client's certificate is valid.

Warning: BEA requires a key length of 1024 bits or larger.

You can use Sun Microsystem's keytool utility to perform this step.

See Obtaining Private Keys and Digital Signatures.

5. Using the Administration Console, create users for authentication in your security realm.

See Users, Groups, and Security Roles.

6. Update your client application by adding the Java code to invoke the message-secured Web Service.

See Updating a Client Application to Invoke a Message-Secured Web Service.

7. Recompile your client application.

See Compiling and Running the Client Application for general information.

See the following sections for information about additional Web Service security uses cases that build on the basic message-level security use case:

- Using Key Pairs Other Than the Out-Of-The-Box SSL Pair
- Setting the SOAP Message Expiration
- Creating and Using a Custom WS-Policy File
- Associating WS-Policy Files at Runtime Using the Administration Console
- Using Security Assertion Markup Language (SAML) Tokens For Identity
- Using X.509 Certificate Tokens for Identity
- Using a Password Digest In the SOAP Message Rather Than Plaintext
- Invoking a Message-Secured Web Service From a Client Running in a WebLogic Server Instance
- Associating a Web Service with a Security Configuration Other Than the Default

## Ensuring That WebLogic Server Can Validate the Client's Certificate

You must ensure that WebLogic Server is able to validate the X.509 certificate that the client uses to digitally sign its SOAP request, and that WebLogic Server in turn uses to encrypt its SOAP responses to the client. Do one of the following:

- Ensure that the client application obtains a digital certificate that WebLogic Server automatically trusts, because it has been issued by a trusted certificate authority.
- Create a certificate registry which lists all the individual certificates trusted by WebLogic Server, and then ensure that the client uses one of these registered certificates.

For more information, see SSL Certificate Validation.

## Updating the JWS File with @Policy and @Policies Annotations

Use the `@Policy` and `@Policies` annotations in your JWS file to specify that the Web Service has one or more WS-Policy files attached to it. You can use these annotations at either the class or method level.

The `@Policies` annotation simply groups two or more `@Policy` annotations together. Use the `@Policies` annotation if you want to attach two or more WS-Policy files to the class or method. If you want to attach just one WS-Policy file, you can use `@Policy` on its own.

The `@Policy` annotation specifies a single WS-Policy file, where it is located, whether the policy applies to the request or response SOAP message (or both), and whether to attach the WS-Policy file to the public WSDL of the service.

Use the `uri` attribute to specify the location of the WS-Policy file, as described below:

- To specify one of the three pre-packaged WS-Policy files that are installed with WebLogic Server, use the `policy:` prefix and the name of one of the WS-Policy files (either `Auth.xml`, `Encrypt.xml`, or `Sign.xml`), as shown in the following example:

>     @Policy(uri="policy:Encrypt.xml")

If you use the pre-packaged WS-Policy files, you do not have to create one yourself or package it in an accessible location. For this reason, BEA recommends that you use the pre-packaged WS-Policy files whenever you can.

See Using WS-Policy Files for Message-Level Security Configuration for information on the various types of message-level security provided by the pre-packaged WS-Policy files.

- To specify a user-created WS-Policy file, specify the path (relative to the location of the JWS file) along with its name, as shown in the following example:

>     @Policy(uri="../policies/MyPolicy.xml")

In the example, the `MyPolicy.xml` file is located in the `policies` sibling directory of the one that contains the JWS file.

- You can also specify that a WS-Policy file that is located in a shared J2EE library; this method is useful if you want to share the file amongst multiple Web Services packaged in different J2EE archives.

In this case, it is assumed that the WS-Policy file is in the `META-INF/policies` or `WEB-INF/policies` directory of the shared J2EE library. Be sure, when you package the library, that you put the WS-Policy file in this directory.

To specify a WS-Policy file in a shared J2EE library, use the `policy` prefix and then the name of the WS-policy file, as shown in the following example:

>     @Policy(uri="policy:MySharedPolicy.xml")

See Creating Shared J2EE Libraries and Optional Packages for information on creating shared libraries and setting up your environment so the Web Service can find the shared WS-Policy files.

You can also set the following attributes of the `@Policy` annotation:

- `direction`—Specifies whether the policy file should be applied to the request (inbound) SOAP message, the response (outbound) SOAP message, or both. The default value if you do not specify this attribute is both. The `direction` attribute accepts the following values:

- `Policy.Direction.both`
- `Policy.Direction.inbound`
- `Policy.Direction.outbound`

- `attachToWsdl`—Specifies whether the policy file should be attached to the WSDL file that describes the public contract of the Web Service. The default value of this attribute is `false`. Abstract WS-Policy files cannot be attached at build time, but rather, they are attached at deploy time when the missing information is filled in by WebLogic Server.

The following example shows how to use the `@Policy` and `@Policies` JWS annotations, with the relevant sections shown in bold:

>     package examples.webservices.security_jws;

>     import weblogic.jws.WLHttpTransport;
>     import weblogic.jws.Policies;
>     import weblogic.jws.Policy;
>     import javax.jws.WebService;
>     import javax.jws.WebMethod;
>     import javax.jws.soap.SOAPBinding;

>     /**
>      *
>      */
>     @WebService(name="SecureHelloWorldPortType",
>                 serviceName="SecureHelloWorldService",
>                 targetNamespace="http://www.bea.com")

>     @SOAPBinding(style=SOAPBinding.Style.DOCUMENT,
>                  use=SOAPBinding.Use.LITERAL,
>                  parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)

>     @WLHttpTransport(contextPath="SecureHelloWorldService",
>                      serviceUri="SecureHelloWorldService",
>                      portName="SecureHelloWorldServicePort")

>     @Policies({
>         @Policy(uri="policy:Auth.xml", direction=Policy.Direction.inbound),
>         @Policy(uri="policy:Sign.xml"),
>         @Policy(uri="policy:Encrypt.xml")})

>     public class SecureHelloWorldImpl {

>       @WebMethod()
>       public String sayHello(String s) {
>         return "Hello " + s;
>       }
>     }

In the example, three WS-Policy files are attached to the Web Service at the class level, which means that all three WS-Policy files are applied to all public operations of the Web Service. The specified WS-Policy files are those pre-packaged with WebLogic Server, which means that the developers do not need to create their own files or package them in the corresponding archive.

The `Auth.xml` file is applied to only the request (inbound) SOAP message, as specified by the `direction` attribute. This means that only the client application needs to provide a username token; when WebLogic Server responds to the invoke, it does not provide a username token. The `Sign.xml` WS-Policy file specifies that the body and WebLogic system headers of both the request and response SOAP message be digitally signed. The `Encrypt.xml` policy file specifies that the body of both the request and response SOAP messages be encrypted.

## Updating a Client Application to Invoke a Message-Secured Web Service

When you update your Java code to invoke a message-secured Web Service, you must load a private key and digital certificate pair from the client's keystore and pass this information, along with a username and password for user authentication if so required by the WS-Policy, to the secure WebLogic Web Service being invoked.

If the WS-Policy file of the Web Service specifies that the SOAP request must be encrypted, then the Web Services client runtime automatically gets the server's certificate from the WS-Policy file that is attached to the WSDL of the service, and uses it for the encryption. If, however, the WS-Policy file is not attached to the WSDL, or the entire WSDL itself is not available, then the client application must use a client-side copy of the WS-Policy file; for details, see Using a Client-Side Security WS-Policy File.

The following example shows a Java client application that invokes the message-secured WebLogic Web Service described by the JWS file in Updating the JWS File With the Security-Related Annotations. The client application takes five arguments:

- Client username for client authentication
- Client password for client authentication
- Client private key file
- Client digital certificate
- WSDL of the deployed Web Service

The security-specific code in the sample client application is shown in bold (and described after the example):

>     package examples.webservices.security_jws.client;

>     import weblogic.security.SSL.TrustManager;

>     import weblogic.xml.crypto.wss.provider.CredentialProvider;
>     import weblogic.xml.crypto.wss.WSSecurityContext;
>     import weblogic.wsee.security.bst.ClientBSTCredentialProvider;
>     import weblogic.wsee.security.unt.ClientUNTCredentialProvider;

>     import javax.xml.rpc.Stub;
>     import java.util.List;
>     import java.util.ArrayList;

>     import java.security.cert.X509Certificate;

>     /**
>      *  Copyright (c) 2005 by BEA Systems. All Rights Reserved.
>      */
>     public class SecureHelloWorldClient {
>       public static void main(String[] args) throws Throwable {

>         //username or password for the UsernameToken
>         String username = args[0];
>         String password = args[1];

>         //client private key file
>         String keyFile = args[2];

>         //client certificate
>         String clientCertFile = args[3];

>         String wsdl = args[4];

>         SecureHelloWorldService service = new SecureHelloWorldService_Impl(wsdl + "?WSDL" );

>         SecureHelloWorldPortType port = service.getSecureHelloWorldServicePort();

>         //create credential provider and set it to the Stub
>         List credProviders = new ArrayList();

>         //client side BinarySecurityToken credential provider -- x509
>         CredentialProvider cp = new ClientBSTCredentialProvider(clientCertFile, keyFile);
>         credProviders.add(cp);

>         //client side UsernameToken credential provider
>         cp = new ClientUNTCredentialProvider(username, password);
>         credProviders.add(cp);

>         Stub stub = (Stub)port;
>         stub._setProperty(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credProviders);

>         stub._setProperty(WSSecurityContext.TRUST_MANAGER,
>           new TrustManager(){
>              public boolean certificateCallback(X509Certificate[] chain, int validateErr){
>                return true;
>              }
>            } );

>         String response = port.sayHello("World");
>         System.out.println("response = " + response);
>       }
>     }

The main points to note about the preceding code are:

- Import the WebLogic security `TrustManager` API:

>     import weblogic.security.SSL.TrustManager;

- Import the following WebLogic Web Services security APIs to create the needed client-side credential providers, as specified by the WS-Policy files that are associated with the Web Service:

>     import weblogic.xml.crypto.wss.provider.CredentialProvider;
>     import weblogic.xml.crypto.wss.WSSecurityContext;
>     import weblogic.wsee.security.bst.ClientBSTCredentialProvider;
>     import weblogic.wsee.security.unt.ClientUNTCredentialProvider;

- Use the `ClientBSTCredentialProvider` WebLogic API to create a binary security token credential provider from the client's certificate and private key:

>      CredentialProvider cp =
>         new ClientBSTCredentialProvider(clientCertFile, keyFile);

- Use the `ClientUNTCredentialProvider` WebLogic API to create a username token from the client's username and password, which are also known by WebLogic Server:

>     cp = new ClientUNTCredentialProvider(username, password);

- Use the `WSSecurityContext.CREDENTIAL_PROVIDER_LIST` property to pass a `List` object that contains the binary security and username tokens to the JAX-RPC Stub:

>     stub._setProperty(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credProviders)

- Use the `weblogic.security.SSL.TrustManager` WebLogic security API to verify that the certificate used to encrypt the SOAP request is valid. The Web Services client runtime gets this certificate from the deployed WSDL of the Web Service, which in production situations is not automatically trusted, so the client application must ensure that it is okay before it uses it to encrypt the SOAP request:

>     stub._setProperty(WSSecurityContext.TRUST_MANAGER,
>           new TrustManager(){
>              public boolean certificateCallback(X509Certificate[] chain, int validateErr){
>                return true;
>              }
>            } );

## Using Key Pairs Other Than the Out-Of-The-Box SSL Pair

In the simple message-level configuration procedure, documented in Configuring Simple Message-Level Security: Main Steps, it is assumed that the Web Services runtime uses the private key and X.509 certificate pair that is provided out-of-the-box with WebLogic Server; this same key pair is also used by the core security subsystem for SSL and is provided mostly for demonstration and testing purposes. In production environments, the Web Services runtime typically uses its own two private key and digital certificate pairs, one for signing and one for encrypting SOAP messages.

The following procedure describes the additional steps you must take to enable this use case.

1. Obtain two private key and digital certificate pairs to be used by the Web Services runtime. One of the pairs is used for digitally signing the SOAP message and the other for encrypting it.

Although not required, BEA recommends that you obtain two pairs that will be used only by WebLogic Web Services. You must also ensure that both of the certificate's key usage matches what you are configuring them to do. For example, if you are specifying that a certificate be used for encryption, be sure that the certificate's key usage is specified as for encryption or is undefined. Otherwise, the Web Services security runtime will reject the certificate.

Warning: BEA requires that the key length be 1024 bits or larger.

You can use the Cert Gen utility or Sun Microsystem's keytool utility to perform this step. For development purposes, the `keytool` utility is the easiest way to get started.

See Obtaining Private Keys and Digital Signatures.

2. Create, if one does not currently exist, a custom identity keystore for WebLogic Server and load the private key and digital certificate pairs you obtained in the preceding step into the identity keystore.

If you have already configured WebLogic Server for SSL, then you have already created a identity keystore which you can also use in this step.

You can use WebLogic's `ImportPrivateKey` utility and Sun Microsystem's keytool utility to perform this step. For development purposes, the `keytool` utility is the easiest way to get started.

See Creating a Keystore and Loading Private Keys and Trusted Certificate Authorities Into the Keystore.

3. Using the Administration Console, configure WebLogic Server to locate the keystore you created in the preceding step. If you are using a keystore that has already been configured for WebLogic Server, you do not need to perform this step.

See Configuring Keystores for Production.

4. Using the Administration Console, create the default Web Service security configuration, which must be named `default_wss`. The default Web Service security configuration is used by all Web Services in the domain unless they have been explicitly programmed to use a different configuration.

See Create a Web Service security configuration.

5. Update the default Web Services security configuration you created in the preceding step to use one of the private key and digital certificate pairs for digitally signing SOAP messages.

See Specify the Key Pair Used to Sign SOAP Messagess. In the procedure, when you create the properties used to identify the keystore and key pair, enter the exact value for the Name of each property (such as `IntegrityKeyStore`, `IntegrityKeyStorePassword`, and so on), but enter the value that identifies your own previously-created keystore and key pair in the Value fields.

6. Similarly, update the default Web Services security configuration you created in a preceding step to use the second private key and digital certificate pair for encrypting SOAP messages.

See Create keystore used by SOAP message encryption. In the procedure, when you create the properties used to identify the keystore and key pair, enter the exact value for the Name of each property (such as `ConfidentialityKeyStore`. `ConfidentialityKeyStorePassword`, and so on), but enter the value that identifies your own previously-created keystore and key pair in the Value fields.

## Setting the SOAP Message Expiration

The `<MessageAge>` element in the WS-Policy file specifies whether SOAP messages resulting from an invoke of the Web Service associated with the WS-Policy file have an expiration. WebLogic Server rejects SOAP requests that have expired, based on their expiration time and the creation timestamp, which is included in the message. You can further configure expiration of messages by using the Administration Console to create and update the Web Services security configuration that is associated with the service.

The following bullets describe how the WebLogic Web Services runtime determines the expiration of a SOAP message for a particular Web Service:

- If the WS-Policy file associated with the Web Service does not include a `<MessageAge>` assertion, then the SOAP messages never expire.
- If the WS-Policy file includes a `<MessageAge>` assertion, but with no attributes, and the Web Service is not associated with a Web Service security configuration, then the expiration time is 60 seconds. If the Web Service is associated with a Web Service security configuration, then the expiration is the value of the Validity Period timestamp field of the associated Web Service security configuration (typically `default_wss`).

The pre-packaged `Sign.xml` WS-Policy file falls into this category.

- If the WS-Policy file includes a `<MesageAge>` assertion with the `Age` attribute, then the expiration time is the value of the `Age` attribute. This value always overrides the value of the Validity Period field of any associated Web Service security configuration.

It is assumed in the following procedure that you have followed the steps in Configuring Simple Message-Level Security: Main Steps and now want to set the message expiration.

To set the SOAP message expiration:

1. Ensure that the WS-Policy file associated with the Web Service includes a `<MessageAge>` assertion. The pre-packaged `Sign.xml` file includes one without any attributes.

If you add a `<MessageAge>` assertion to a custom WS-Policy file, and specify the `Age` attribute, then you are done; the expiration is the value of this attribute and cannot be overridden with the Administration Console. If you do not specify an attribute because you want the default of 60 seconds, then you are also done. If, however, you want to change this default value, go to the next step.

2. Using the Administration Console, create (if you have not already done so) the default Web Service security configuration, which must be named `default_wss`. The default Web Service security configuration is used by all Web Services in the domain unless they have been explicitly programmed to use a different configuration.

See Create a Web Service security configuration.

3. Update the default Web Services security configuration you created in the preceding step to specify a different expiration:

1. In the left pane of the Administration Console, select domain > Web Service Security.
2. Select `default_wss` in the Web Service Security Configuration table.
3. Select Web Service Security > Timestamp.
4. Update the Validity Period field with the new expiration time, in seconds.
5. Optionally update the other fields. Click the Help link in the top right corner for detailed information about these fields.
6. Click Save.

## Creating and Using a Custom WS-Policy File

Although WebLogic Server includes three pre-packaged WS-Policy files that typically satisfy the security needs of most programmers, you can also create and use your own WS-Policy file if you need additional configuration. For example, you must create your own WS-Policy file if you want to:

- Use SAML tokens for authentication
- Specify that particular parts of the body of a SOAP message be encrypted or digitally signed, rather than the entire body, which is what the `Encrypt.xml` and `Sign.xml` pre-packaged WS-Policy files do.

See Using WS-Policy Files for Message-Level Security Configuration for general information about WS-Policy files and how they are used for message-level security configuration.

When you create a custom WS-Policy file, you can separate out the three main security categories (authentication, encryption, and signing) into three separate WS-Policy files, as do the pre-packaged files, or create a single WS-Policy file that contains all three categories. You can also create a custom WS-Policy file that changes just one category (such as authentication) and use the pre-packaged files for the other categories (`Sign.xml` and `Encrypt.xml`). In other words, you can mix and match the number and content of the WS-Policy files that you associate with a Web Service. In this case, however, you must always ensure yourself that the multiple files do not contradict each other.

The root element of your WS-Policy file must be `<Policy>` and include the following namespace declarations:

>     <wsp:Policy
>       xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
>       xmlns:wssp="http://www.bea.com/wls90/security/policy"
>       xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
>       xmlns:wls="http://www.bea.com/wls90/security/policy/wsee#part"
>       >

### Defining Child Elements in a Custom WS-Policy File

Define the following child elements of the `<Policy>` root element in your WS-Policy file (see Security Policy Assertion Reference, for complete reference information about the elements):

- `<Identity>`—Specifies the tokens that are supported for authentication. The `<SupportedTokens>` element groups one or more `<SecurityTokens>` elements for each type of supported tokens for identity: username, X.509, or SAML. Use the `<Claims>` element to specify the type of confirmation for SAML tokens (sender-vouches or holder-of-key) and to specify use of password digests when using username tokens.
- `<Confidentiality>`—Specifies what parts of the SOAP message must be encrypted. Optional child elements include: `<KeyWrappingAlgorithm>` to specify the algorithm used to wrap symmetric keys, `<Target>` to specify the blocks of the SOAP message that are encrypted, and `<KeyInfo>` to specify the tokens used for encryption (only X.509 tokens are supported.)
- `<Integrity>`—Specifies what parts of the SOAP message must be digitally signed. Optional child elements include: `<SignatureAlgorithm>` to specify the algorithm used to sign the message, `<CanonicalizationAlgorithm>` to specify the algorithm used for canonicalization, `<Target>` to specify the blocks of the SOAP message that are digitally signed, and `<SupportedTokens>` to specify the types of tokens that can be used for signing (only X.509 tokens are supported.)
- `<MessageAge>`—Specifies the maximum age, in seconds, of a SOAP message.

See Example of a Custom WS-Policy File for an example of a custom WS-Policy file used to specify SAML tokens for identity. Because the `<Integrity>` and `<Confidentiality>` elements do not include `<KeyInfo>` and `<SupportedTokens>` child elements, respectively, these sections of the file are abstract. The `<Identity>` element does include the SAML token, so the identity section is concrete.

You can also use the abstract pre-packaged WS-Policy files as templates to create your own custom files. See Auth.xml, Sign.xml, and Encrypt.xml.

### Example of a Custom WS-Policy File

>     <<?xml version="1.0"?>

>     <wsp:Policy
>       xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
>       xmlns:wssp="http://www.bea.com/wls90/security/policy"
>       xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
>       xmlns:wls="http://www.bea.com/wls90/security/policy/wsee#part"
>       >

>       <wssp:Identity>
>         <wssp:SupportedTokens>
>           <wssp:SecurityToken  TokenType="http://docs.oasis-open.org/wss/2004/01/oasis-2004-01-saml-token-profile-1.0#SAMLAssertionID">
>             <wssp:Claims>
>               <wssp:ConfirmationMethod>sender-vouches</wssp:ConfirmationMethod>
>             </wssp:Claims>
>           </wssp:SecurityToken>
>         </wssp:SupportedTokens>
>       </wssp:Identity>

>       <wssp:Integrity>

>         <wssp:SignatureAlgorithm URI="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
>         <wssp:CanonicalizationAlgorithm
>              URI="http://www.w3.org/2001/10/xml-exc-c14n#"/>

>         <wssp:Target>
>           <wssp:DigestAlgorithm
>                URI="http://www.w3.org/2000/09/xmldsig#sha1" />
>           <wssp:MessageParts
>                Dialect="http://schemas.xmlsoap.org/2002/12/wsse#part">
>                wsp:Body()
>           </wssp:MessageParts>
>         </wssp:Target>

>         <wssp:Target>
>           <wssp:DigestAlgorithm URI="http://www.w3.org/2000/09/xmldsig#sha1" />
>           <wssp:MessageParts
>                Dialect="http://www.bea.com/wls90/security/policy/wsee#part">
>                wls:SecurityHeader(Assertion)
>           </wssp:MessageParts>
>         </wssp:Target>

>       </wssp:Integrity>

>       <wssp:Confidentiality>

>         <wssp:KeyWrappingAlgorithm URI="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>

>         <wssp:Target>
>           <wssp:EncryptionAlgorithm
>                URI="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/>
>           <wssp:MessageParts
>                Dialect="http://www.bea.com/wls90/security/policy/wsee#part">
>                 wls:SecurityHeader(Assertion)
>           </wssp:MessageParts>
>         </wssp:Target>

>         <wssp:Target>
>           <wssp:EncryptionAlgorithm
>                URI="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/>
>           <wssp:MessageParts
>                Dialect="http://schemas.xmlsoap.org/2002/12/wsse#part">
>                wsp:Body()</wssp:MessageParts>
>         </wssp:Target>

>         <wssp:KeyInfo />
>       </wssp:Confidentiality>

>       <wssp:MessageAge/>

>     </wsp:Policy>

## Associating WS-Policy Files at Runtime Using the Administration Console

The simple message-level configuration procedure, documented in Configuring Simple Message-Level Security: Main Steps, describes how to use the `@Policy` and `@Policies` JWS annotations in the JWS file that implements your Web Service to specify one or more WS-Policy files that are associated with your service. This of course implies that you must already know, at the time you program your Web Service, which WS-Policy files you want to associate with your Web Service and its operations. This might not always be possible, which is why you can also associate WS-Policy files at runtime, after the Web Service has been deployed, using the Administration Console.

You can use no `@Policy` or `@Policies` JWS annotations at all in your JWS file and associate WS-Policy files only at runtime using the Administration Console, or you can specify some WS-Policy files using the annotations and then associate additional ones at runtime. However, once you associate a WS-Policy file using the JWS annotations, you cannot change this association at runtime using the Administration Console.

At runtime, the Administration Console allows you to associate as many WS-Policy files as you want with a Web Service and its operations, even if the policy assertions in the files contradict each other or contradict the assertions in WS-Policy files associated with the JWS annotations. It is up to you to ensure that multiple associated WS-Policy files work together. If any contradictions do exist, WebLogic Server returns a runtime error when a client application invokes the Web Service operation.

See Associate a WS-Policy file with a Web Service for detailed instructions on using the Administration Console to associate a WS-Policy file at runtime.

## Using Security Assertion Markup Language (SAML) Tokens For Identity

In the simple Web Services configuration procedure, described in Configuring Simple Message-Level Security: Main Steps, it is assumed that users use username tokens to authenticate themselves. Because WebLogic Server implements the Web Services Security: SAML Token Profile of the Web Services Security specification, users can also use SAML tokens in the SOAP messages to authenticate themselves when invoking a Web Service operation, as described in this section.

Use of SAML tokens works server-to-server. This means that the client application is running inside of a WebLogic Server instance and then invokes a Web Service running in another WebLogic Server instance using SAML for identity. Because the client application is itself a Web Service, the Web Services security runtime takes care of all the SAML processing.

When you configure a Web Service to require SAML tokens for identity, you can specify one of the following confirmation methods:

- `sender-vouches`
- `holder-of-key`

See SAML Token Profile Support in WebLogic Web Services, as well as the Web Services Security: SAML Token Profile specification itself, for details about these confirmation methods.

Note: It is assumed in this section that you understand the basics of SAML and how it relates to core security in WebLogic Server. For general information, see Security Assertion Markup Language (SAML).

It is also assumed in the following procedure that you have followed the steps in Configuring Simple Message-Level Security: Main Steps and now want to enable the additional use case of using SAML tokens, rather than usename tokens, for identity.

To use SAML tokens for identity, follow these steps:

1. Using the Administration Console, configure a SAML identity assertion and credential mapping provider. This step configures the core WebLogic Server security subsystem. For details, see:

- Configuring a SAML Identity Assertion Provider
- Configuring a SAML Credential Mapping Provider

2. Create a custom WS-Policy file that specifies that SAML should be used for identity. The exact syntax depends on the type of confirmation method you want to configure (`sender-vouches` or `holder-of-key`).

To specify the sender-vouches confirmation method:

- Create a `<SecurityToken>` child element of the `<Identity><SupportedTokens>` elements and set the `TokenType` attribute to a value that indicates SAML token usage.
- Add a `<Claims><Confirmationmethod>` child element of `<SecurityToken>` and specify `sender-vouches`.

For example:

>     <?xml version="1.0"?>

>     <wsp:Policy
>       xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
>       xmlns:wssp="http://www.bea.com/wls90/security/policy"
>       xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
>       xmlns:wls="http://www.bea.com/wls90/security/policy/wsee#part"
>       >

>       <wssp:Identity>
>         <wssp:SupportedTokens>
>           <wssp:SecurityToken
>             TokenType="http://docs.oasis-open.org/wss/2004/01/oasis-2004-01-saml-token-profile-1.0#SAMLAssertionID">
>             <wssp:Claims>
>               <wssp:ConfirmationMethod>sender-vouches</wssp:ConfirmationMethod>
>             </wssp:Claims>
>           </wssp:SecurityToken>
>         </wssp:SupportedTokens>
>       </wssp:Identity>

>     </wsp:Policy>

To specify the holder-of-key confirmation method:

- Create a `<SecurityToken>` child element of the `<Integrity><SupportedTokens>` elements and set the `TokenType` attribute to a value that indicates SAML token usage.

The reason you put the SAML token in the `<Integrity>` assertion for the `holder-of-key` confirmation method is that the Web Service runtime must prove the integrity of the message, which is not required by `sender-vouches`.

- Add a `<Claims><Confirmationmethod>` child element of `<SecurityToken>` and specify `holder-of-key`.

For example:

>     <?xml version="1.0"?>

>     <wsp:Policy
>       xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
>       xmlns:wssp="http://www.bea.com/wls90/security/policy"
>       xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
>       xmlns:wls="http://www.bea.com/wls90/security/policy/wsee#part">

>       <wssp:Integrity>
>         <wssp:SignatureAlgorithm
>            URI="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
>         <wssp:CanonicalizationAlgorithm
>            URI="http://www.w3.org/2001/10/xml-exc-c14n#"/>

>         <wssp:Target>
>           <wssp:DigestAlgorithm
>              URI="http://www.w3.org/2000/09/xmldsig#sha1" />
>           <wssp:MessageParts
>              Dialect="http://schemas.xmlsoap.org/2002/12/wsse#part">
>              wsp:Body()
>           </wssp:MessageParts>
>         </wssp:Target>

>         <wssp:SupportedTokens>
>           <wssp:SecurityToken
>               IncludeInMessage="true"
>               TokenType="http://docs.oasis-open.org/wss/2004/01/oasis-2004-01-saml-token-profile-1.0#SAMLAssertionID">
>             <wssp:Claims>
>               <wssp:ConfirmationMethod>holder-of-key</wssp:ConfirmationMethod>
>             </wssp:Claims>
>           </wssp:SecurityToken>
>         </wssp:SupportedTokens>
>       </wssp:Integrity>

>     </wsp:Policy>

- By default, the WebLogic Web Services runtime always validates the X.509 certificate specified in the `<KeyInfo>` assertion of any associated WS-Policy file. To disable this validation when using SAML holder-of-key assertions, you must configure the Web Service security configuration associated with the Web service by setting a property on the SAML token handler. See Disable X.509 certificate validation when using SAML holder_of_key assertions for information on how to do this using the Administration Console.

See Creating and Using a Custom WS-Policy File for additional information about creating your own WS-Policy file. See Security Policy Assertion Reference, for reference information about the assertions.

3. Update the appropriate `@Policy` annotations in the JWS file that implements the Web Service to point to the custom WS-Policy file you created in the preceding step. For example, if you want invokes of all the operations of a Web Service to SAML for identity, specify the `@Policy` annotation at the class-level.

You can mix and match the WS-Policy files that you associate with a Web Service, as long as they do not contradict each other. For example, you can create a simple `MyAuth.xml` file that contains only the `<Identity>` security assertion to specify use of SAML for identity and then associate it with the Web Service together with the pre-packaged `Encrypt.xml` and `Sign.xml` files. It is, however, up to you to ensure that multiple associated WS-Policy files do not contradict each other; if they do, you will either receive a runtime error or the Web Service might not behave as you expect.

4. Recompile and redeploy your Web Service as part of the normal iterative development process.

See Iterative Development of WebLogic Web Services Starting From Java: Main Steps.

5. Create a client application that runs in a WebLogic Server instance to invoke the main Web Service using SAML as identity. See Invoking a Message-Secured Web Service From a Client Running in a WebLogic Server Instance for details.

## Using X.509 Certificate Tokens for Identity

In the simple Web Services configuration procedure, described in Configuring Simple Message-Level Security: Main Steps, it is assumed that users use username tokens to authenticate themselves. Because WebLogic Server implements the Web Services Security: X.509 Certificate Token Profile of the Web Services Security specification, users can also use X.509 certificates to authenticate themselves when invoking a Web Service operation, as described in this section.

Note: It is assumed in the following procedure that you have followed the steps in Configuring Simple Message-Level Security: Main Steps and now want to enable the additional use case of using X.509 certificates for identity.

1. Using the Administration Console, create (if you have not already done so) the default Web Service security configuration, which must be named `default_wss`. The default Web Service security configuration is used by all Web Services in the domain unless they have been explicitly programmed to use a different configuration.

See Create a Web Service security configuration.

2. Update the default Web Services security configuration you created in the preceding step to specify that X.509 certificates should be used for identity. See Use X.509 certificates to establish identity.
3. Create a custom WS-Policy file that specifies that X.509 certificates should be used for identity.

In particular, you must set the `TokenType` attribute of the `<SecurityToken>` child element of the `<Identity><SupportedTokens>` elements to `#x509Token`, as shown in the following simple example:

>     <?xml version="1.0"?>

>     <wsp:Policy
>       xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
>       xmlns:wssp="http://www.bea.com/wls90/security/policy"
>       >

>       <wssp:Identity>

>           <wssp:SupportedTokens>
>             <wssp:SecurityToken TokenType="#X509Token" />
>           </wssp:SupportedTokens>

>       </wssp:Identity>

>     </wsp:Policy>

See Creating and Using a Custom WS-Policy File for additional information about creating your own WS-Policy file.

4. Update the appropriate `@Policy` annotations in your JWS file to point to the custom WS-Policy file you created in the preceding step. For example, if you want invokes of all the operations of a Web Service to use X.509 for identity, specify the `@Policy` annotation at the class-level.

You can mix and match the WS-Policy files that you associate with a Web Service, as long as they do not contradict each other. For example, you can create a simple `MyAuth.xml` file that contains only the `<Identity>` security assertion to specify use of X.509 certificates for identity and then associate it with the Web Service together with the pre-packaged `Encrypt.xml` and `Sign.xml` files. It is, however, up to you to ensure that multiple associated WS-Policy files do not contradict each other. If they do, you will receive a runtime error.

5. Recompile and redeploy your Web Service as part of the normal iterative development process.

See Iterative Development of WebLogic Web Services Starting From Java: Main Steps.

6. You can use the same client application, described in Updating a Client Application to Invoke a Message-Secured Web Service, when using X.509 for identity. The only optional update is to remove the creation of the username token, which is not needed for this use case. The code to remove is:

>         //client side UsernameToken credential provider
>         cp = new ClientUNTCredentialProvider(username, password);
>         credProviders.add(cp);

## Using a Password Digest In the SOAP Message Rather Than Plaintext

By default, the WebLogic Web Services security runtime uses cleartext passwords, rather than the password digest, in the SOAP messages resulting from an invoke of a message-secured Web Service. The following procedure shows how to change this default behavior so that the SOAP messages use the password digest.

It is assumed in the following procedure that you have followed the steps in Configuring Simple Message-Level Security: Main Steps and now want to specify that all SOAP messages use password digest rather than cleartext.

1. Using the Administration Console, create (if you have not already done so) the default Web Service security configuration, which must be named `default_wss`. The default Web Service security configuration is used by all Web Services in the domain unless they have been explicitly programmed to use a different configuration.

Warning: If you have created Web Services security configuration in addition to the default one (`default_wss`), each configuration should specify the same password digest use. Inconsistent password digest use in different Web Service security configurations will result in a runtime error.

See Create a Web Service security configuration.

2. Update the default Web Services security configuration you created in the preceding step to specify that password digests should be used in SOAP messages. See Use a password digest in SOAP messages.
3. Update the default WebLogic Authentication provider of the core WebLogic Server security to store cleartext passwords rather than the digest. See Configure Authentication and Identity Assertion providers.
4. If you are not using the pre-packaged `Auth.xml` file and have instead created a custom WS-Policy file and have explicitly specified a username token with the `<Identity><SupportedTokens><SecurityToken>` elements, then you must add a `<Claims><UsePassword>` child element as shown below:

>     <wssp:Identity>

>       <wssp:SupportedTokens>

>        <wssp:SecurityToken TokenType="#UsernameToken">
>         <wssp:Claims>
>          <wssp:UsePassword
>           Type="http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest" />

>         </wssp:Claims>
>        </wssp:SecurityToken>

>       </wssp:SupportedTokens>

>     </wssp:Identity>

If you are using the pre-packaged `Auth.xml` file to configure authentication, you do not need to perform this step.

See Creating and Using a Custom WS-Policy File for additional information about creating your own WS-Policy file.

5. If you created a custom WS-Policy file, update the appropriate `@Policy` annotations in your JWS file to point to it. See Updating the JWS File with @Policy and @Policies Annotations.
6. Recompile and redeploy your Web Service as part of the normal iterative development process.

See Iterative Development of WebLogic Web Services Starting From Java: Main Steps.

## Invoking a Message-Secured Web Service From a Client Running in a WebLogic Server Instance

In the simple Web Services configuration procedure, described in Configuring Simple Message-Level Security: Main Steps, it is assumed that a stand-alone client application invokes the message-secured Web Service. Sometimes, however, the client is itself running in a WebLogic Server instance, as part of an EJB, servlet, or another Web Service. In this case, you can use the core WebLogic Server security framework to configure the credential providers and trust manager so that your EJB, servlet, or JWS code contains only the simple invoke of the secured operation and no other security-related API usage. The following procedure describes the high level steps you must perform to make use of the core WebLogic Server security framework in this use case.

1. In your EJB, servlet, or JWS code, invoke the Web Service operation as if it were not configured for message-level security. Specifically, do not create a `CredentialProvider` object that contains username or X.509 tokens, and do not use the `TrustManager` core security API to validate the certificate from the WebLogic Server hosting the secure Web Service. The reason you should not use these APIs in your client code is that the Web Services runtime will perform this work for you.
2. Using the Administration Console, configure the required credential mapping providers of the core security of the WebLogic Server instance that hosts your client application. The list of required credential mapper providers depends on the WS-Policy file that is attached to the Web Service you are invoking. Typically, you must configure the credential mapper providers for both username/password and X.509 certificates. See Configuring a WebLogic Credential Mapping Provider.

Note: WebLogic Server includes a credential mapping provider for username/passwords and X.509. However, only username/password is configured by default.

3. Using the Administration Console, create the actual credential mappings in the credential mapping providers you configured in the preceding step. You must map the user principal, associated with the client running in the server, to the credentials that are valid for the Web Service you are invoking. See Configuring a WebLogic Credential Mapping Provider.
4. Using the Administration Console, configure the core WebLogic Server security framework to trust the X.509 certificate of the invoked Web Service. See Configuring the Credential Lookup and Validation Framework.

You are not required to configure the core WebLogic Server security framework, as described in this procedure, if your client application does not want to use the out-of-the-box credential provider and trust manager. Rather, you can override all of this configuration by using the same APIs in your EJB, servlet, and JWS code as in the stand-alone Java code described in Updating a Client Application to Invoke a Message-Secured Web Service. However, using the core security framework standardizes the WebLogic Server configuration and simplifies the Java code of the client application that invokes the Web Service.

## Associating a Web Service with a Security Configuration Other Than the Default

Many use cases previously discussed require you to use the Administration Console to create the default Web Service security configuration called `default_wss`. After you create this configuration, it is applied to all Web Services that either do not use the `@weblogic.jws.security.WssConfiguration` JWS annotation or specify the annotation with no attribute.

There are some cases, however, in which you might want to associate a Web Service with a security configuration other than the default; such use cases include specifying different timestamp values for different services.

To associate a Web Service with a security configuration other than the default:

1. Create a Web Service security configuration with a name that is not `default_wss`.
2. Update your JWS file, adding the `@WssConfiguration` annotation to specify the name of this security configuration. See weblogic.jws.security.WssConfiguration for additional information and an example.
3. Recompile and redeploy your Web Service as part of the normal iterative development process.

See Iterative Development of WebLogic Web Services Starting From Java: Main Steps.

Warning: All Web Services security configurations are required to specify the same password digest use. Inconsistent password digest use in different Web Service security configurations will result in a runtime error.

# Configuring Transport-Level Security

Transport-level security refers to securing the connection between a client application and a Web Service with Secure Sockets Layer (SSL).

See Secure Sockets Layer (SSL) for general information about SSL and the implementations included in WebLogic Server.

To configure transport-level Web Services security:

1. Configure SSL for the core WebLogic Server security subsystem.

You can configure one-way SSL where WebLogic Server is required to present a certificate to the client application, or two-way SSL where both the client applications and WebLogic server present certificates to each other.

To configure two-way or one-way SSL for the core WebLogic Server security subsystem, see Configuring SSL.

2. In the JWS file that implements your Web Service, add the `@weblogic.jws.security.UserDataConstaint` annotation to require that the Web Service be invoked using the HTTPS transport.

For details, see weblogic.jws.security.UserDataConstraint.

3. Specify the URL used to invoke the Web Service using HTTPS by using one of the following mechanisms:

- When programming the JWS file that implements your Web Service, specify the `@weblogic.jws.WLHttpsTransport` annotation. See weblogic.jws.WLHttpsTransport.
- When building the Web Service, specify the`<WLHttpsTransport>` child element of the `jwsc` Ant task. See jwsc.

Either of these methods ensure that the generated WSDL of the Web Service includes an HTTPS binding.

4. Recompile and redeploy your Web Service as part of the normal iterative development process.

See Iterative Development of WebLogic Web Services Starting From Java: Main Steps.

5. Update the `build.xml` file that invokes the `clientgen` Ant task to use a static WSDL to generate the JAX-RPC stubs of the Web Service, rather than the dynamic deployed WSDL of the service.

The reason `clientgen` cannot generate the stubs from the dynamic WSDL in this case is that when you specify the `@UserDataConstraint` annotation, all client applications are required to specify a truststore, including `clientgen`. However, there is currently no way for `clientgen` to specify a truststore, thus the Ant task must generate its client components from a static WSDL that describes the Web Service in the same way as the dynamic WSDL.

6. When you run the client application that invokes the Web Service, specify certain properties to indicate the SSL implementation that your application should use. In particular:

- To specify the Certicom SSL implementation, use the following properties

>     -Djava.protocol.handler.pkgs=weblogic.net
>     -Dweblogic.security.SSL.trustedCAKeyStore=trustStore

where `trustStore` specifies the name of the client-side truststore that contains the list of trusted certificates (one of which should be the server's certificate). To disable host name verification, also specify the following property:

>     -Dweblogic.security.SSL.ignoreHostnameVerification=true

- To specify Sun's SSL implementation, use the following properties:

>     -Djavax.net.ssl.trustStore=trustStore

where `trustStore` specifies the name of the client-side truststore that contains the list of trusted certificates (one of which should be the server's certificate). To disable host name verification, also specify the following property:

>     -Dweblogic.wsee.client.ssl.stricthostchecking=false

See Configuring Two-Way SSL for a Client Application for details about two-way SSL.

## Configuring Two-Way SSL for a Client Application

If you configured two-way SSL for WebLogic Server, the client application must present a certificate to WebLogic Server, in addition to WebLogic Server presenting a certificate to the client application as required by one-way SSL. You must also follow these requirements:

- Create a client-side keystore that contains the client's private key and X.509 certificate pair.

The SSL package of J2SE requires that the password of the client's private key must be the same as the password of the client's keystore. For this reason, the client keystore can include only one private key and X.509 certificate pair.

- Configure the core WebLogic Server's security subsystem, mapping the client's X.509 certificate in the client keystore to a user. See Configuring a User Name Mapper.
- Create a truststore which contains the certificates that the client trusts; the client application uses this truststore to validate the certificate it receives from WebLogic Server. Because of the J2SE password requirement described in the preceding bullet item, this truststore must be different from the keystore that contains the key pair that the client presents to the server.

You can use the Cert Gen utility or Sun Microsystem's keytool utility to perform this step. For development purposes, the `keytool` utility is the easiest way to get started.

See Obtaining Private Keys and Digital Signatures.

- When you run the client application that invokes the Web Service, specify the following properties:

- `-Djavax.net.ssl.trustStore=``trustStore`
- `-Djavax.net.ssl.trustStorePassword=``trustStorePassword`

where `trustStore` specifies the name of the client-side truststore that contains the list of trusted certificates (one of which should be the server's certificate) and `trustStorePassword` specifies the truststore's password.

The preceding properties are in addition to the standard properties you must set to specify the client-side keystore:

- `-Djavax.net.ssl.keyStore=``keyStore`
- -D`javax.net.ssl.keyStorePassword=``keyStorePassword`

## Additional Web Services SSL Examples

The dev2dev CodeShare is a community of developers that share ideas, code and best practices related to BEA technologies. The site includes code examples for a variety of BEA technologies, including using SSL with Web Services.

To view and download the SSL Web Services code examples on the dev2dev site, go to the main Projects page and click on Web Services in the By Technology column.

# Configuring Access Control Security: Main Steps

Access control security refers to configuring the Web Service to control the users who are allowed to access it, and then coding your client application to authenticate itself, using HTTP/S or username tokens, to the Web Service when the client invokes one of its operations.

You specify access control security for your Web Service by using one or more of the following annotations in your JWS file:

- `weblogic.jws.security.RolesAllowed`
- `weblogic.jws.security.SecurityRole`
- `weblogic.jws.security.RolesReferenced`
- `weblogic.jws.security.SecurityRoleRef`
- `weblogic.jws.security.RunAs`

Note: The `@weblogic.security.jws.SecurityRoles` and `@weblogic.security.jws.SecurityIdentity` JWS annotations are deprecated as of WebLogic Server 9.1.

The following procedure describes the high-level steps to use these annotations to enable access control security; later sections in the chapter describe the steps in more detail.

Note: It is assumed in the following procedure that you have already created a JWS file that implements a WebLogic Web Service and you want to update it with access control security. It is also assumed that you use Ant build scripts to iteratively develop your Web Service and that you have a working `build.xml` file that you can update with new information. Finally, it is assumed that you have a client application that invokes the non-secured Web Service. If these assumptions are not true, see:

- Programming the JWS File
- Iterative Development of WebLogic Web Services
- Invoking Web Services

1. Update your JWS file, adding the`@weblogic.jws.security.RolesAllowed`, `@weblogic.jws.security.SecurityRole`, `@weblogic.jws.security.RolesReferenced`, or `@weblogic.jws.security.SecurityRoleRef` annotations as needed at the appropriate level (class or operation).

See Updating the JWS File With the Security-Related Annotations.

2. Optionally specify that WebLogic Server internally run the Web Service using a specific role, rather than the role assigned to the user who actually invokes the Web Service, by adding the `@weblogic.jws.security.RunAs` JWS annotation.

See Updating the JWS File With the @RunAs Annotation.

3. Optionally specify that your Web Service can be, or is required to be, invoked using HTTPS by adding the `@weblogic.jws.WLHttpsTransport` or `@weblogic.jws.security.UserDataConstraint` JWS annotations.

See Configuring Transport-Level Security for details. This section also discusses how to update your client application to use SSL.

4. Recompile and redeploy your Web Service as part of the normal iterative development process.

See Iterative Development of WebLogic Web Services Starting From Java: Main Steps.

5. Using the Administration Console, create valid WebLogic Server users, if they do not already exist. If the mapping of users to roles is external, also use the Admininstration Console to create the roles specified by the `@SecurityRole` annotation and map the users to the roles.

Note: The mapping of users to roles is defined externally if you do not specify the `mapToPrincipals` attribute of the `@SecurityRole` annotation in your JWS file to list all users who can invoke the Web Service.

See Users, Groups, and Security Roles.

6. Update your client application to use the `HttpTransportInfo` WebLogic API to specify the appropriate user and password when creating the JAX-RPC `Service` object.

See Setting the Username and Password When Creating the JAX-RPC Service Object.

7. Update the `build.xml` file that invokes the `clientgen` Ant task to use a static WSDL to generate the JAX-RPC stubs of the Web Service, rather than the dynamic deployed WSDL of the service.

The reason `clientgen` cannot generate the stubs from the dynamic WSDL in this case is that when you specify the `@RolesAllowed` annotation, the entire Web Service is secured, including its WSDL. There is currently no way for `clientgen` to authenticate itself using a valid username, thus the Ant task must generate its client components from a static WSDL that describes the Web Service in the same way as the dynamic WSDL.

## Updating the JWS File With the Security-Related Annotations

Use the WebLogic-specific `@weblogic.jws.security.RolesAllowed` annotation in your JWS file to specify an array of `@weblogic.jws.security.SecurityRoles` annotations that list the roles that are allowed to invoke the Web Service. You can specify these two annotations at either the class- or method-level. When set at the class-level, the roles apply to all public operations. You can add additional roles to a particular operation by specifying the annotation at the method level.

The `@SecurityRole` annotation has the following two attributes:

- `role`—Name of the role that is allowed to invoke the Web Service.
- `mapToPrincipals`—List of users that map to the role. If you specify one or more users with this attribute, you do not have to externally create the mapping between users and roles, typically using the Administration Console. However, the mapping specified with this attribute applies only within the context of the Web Service.

The `@RolesAllowed` annotation does not have any attributes.

You can also use the `@weblogic.jws.security.RolesReferenced` annotation to specify an array of `@weblogic.jws.security.SecurityRoleRef` annotations that list references to existing roles. For example, if the role `manager` is already allowed to invoke the Web Service, you can specify that the `mgr` role be linked to the `manager` role and any user mapped to `mgr` is also able to invoke the Web Service. You can specify these two annotations only at the class-level.

The `@SecurityRoleRef` annotation has the following two attributes:

- `role`—Name of the role reference.
- `link`—Name of the already-specified role that is allowed to invoke the Web Service. The value of this attribute corresponds to the value of the `role` attribute of a `@SecurityRole annotation` specified in the same JWS file.

The `@RolesReferenced` annotation does not have any attributes.

The following example shows how to use the annotations described in this section in a JWS file, with the relevant sections shown in bold:

>     package examples.webservices.security_roles;

>     import javax.jws.WebMethod;
>     import javax.jws.WebService;

>     // WebLogic JWS annotations

>     import weblogic.jws.WLHttpTransport;

>     import weblogic.jws.security.RolesAllowed;
>     import weblogic.jws.security.RolesReferenced;
>     import weblogic.jws.security.SecurityRole;
>     import weblogic.jws.security.SecurityRoleRef;

>     @WebService(name="SecurityRolesPortType",
>                 serviceName="SecurityRolesService",
>                 targetNamespace="http://example.org")

>     @WLHttpTransport(contextPath="security",
>                      serviceUri="SecurityRolesService",
>                       portName="SecurityRolesPort")

>     @RolesAllowed (  {
>         @SecurityRole (role="manager",
>                        mapToPrincipals={ "juliet","amanda" }),
>         @SecurityRole (role="vp")
>     } )

>     @RolesReferenced (
>         @SecurityRoleRef (role="mgr", link="manager")
>     )

>     /**
>      * This JWS file forms the basis of simple Java-class implemented WebLogic
>      * Web Service with a single operation: sayHello
>      *
>      */

>     public class SecurityRolesImpl {

>       @WebMethod()
>       public String sayHello(String message) {
>         System.out.println("sayHello:" + message);
>         return "Here is the message: '" + message + "'";

>       }

>     }

The example shows how to specify that only the `manager`, `vp`, and `mgr` roles are allowed to invoke the Web Service. The `mgr` role is actually a reference to the `manager` role. The users `juliet` and `amanda` are mapped to the `manager` role within the context of the Web Service. Because no users are mapped to the `vp` role, it is assumed that the mapping occurs externally, typically using the Administration Console to update the WebLogic Server security realm.

See JWS Annotation Reference, for reference information on these annotations.

## Updating the JWS File With the @RunAs Annotation

Use the WebLogic-specific @weblogic.jws.security.RunAs annotation in your JWS file to specify that the Web Service is always run as a particular role. This means that regardless of the user, and the role to which the user is mapped, initially invokes the Web Service, the service is internally executed as the specified role.

You can set the `@RunAs` annotation only at the class-level. The annotation has the following attributes:

- `role`—Role which the Web Service should run as.
- `mapToPrincipal`—Principal user that maps to the role.

The following example shows how to use the `@RunAs` annotation in a JWS file, with the relevant sections shown in bold:

>     package examples.webservices.security_roles;

>     import javax.jws.WebMethod;
>     import javax.jws.WebService;

>     // WebLogic JWS annotations

>     import weblogic.jws.WLHttpTransport;

>     import weblogic.jws.security.RunAs;

>     @WebService(name="SecurityRunAsPortType",
>                 serviceName="SecurityRunAsService",
>                 targetNamespace="http://example.org")

>     @WLHttpTransport(contextPath="security_runas",
>                      serviceUri="SecurityRunAsService",
>                      portName="SecurityRunAsPort")

>     @RunAs (role="manager", mapToPrincipal="juliet")

>     /**
>      * This JWS file forms the basis of simple WebLogic
>      * Web Service with a single operation: sayHello
>      *
>      */

>     public class SecurityRunAsImpl {

>       @WebMethod()
>       public String sayHello(String message) {
>         System.out.println("sayHello:" + message);
>         return "Here is the message: '" + message + "'";
>       }
>     }

## Setting the Username and Password When Creating the JAX-RPC Service Object

When you use the `@RolesAllowed` JWS annotation to secure a Web Service so that only specified roles are allowed to access a Web Service, the WSDL that describes the Web Service is itself also protected. This means that you must specify an authorized username and password when creating the JAX-RPC `Service` object in your client application that invokes the protected Web Service.

WebLogic Server provides the `HttpTransportInfo` class for setting the username and password and passing it to the `Service` constructor. The following example is based on the standard way to invoke a Web Service from a standalone Java client (as described in Invoking Web Services) but also shows how to use the `HttpTransportInfo` class to set the username and password. The sections in bold are discussed after the example.

>     package examples.webservices.sec_wsdl.client;

>     import weblogic.wsee.connection.transport.http.HttpTransportInfo;

>     import java.rmi.RemoteException;

>     import javax.xml.rpc.ServiceException;
>     import javax.xml.rpc.Stub;

>     /**
>      * This is a simple standalone client application that invokes the
>      * the <code>sayHello</code> operation of the SecWsdlService Web service.
>      *
>      * @author Copyright (c) 2004 by BEA Systems. All Rights Reserved.
>      */

>     public class Main {

>       public static void main(String[] args)
>           throws ServiceException, RemoteException{

>         HttpTransportInfo info = new HttpTransportInfo();
>         info.setUsername("juliet".getBytes());
>         info.setPassword("secret".getBytes());

>         SecWsdlService service = new SecWsdlService_Impl(args[0] + "?WSDL", info);
>         SecWsdlPortType port = service.getSecWsdlPort();

>         try {
>           String result = null;
>           result = port.sayHello("Hi there!");
>           System.out.println( "Got result: " + result );
>         } catch (RemoteException e) {
>           throw e;
>         }
>       }

>     }

The main points to note in the preceding example are as follows:

- Import the `HttpTransportInfo` class into your client application:

>     import weblogic.wsee.connection.transport.http.HttpTransportInfo;

- Use the `setXXX()` methods of the `HttpTransportInfo` class to set the username and password:

>     HttpTransportInfo info = new HttpTransportInfo();
>     info.setUsername("juliet".getBytes());
>     info.setPassword("secret".getBytes());

In the example, it is assumed that the user `juliet` with password `secret` is a valid WebLogic user and has been mapped to the role specified in the `@RolesAllowed` JWS annotation of the Web Service.

If you are accessing a Web Service using a proxy, the Java code would be similar to:

>     HttpTransportInfo info = new HttpTransportInfo();
>     Proxy p = new Proxy(Proxy.Type.HTTP, new  InetSocketAddress(proxyHost, Integer.parseInt(proxyPort)));
>     info.setProxy(p);
>     info.setProxyUsername(user.getBytes());
>     info.setProxyPassword(pass.getBytes());

- Pass the `info` object that contains the username and password to the `Service` constructor as the second argument, in addition to the standard WSDL first argument:

>     SecWsdlService service = new SecWsdlService_Impl(args[0] + "?WSDL", info);

See Invoking Web Services, for general information about invoking a non-secured Web Service.