You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ws.apache.org by gi...@apache.org on 2012/12/03 22:26:22 UTC

svn commit: r1416670 [1/2] - in /webservices/wss4j/trunk: ./ integration/ integration/src/ integration/src/main/ integration/src/main/java/ integration/src/main/resources/ integration/src/test/ integration/src/test/java/ integration/src/test/java/org/ ...

Author: giger
Date: Mon Dec  3 21:26:13 2012
New Revision: 1416670

URL: http://svn.apache.org/viewvc?rev=1416670&view=rev
Log:
- Kerberos support in StAX - WSS-359
- Kerberos refactoring
- separate module for integration tests as suggested by Colm
- Kerberos bugfixes
- a default/standard KerberosTokenDecoderImpl without dependency to proprietary apis


Added:
    webservices/wss4j/trunk/integration/
    webservices/wss4j/trunk/integration/pom.xml   (with props)
    webservices/wss4j/trunk/integration/src/
    webservices/wss4j/trunk/integration/src/main/
    webservices/wss4j/trunk/integration/src/main/java/
    webservices/wss4j/trunk/integration/src/main/resources/
    webservices/wss4j/trunk/integration/src/test/
    webservices/wss4j/trunk/integration/src/test/java/
    webservices/wss4j/trunk/integration/src/test/java/org/
    webservices/wss4j/trunk/integration/src/test/java/org/apache/
    webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/
    webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/
    webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/
    webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/
    webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/common/
    webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/common/KerberosServiceStarter.java   (with props)
    webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/dom/
    webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/dom/KerberosTest.java
      - copied, changed from r1415303, webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/ws/security/dom/message/token/KerberosTest.java
    webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/stax/
    webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/stax/KerberosTest.java   (with props)
    webservices/wss4j/trunk/integration/src/test/resources/
    webservices/wss4j/trunk/integration/src/test/resources/kerberos/
    webservices/wss4j/trunk/integration/src/test/resources/kerberos/kerberos.jaas
    webservices/wss4j/trunk/integration/src/test/resources/kerberos/kerberos.ldif
    webservices/wss4j/trunk/integration/src/test/resources/kerberos/krb5.conf
    webservices/wss4j/trunk/integration/src/test/resources/log4j.xml   (with props)
    webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/ws/security/common/kerberos/
    webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/ws/security/common/kerberos/KerberosClientAction.java   (contents, props changed)
      - copied, changed from r1400458, webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/ws/security/dom/message/token/KerberosClientAction.java
    webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/ws/security/common/kerberos/KerberosContextAndServiceNameCallback.java   (with props)
    webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/ws/security/common/kerberos/KerberosServiceAction.java   (contents, props changed)
      - copied, changed from r1400458, webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/ws/security/dom/message/token/KerberosServiceAction.java
    webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/ws/security/common/kerberos/KerberosTokenDecoder.java   (contents, props changed)
      - copied, changed from r1400458, webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/ws/security/dom/validate/KerberosTokenDecoder.java
    webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/ws/security/common/kerberos/KerberosTokenDecoderImpl.java   (with props)
    webservices/wss4j/trunk/ws-security-common/src/test/java/org/apache/ws/security/common/kerberos/
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/output/KerberosSecurityTokenOutputProcessor.java
      - copied, changed from r1400458, webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/output/BinarySecurityTokenOutputProcessor.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/KerberosClientSecurityToken.java   (with props)
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/KerberosServiceSecurityToken.java   (with props)
Removed:
    webservices/wss4j/trunk/ws-security-common/src/test/resources/kerberos.jaas
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/ws/security/dom/message/token/KerberosClientAction.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/ws/security/dom/message/token/KerberosServiceAction.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/ws/security/dom/validate/KerberosTokenDecoder.java
    webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/ws/security/dom/message/token/KerberosTest.java
    webservices/wss4j/trunk/ws-security-dom/src/test/resources/kerberos.jaas
Modified:
    webservices/wss4j/trunk/parent/pom.xml
    webservices/wss4j/trunk/pom.xml
    webservices/wss4j/trunk/ws-security-common/pom.xml
    webservices/wss4j/trunk/ws-security-common/src/main/resources/messages/wss4j_errors.properties
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/ws/security/dom/message/WSSecEncrypt.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/ws/security/dom/message/token/KerberosSecurity.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/ws/security/dom/validate/KerberosTokenValidator.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/WSSec.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/ext/OutboundWSSec.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/ext/WSSConstants.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/input/BinarySecurityTokenInputHandler.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/processor/output/WSSSignatureEndingOutputProcessor.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/ws/security/stax/impl/securityToken/SecurityTokenFactoryImpl.java

Added: webservices/wss4j/trunk/integration/pom.xml
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/integration/pom.xml?rev=1416670&view=auto
==============================================================================
--- webservices/wss4j/trunk/integration/pom.xml (added)
+++ webservices/wss4j/trunk/integration/pom.xml Mon Dec  3 21:26:13 2012
@@ -0,0 +1,196 @@
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License. You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing,
+  software distributed under the License is distributed on an
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  KIND, either express or implied. See the License for the
+  specific language governing permissions and limitations
+  under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <parent>
+        <groupId>org.apache.ws.security</groupId>
+        <artifactId>wss4j-parent</artifactId>
+        <relativePath>../parent/pom.xml</relativePath>
+        <version>2.0-SNAPSHOT</version>
+    </parent>
+    <groupId>org.apache.ws.security</groupId>
+    <artifactId>integration</artifactId>
+    <version>2.0-SNAPSHOT</version>
+    <name>Apache WSS4J WS-Security Integration</name>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.ws.security</groupId>
+            <artifactId>wss4j-ws-security-dom</artifactId>
+            <version>${project.version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.ws.security</groupId>
+            <artifactId>wss4j-ws-security-stax</artifactId>
+            <version>${project.version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.ws.security</groupId>
+            <artifactId>wss4j-ws-security-stax</artifactId>
+            <version>${project.version}</version>
+            <classifier>tests</classifier>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.directory.server</groupId>
+            <artifactId>apacheds-kerberos-shared</artifactId>
+            <version>1.5.7</version>
+            <exclusions>
+                <exclusion>
+                    <groupId>bouncycastle</groupId>
+                    <artifactId>bcprov-jdk15</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.server</groupId>
+                    <artifactId>apacheds-i18n</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.server</groupId>
+                    <artifactId>apacheds-core-jndi</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.server</groupId>
+                    <artifactId>apacheds-protocol-shared</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.shared</groupId>
+                    <artifactId>shared-ldap</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.shared</groupId>
+                    <artifactId>shared-ldap-schema</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.shared</groupId>
+                    <artifactId>shared-ldap-schema-loader</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.shared</groupId>
+                    <artifactId>shared-ldap-schema-manager</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.shared</groupId>
+                    <artifactId>shared-cursor</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.shared</groupId>
+                    <artifactId>shared-ldap-jndi</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.shared</groupId>
+                    <artifactId>shared-asn1-codec</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.shared</groupId>
+                    <artifactId>shared-ldap-constants</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.shared</groupId>
+                    <artifactId>shared-ldap-converter</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.shared</groupId>
+                    <artifactId>shared-ldap-schema-dao</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.shared</groupId>
+                    <artifactId>shared-ldif</artifactId>
+                </exclusion>
+                <exclusion>
+                    <groupId>org.apache.directory.shared</groupId>
+                    <artifactId>shared-dsml-parser</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.directory.server</groupId>
+            <artifactId>apacheds-core-annotations</artifactId>
+            <version>1.5.7</version>
+            <scope>test</scope>
+            <exclusions>
+                <exclusion>
+                    <groupId>bouncycastle</groupId>
+                    <artifactId>bcprov-jdk15</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.directory.server</groupId>
+            <artifactId>apacheds-protocol-shared</artifactId>
+            <version>1.5.7</version>
+            <scope>test</scope>
+            <exclusions>
+                <exclusion>
+                    <groupId>bouncycastle</groupId>
+                    <artifactId>bcprov-jdk15</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.directory.server</groupId>
+            <artifactId>apacheds-protocol-kerberos</artifactId>
+            <version>1.5.7</version>
+            <scope>test</scope>
+            <exclusions>
+                <exclusion>
+                    <groupId>bouncycastle</groupId>
+                    <artifactId>bcprov-jdk15</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.directory.server</groupId>
+            <artifactId>apacheds-interceptor-kerberos</artifactId>
+            <version>1.5.7</version>
+            <scope>test</scope>
+            <exclusions>
+                <exclusion>
+                    <groupId>bouncycastle</groupId>
+                    <artifactId>bcprov-jdk15</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>commons-io</groupId>
+            <artifactId>commons-io</artifactId>
+            <version>2.4</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.testng</groupId>
+            <artifactId>testng</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-log4j12</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>log4j</groupId>
+            <artifactId>log4j</artifactId>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+</project>
\ No newline at end of file

Propchange: webservices/wss4j/trunk/integration/pom.xml
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/common/KerberosServiceStarter.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/common/KerberosServiceStarter.java?rev=1416670&view=auto
==============================================================================
--- webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/common/KerberosServiceStarter.java (added)
+++ webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/common/KerberosServiceStarter.java Mon Dec  3 21:26:13 2012
@@ -0,0 +1,151 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.ws.security.integration.test.common;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.directory.server.core.DirectoryService;
+import org.apache.directory.server.core.factory.DefaultDirectoryServiceFactory;
+import org.apache.directory.server.core.factory.DirectoryServiceFactory;
+import org.apache.directory.server.core.factory.PartitionFactory;
+import org.apache.directory.server.core.interceptor.Interceptor;
+import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor;
+import org.apache.directory.server.core.partition.Partition;
+import org.apache.directory.server.kerberos.kdc.KdcServer;
+import org.apache.directory.server.kerberos.shared.crypto.encryption.EncryptionType;
+import org.apache.directory.server.protocol.shared.transport.UdpTransport;
+import org.apache.directory.shared.ldap.entry.DefaultServerEntry;
+import org.apache.directory.shared.ldap.ldif.LdifEntry;
+import org.apache.directory.shared.ldap.ldif.LdifReader;
+
+import java.io.File;
+import java.io.InputStream;
+import java.net.DatagramSocket;
+import java.security.Provider;
+import java.security.Security;
+import java.util.List;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class KerberosServiceStarter {
+
+    /**
+     * The used DirectoryService instance
+     */
+    public static DirectoryService directoryService;
+
+    /**
+     * The used KdcServer instance
+     */
+    public static KdcServer kdcServer;
+
+    private static Provider provider = null;
+    private static int providerPos = 2;
+
+    private static final int kdcPort = 23749;
+
+    public static boolean startKerberosServer() throws Exception {
+        try {
+            DatagramSocket datagramSocket = new DatagramSocket(kdcPort);
+            datagramSocket.setReuseAddress(true);
+            datagramSocket.close();
+        } catch (Exception e) {
+            return false;
+        }
+
+        //Ok, apache ds doesn't like the bouncy castle provider at position 2
+        //Caused by: KrbException: Integrity check on decrypted field failed (31) - Integrity check on decrypted field failed
+        Provider[] installedProviders = Security.getProviders();
+        for (int i = 0; i < installedProviders.length; i++) {
+            Provider installedProvider = installedProviders[i];
+            if ("BC".equals(installedProvider.getName())) {
+                provider = installedProvider;
+                providerPos = i;
+                Security.removeProvider("BC");
+                break;
+            }
+        }
+        if (provider != null) {
+            Security.addProvider(provider);
+        }
+
+        DirectoryServiceFactory directoryServiceFactory = DefaultDirectoryServiceFactory.DEFAULT;
+        directoryService = directoryServiceFactory.getDirectoryService();
+        directoryService.setAccessControlEnabled(false);
+        directoryService.setAllowAnonymousAccess(false);
+        directoryService.getChangeLog().setEnabled(true);
+
+        List<Interceptor> interceptors = directoryService.getInterceptors();
+        interceptors.add(new KeyDerivationInterceptor());
+        directoryService.setInterceptors(interceptors);
+        directoryServiceFactory.init("defaultDS");
+
+        PartitionFactory partitionFactory = directoryServiceFactory.getPartitionFactory();
+        Partition partition = partitionFactory.createPartition("example", "dc=example,dc=com",
+                1000, new File(directoryService.getWorkingDirectory(), "example"));
+
+        partitionFactory.addIndex(partition, "objectClass", 1000);
+        partitionFactory.addIndex(partition, "dc", 1000);
+        partitionFactory.addIndex(partition, "ou", 1000);
+
+        partition.setSchemaManager(directoryService.getSchemaManager());
+        // Inject the partition into the DirectoryService
+        directoryService.addPartition(partition);
+
+        InputStream is = KerberosServiceStarter.class.getClassLoader().getResourceAsStream("kerberos/kerberos.ldif");
+        LdifReader ldifReader = new LdifReader(is);
+        for (LdifEntry entry : ldifReader) {
+            if (entry.isChangeAdd()) {
+                directoryService.getAdminSession().add(new DefaultServerEntry(directoryService.getSchemaManager(), entry.getEntry()));
+            } else if (entry.isChangeModify()) {
+                directoryService.getAdminSession().modify(entry.getDn(), entry.getModificationItems());
+            }
+        }
+        ldifReader.close();
+
+        kdcServer = new KdcServer();
+        kdcServer.setServiceName("DefaultKrbServer");
+        kdcServer.setKdcPrincipal("krbtgt/service.ws.apache.org@service.ws.apache.org");
+        kdcServer.setPrimaryRealm("service.ws.apache.org");
+        kdcServer.setMaximumTicketLifetime(60000 * 1440);
+        kdcServer.setMaximumRenewableLifetime(60000 * 10080);
+        UdpTransport udp = new UdpTransport("localhost", kdcPort);
+        kdcServer.addTransports(udp);
+        kdcServer.setEncryptionTypes(new EncryptionType[]{EncryptionType.AES128_CTS_HMAC_SHA1_96});
+        kdcServer.setDirectoryService(directoryService);
+        kdcServer.start();
+
+        return true;
+    }
+
+    public static void stopKerberosServer() throws Exception {
+        try {
+            directoryService.shutdown();
+            FileUtils.deleteDirectory(directoryService.getWorkingDirectory());
+            kdcServer.stop();
+        } finally {
+            //restore BC position
+            Security.removeProvider("BC");
+            if (provider != null) {
+                Security.insertProviderAt(provider, providerPos);
+            }
+        }
+    }
+}

Propchange: webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/common/KerberosServiceStarter.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Copied: webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/dom/KerberosTest.java (from r1415303, webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/ws/security/dom/message/token/KerberosTest.java)
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/dom/KerberosTest.java?p2=webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/dom/KerberosTest.java&p1=webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/ws/security/dom/message/token/KerberosTest.java&r1=1415303&r2=1416670&rev=1416670&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/ws/security/dom/message/token/KerberosTest.java (original)
+++ webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/dom/KerberosTest.java Mon Dec  3 21:26:13 2012
@@ -17,7 +17,7 @@
  * under the License.
  */
 
-package org.apache.ws.security.dom.message.token;
+package org.apache.ws.security.integration.test.dom;
 
 import org.apache.ws.security.dom.WSSConfig;
 import org.apache.ws.security.dom.WSSecurityEngine;
@@ -29,54 +29,100 @@ import org.apache.ws.security.common.uti
 import org.apache.ws.security.dom.message.WSSecEncrypt;
 import org.apache.ws.security.dom.message.WSSecHeader;
 import org.apache.ws.security.dom.message.WSSecSignature;
+import org.apache.ws.security.dom.message.token.BinarySecurity;
+import org.apache.ws.security.dom.message.token.KerberosSecurity;
 import org.apache.ws.security.dom.spnego.SpnegoTokenContext;
 import org.apache.ws.security.dom.util.WSSecurityUtil;
-// import org.apache.ws.security.dom.validate.KerberosTokenDecoderImpl;
 import org.apache.ws.security.dom.validate.KerberosTokenValidator;
+import org.apache.ws.security.integration.test.common.KerberosServiceStarter;
 import org.apache.xml.security.utils.Base64;
+import org.testng.Assert;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
 import org.w3c.dom.Document;
 
+import java.io.File;
+import java.io.IOException;
 import java.security.Principal;
 import java.util.List;
 
 import javax.crypto.SecretKey;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
 import javax.security.auth.kerberos.KerberosPrincipal;
 import javax.xml.crypto.dsig.SignatureMethod;
 
+
 /**
  * This is a test for a WSS4J client retrieving a service ticket from a KDC, and inserting
- * it into the security header of a request, to be processed by WSS4J. The tests are @Ignored by
- * default, as a KDC is needed. To replicate the test scenario, set up a KDC with user principal
- * "alice" (keytab in "/etc/alice.keytab"), and host service "bob@service.ws.apache.org" 
- * (keytab in "/etc/bob.keytab").
- * The test can be run with:
- * 
- * mvn -Djava.security.auth.login.config=src/test/resources/kerberos.jaas test -Dtest=KerberosTest
- * 
+ * it into the security header of a request, to be processed by WSS4J.
  * To see the Kerberos stuff add "-Dsun.security.krb5.debug=true".
  */
-public class KerberosTest extends org.junit.Assert {
+public class KerberosTest {
     private static final org.apache.commons.logging.Log LOG = 
         org.apache.commons.logging.LogFactory.getLog(KerberosTest.class);
-    
-    public KerberosTest() throws Exception {
+
+    private static boolean kerberosServerStarted = false;
+
+    @BeforeClass
+    public static void setUp() throws Exception {
+
         WSSConfig.init();
+
+        kerberosServerStarted = KerberosServiceStarter.startKerberosServer();
+
+        String basedir = System.getProperty("basedir");
+        if (basedir == null) {
+            basedir = new File(".").getCanonicalPath();
+        } else {
+            basedir += "/..";
+        }
+
+        //System.setProperty("sun.security.krb5.debug", "true");
+        System.setProperty("java.security.auth.login.config", basedir + "/integration/src/test/resources/kerberos/kerberos.jaas");
+        System.setProperty("java.security.krb5.conf", basedir + "/integration/src/test/resources/kerberos/krb5.conf");
+
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception {
+        if (kerberosServerStarted) {
+            KerberosServiceStarter.stopKerberosServer();
+        }
     }
 
     /**
      * Test using the KerberosSecurity class to retrieve a service ticket from a KDC, wrap it
      * in a BinarySecurityToken, and process it.
      */
-    @org.junit.Test
-    @org.junit.Ignore
+    @Test
     public void testKerberosCreationAndProcessing() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
 
         WSSecHeader secHeader = new WSSecHeader();
         secHeader.insertSecurityHeader(doc);
         
         KerberosSecurity bst = new KerberosSecurity(doc);
-        bst.retrieveServiceTicket("alice", null, "bob@service.ws.apache.org");
+        CallbackHandler callbackHandler = new CallbackHandler() {
+            @Override
+            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                PasswordCallback passwordCallback = (PasswordCallback)callbacks[0];
+                if (passwordCallback.getPrompt().contains("alice")) {
+                    passwordCallback.setPassword("alice".toCharArray());
+                } else if (passwordCallback.getPrompt().contains("bob")) {
+                    passwordCallback.setPassword("bob".toCharArray());
+                }
+            }
+        };
+        bst.retrieveServiceTicket("alice", callbackHandler, "bob@service.ws.apache.org");
         WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement());
         
         if (LOG.isDebugEnabled()) {
@@ -93,65 +139,96 @@ public class KerberosTest extends org.ju
         wssConfig.setValidator(WSSecurityEngine.BINARY_TOKEN, validator);
         WSSecurityEngine secEngine = new WSSecurityEngine();
         secEngine.setWssConfig(wssConfig);
-        
-        List<WSSecurityEngineResult> results = 
-            secEngine.processSecurityHeader(doc, null, null, null);
+
+        List<WSSecurityEngineResult> results =
+            secEngine.processSecurityHeader(doc, null, callbackHandler, null);
         WSSecurityEngineResult actionResult =
             WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
         BinarySecurity token =
             (BinarySecurity)actionResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
-        assertTrue(token != null);
+        Assert.assertTrue(token != null);
         
         Principal principal = (Principal)actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
-        assertTrue(principal instanceof KerberosPrincipal);
-        assertTrue(principal.getName().contains("alice"));
+        Assert.assertTrue(principal instanceof KerberosPrincipal);
+        Assert.assertTrue(principal.getName().contains("alice"));
     }
     
     /**
      * Get and validate a SPNEGO token.
      */
-    @org.junit.Test
-    @org.junit.Ignore
+    @Test
     public void testSpnego() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
 
         WSSecHeader secHeader = new WSSecHeader();
         secHeader.insertSecurityHeader(doc);
         
         SpnegoTokenContext spnegoToken = new SpnegoTokenContext();
-        spnegoToken.retrieveServiceTicket("alice", null, "bob@service.ws.apache.org");
+        CallbackHandler callbackHandler = new CallbackHandler() {
+            @Override
+            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                PasswordCallback passwordCallback = (PasswordCallback)callbacks[0];
+                if (passwordCallback.getPrompt().contains("alice")) {
+                    passwordCallback.setPassword("alice".toCharArray());
+                } else if (passwordCallback.getPrompt().contains("bob")) {
+                    passwordCallback.setPassword("bob".toCharArray());
+                }
+            }
+        };
+        spnegoToken.retrieveServiceTicket("alice", callbackHandler, "bob@service.ws.apache.org");
         
         byte[] token = spnegoToken.getToken();
-        assertNotNull(token);
+        Assert.assertNotNull(token);
         
         spnegoToken = new SpnegoTokenContext();
-        spnegoToken.validateServiceTicket("bob", null, "bob@service.ws.apache.org", token);
-        assertTrue(spnegoToken.isEstablished());
+        spnegoToken.validateServiceTicket("bob", callbackHandler, "bob@service.ws.apache.org", token);
+        Assert.assertTrue(spnegoToken.isEstablished());
     }
     
     /**
      * Various unit tests for a kerberos client
      */
-    @org.junit.Test
-    @org.junit.Ignore
+    @Test
     public void testKerberosClient() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
-        
+
+        CallbackHandler callbackHandler = new CallbackHandler() {
+            @Override
+            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                PasswordCallback passwordCallback = (PasswordCallback)callbacks[0];
+                if (passwordCallback.getPrompt().contains("alice")) {
+                    passwordCallback.setPassword("alice".toCharArray());
+                } else if (passwordCallback.getPrompt().contains("bob")) {
+                    passwordCallback.setPassword("bob".toCharArray());
+                }
+            }
+        };
+
         try {
             KerberosSecurity bst = new KerberosSecurity(doc);
-            bst.retrieveServiceTicket("alice2", null, "bob@service");
-            fail("Failure expected on an unknown user");
+            bst.retrieveServiceTicket("alice2", callbackHandler, "bob@service");
+            Assert.fail("Failure expected on an unknown user");
         } catch (WSSecurityException ex) {
-            // expected
+            Assert.assertEquals(ex.getMessage(), "An error occurred in trying to obtain a TGT: No LoginModules configured for alice2");
         }
         
         
         try {
             KerberosSecurity bst = new KerberosSecurity(doc);
-            bst.retrieveServiceTicket("alice", null, "bob2@service");
-            fail("Failure expected on an unknown user");
+            bst.retrieveServiceTicket("alice", callbackHandler, "bob2@service");
+            Assert.fail("Failure expected on an unknown user");
         } catch (WSSecurityException ex) {
-            // expected
+            Assert.assertEquals(ex.getMessage(), "An error occurred in trying to obtain a service ticket");
         }
         
     }
@@ -160,16 +237,33 @@ public class KerberosTest extends org.ju
      * Test using the KerberosSecurity class to retrieve a service ticket from a KDC, wrap it
      * in a BinarySecurityToken, and use the session key to sign the SOAP Body.
      */
-    @org.junit.Test
-    @org.junit.Ignore
+    @Test
     public void testKerberosSignature() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
 
         WSSecHeader secHeader = new WSSecHeader();
         secHeader.insertSecurityHeader(doc);
         
         KerberosSecurity bst = new KerberosSecurity(doc);
-        bst.retrieveServiceTicket("alice", null, "bob@service.ws.apache.org");
+        CallbackHandler callbackHandler = new CallbackHandler() {
+            @Override
+            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                if (callbacks[0] instanceof PasswordCallback) {
+                    PasswordCallback passwordCallback = (PasswordCallback)callbacks[0];
+                    if (passwordCallback.getPrompt().contains("alice")) {
+                        passwordCallback.setPassword("alice".toCharArray());
+                    } else if (passwordCallback.getPrompt().contains("bob")) {
+                        passwordCallback.setPassword("bob".toCharArray());
+                    }
+                }
+            }
+        };
+        bst.retrieveServiceTicket("alice", callbackHandler, "bob@service.ws.apache.org");
         bst.setID("Id-" + bst.hashCode());
         WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement());
         
@@ -195,22 +289,21 @@ public class KerberosTest extends org.ju
         KerberosTokenValidator validator = new KerberosTokenValidator();
         validator.setContextName("bob");
         validator.setServiceName("bob@service.ws.apache.org");
-        // validator.setKerberosTokenDecoder(new KerberosTokenDecoderImpl());
         wssConfig.setValidator(WSSecurityEngine.BINARY_TOKEN, validator);
         WSSecurityEngine secEngine = new WSSecurityEngine();
         secEngine.setWssConfig(wssConfig);
         
         List<WSSecurityEngineResult> results = 
-            secEngine.processSecurityHeader(doc, null, null, null);
+            secEngine.processSecurityHeader(doc, null, callbackHandler, null);
         WSSecurityEngineResult actionResult =
             WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
         BinarySecurity token =
             (BinarySecurity)actionResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
-        assertTrue(token != null);
+        Assert.assertTrue(token != null);
         
         Principal principal = (Principal)actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
-        assertTrue(principal instanceof KerberosPrincipal);
-        assertTrue(principal.getName().contains("alice"));
+        Assert.assertTrue(principal instanceof KerberosPrincipal);
+        Assert.assertTrue(principal.getName().contains("alice"));
     }
     
     
@@ -218,16 +311,33 @@ public class KerberosTest extends org.ju
      * Test using the KerberosSecurity class to retrieve a service ticket from a KDC, wrap it
      * in a BinarySecurityToken, and use the session key to sign the SOAP Body.
      */
-    @org.junit.Test
-    @org.junit.Ignore
+    @Test
     public void testKerberosSignatureKI() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
 
         WSSecHeader secHeader = new WSSecHeader();
         secHeader.insertSecurityHeader(doc);
         
         KerberosSecurity bst = new KerberosSecurity(doc);
-        bst.retrieveServiceTicket("alice", null, "bob@service.ws.apache.org");
+        CallbackHandler callbackHandler = new CallbackHandler() {
+            @Override
+            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                if (callbacks[0] instanceof PasswordCallback) {
+                    PasswordCallback passwordCallback = (PasswordCallback)callbacks[0];
+                    if (passwordCallback.getPrompt().contains("alice")) {
+                        passwordCallback.setPassword("alice".toCharArray());
+                    } else if (passwordCallback.getPrompt().contains("bob")) {
+                        passwordCallback.setPassword("bob".toCharArray());
+                    }
+                }
+            }
+        };
+        bst.retrieveServiceTicket("alice", callbackHandler, "bob@service.ws.apache.org");
         bst.setID("Id-" + bst.hashCode());
         
         WSSecSignature sign = new WSSecSignature();
@@ -257,22 +367,21 @@ public class KerberosTest extends org.ju
         KerberosTokenValidator validator = new KerberosTokenValidator();
         validator.setContextName("bob");
         validator.setServiceName("bob@service.ws.apache.org");
-        // validator.setKerberosTokenDecoder(new KerberosTokenDecoderImpl());
         wssConfig.setValidator(WSSecurityEngine.BINARY_TOKEN, validator);
         WSSecurityEngine secEngine = new WSSecurityEngine();
         secEngine.setWssConfig(wssConfig);
         
         List<WSSecurityEngineResult> results = 
-            secEngine.processSecurityHeader(doc, null, null, null);
+            secEngine.processSecurityHeader(doc, null, callbackHandler, null);
         WSSecurityEngineResult actionResult =
             WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
         BinarySecurity token =
             (BinarySecurity)actionResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
-        assertTrue(token != null);
+        Assert.assertTrue(token != null);
         
         Principal principal = (Principal)actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
-        assertTrue(principal instanceof KerberosPrincipal);
-        assertTrue(principal.getName().contains("alice"));
+        Assert.assertTrue(principal instanceof KerberosPrincipal);
+        Assert.assertTrue(principal.getName().contains("alice"));
     }
     
     
@@ -280,16 +389,33 @@ public class KerberosTest extends org.ju
      * Test using the KerberosSecurity class to retrieve a service ticket from a KDC, wrap it
      * in a BinarySecurityToken, and use the session key to encrypt the SOAP Body.
      */
-    @org.junit.Test
-    @org.junit.Ignore
+    @Test
     public void testKerberosEncryption() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
 
         WSSecHeader secHeader = new WSSecHeader();
         secHeader.insertSecurityHeader(doc);
         
         KerberosSecurity bst = new KerberosSecurity(doc);
-        bst.retrieveServiceTicket("alice", null, "bob@service.ws.apache.org");
+        CallbackHandler callbackHandler = new CallbackHandler() {
+            @Override
+            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                if (callbacks[0] instanceof PasswordCallback) {
+                    PasswordCallback passwordCallback = (PasswordCallback)callbacks[0];
+                    if (passwordCallback.getPrompt().contains("alice")) {
+                        passwordCallback.setPassword("alice".toCharArray());
+                    } else if (passwordCallback.getPrompt().contains("bob")) {
+                        passwordCallback.setPassword("bob".toCharArray());
+                    }
+                }
+            }
+        };
+        bst.retrieveServiceTicket("alice", callbackHandler, "bob@service.ws.apache.org");
         bst.setID("Id-" + bst.hashCode());
         WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement());
         
@@ -314,38 +440,54 @@ public class KerberosTest extends org.ju
         KerberosTokenValidator validator = new KerberosTokenValidator();
         validator.setContextName("bob");
         validator.setServiceName("bob@service.ws.apache.org");
-        // validator.setKerberosTokenDecoder(new KerberosTokenDecoderImpl());
         wssConfig.setValidator(WSSecurityEngine.BINARY_TOKEN, validator);
         WSSecurityEngine secEngine = new WSSecurityEngine();
         secEngine.setWssConfig(wssConfig);
         
         List<WSSecurityEngineResult> results = 
-            secEngine.processSecurityHeader(encryptedDoc, null, null, null);
+            secEngine.processSecurityHeader(encryptedDoc, null, callbackHandler, null);
         WSSecurityEngineResult actionResult =
             WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
         BinarySecurity token =
             (BinarySecurity)actionResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
-        assertTrue(token != null);
+        Assert.assertTrue(token != null);
         
         Principal principal = (Principal)actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
-        assertTrue(principal instanceof KerberosPrincipal);
-        assertTrue(principal.getName().contains("alice"));
+        Assert.assertTrue(principal instanceof KerberosPrincipal);
+        Assert.assertTrue(principal.getName().contains("alice"));
     }
     
     /**
      * Test using the KerberosSecurity class to retrieve a service ticket from a KDC, wrap it
      * in a BinarySecurityToken, and use the session key to encrypt the SOAP Body.
      */
-    @org.junit.Test
-    @org.junit.Ignore
+    @Test
     public void testKerberosEncryptionBSTFirst() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
 
         WSSecHeader secHeader = new WSSecHeader();
         secHeader.insertSecurityHeader(doc);
         
         KerberosSecurity bst = new KerberosSecurity(doc);
-        bst.retrieveServiceTicket("alice", null, "bob@service.ws.apache.org");
+        CallbackHandler callbackHandler = new CallbackHandler() {
+            @Override
+            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                if (callbacks[0] instanceof PasswordCallback) {
+                    PasswordCallback passwordCallback = (PasswordCallback)callbacks[0];
+                    if (passwordCallback.getPrompt().contains("alice")) {
+                        passwordCallback.setPassword("alice".toCharArray());
+                    } else if (passwordCallback.getPrompt().contains("bob")) {
+                        passwordCallback.setPassword("bob".toCharArray());
+                    }
+                }
+            }
+        };
+        bst.retrieveServiceTicket("alice", callbackHandler, "bob@service.ws.apache.org");
         bst.setID("Id-" + bst.hashCode());
         
         WSSecEncrypt builder = new WSSecEncrypt();
@@ -371,38 +513,54 @@ public class KerberosTest extends org.ju
         KerberosTokenValidator validator = new KerberosTokenValidator();
         validator.setContextName("bob");
         validator.setServiceName("bob@service.ws.apache.org");
-        // validator.setKerberosTokenDecoder(new KerberosTokenDecoderImpl());
         wssConfig.setValidator(WSSecurityEngine.BINARY_TOKEN, validator);
         WSSecurityEngine secEngine = new WSSecurityEngine();
         secEngine.setWssConfig(wssConfig);
         
         List<WSSecurityEngineResult> results = 
-            secEngine.processSecurityHeader(encryptedDoc, null, null, null);
+            secEngine.processSecurityHeader(encryptedDoc, null, callbackHandler, null);
         WSSecurityEngineResult actionResult =
             WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
         BinarySecurity token =
             (BinarySecurity)actionResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
-        assertTrue(token != null);
+        Assert.assertTrue(token != null);
         
         Principal principal = (Principal)actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
-        assertTrue(principal instanceof KerberosPrincipal);
-        assertTrue(principal.getName().contains("alice"));
+        Assert.assertTrue(principal instanceof KerberosPrincipal);
+        Assert.assertTrue(principal.getName().contains("alice"));
     }
     
     /**
      * Test using the KerberosSecurity class to retrieve a service ticket from a KDC, wrap it
      * in a BinarySecurityToken, and use the session key to encrypt the SOAP Body.
      */
-    @org.junit.Test
-    @org.junit.Ignore
+    @Test
     public void testKerberosEncryptionKI() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
 
         WSSecHeader secHeader = new WSSecHeader();
         secHeader.insertSecurityHeader(doc);
         
         KerberosSecurity bst = new KerberosSecurity(doc);
-        bst.retrieveServiceTicket("alice", null, "bob@service.ws.apache.org");
+        CallbackHandler callbackHandler = new CallbackHandler() {
+            @Override
+            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                if (callbacks[0] instanceof PasswordCallback) {
+                    PasswordCallback passwordCallback = (PasswordCallback)callbacks[0];
+                    if (passwordCallback.getPrompt().contains("alice")) {
+                        passwordCallback.setPassword("alice".toCharArray());
+                    } else if (passwordCallback.getPrompt().contains("bob")) {
+                        passwordCallback.setPassword("bob".toCharArray());
+                    }
+                }
+            }
+        };
+        bst.retrieveServiceTicket("alice", callbackHandler, "bob@service.ws.apache.org");
         bst.setID("Id-" + bst.hashCode());
         
         WSSecEncrypt builder = new WSSecEncrypt();
@@ -430,24 +588,20 @@ public class KerberosTest extends org.ju
         KerberosTokenValidator validator = new KerberosTokenValidator();
         validator.setContextName("bob");
         validator.setServiceName("bob@service.ws.apache.org");
-        // validator.setKerberosTokenDecoder(new KerberosTokenDecoderImpl());
         wssConfig.setValidator(WSSecurityEngine.BINARY_TOKEN, validator);
         WSSecurityEngine secEngine = new WSSecurityEngine();
         secEngine.setWssConfig(wssConfig);
         
         List<WSSecurityEngineResult> results = 
-            secEngine.processSecurityHeader(encryptedDoc, null, null, null);
+            secEngine.processSecurityHeader(encryptedDoc, null, callbackHandler, null);
         WSSecurityEngineResult actionResult =
             WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
         BinarySecurity token =
             (BinarySecurity)actionResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
-        assertTrue(token != null);
+        Assert.assertTrue(token != null);
         
         Principal principal = (Principal)actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
-        assertTrue(principal instanceof KerberosPrincipal);
-        assertTrue(principal.getName().contains("alice"));
-    
+        Assert.assertTrue(principal instanceof KerberosPrincipal);
+        Assert.assertTrue(principal.getName().contains("alice"));
     }
-    
-    
 }

Added: webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/stax/KerberosTest.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/stax/KerberosTest.java?rev=1416670&view=auto
==============================================================================
--- webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/stax/KerberosTest.java (added)
+++ webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/stax/KerberosTest.java Mon Dec  3 21:26:13 2012
@@ -0,0 +1,634 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.ws.security.integration.test.stax;
+
+import org.apache.ws.security.common.kerberos.KerberosContextAndServiceNameCallback;
+import org.apache.ws.security.dom.WSConstants;
+import org.apache.ws.security.dom.WSSConfig;
+import org.apache.ws.security.dom.WSSecurityEngine;
+import org.apache.ws.security.dom.WSSecurityEngineResult;
+import org.apache.ws.security.dom.message.WSSecEncrypt;
+import org.apache.ws.security.dom.message.WSSecHeader;
+import org.apache.ws.security.dom.message.WSSecSignature;
+import org.apache.ws.security.dom.message.token.BinarySecurity;
+import org.apache.ws.security.dom.message.token.KerberosSecurity;
+import org.apache.ws.security.dom.util.WSSecurityUtil;
+import org.apache.ws.security.dom.validate.KerberosTokenValidator;
+import org.apache.ws.security.integration.test.common.KerberosServiceStarter;
+import org.apache.ws.security.stax.WSSec;
+import org.apache.ws.security.stax.ext.InboundWSSec;
+import org.apache.ws.security.stax.ext.OutboundWSSec;
+import org.apache.ws.security.stax.ext.WSSConstants;
+import org.apache.ws.security.stax.ext.WSSSecurityProperties;
+import org.apache.ws.security.stax.securityEvent.KerberosTokenSecurityEvent;
+import org.apache.ws.security.stax.test.AbstractTestBase;
+import org.apache.ws.security.stax.test.utils.SOAPUtil;
+import org.apache.ws.security.stax.test.utils.StAX2DOM;
+import org.apache.ws.security.stax.test.utils.XmlReaderToWriter;
+import org.apache.xml.security.exceptions.XMLSecurityException;
+import org.apache.xml.security.stax.securityEvent.SecurityEvent;
+import org.apache.xml.security.stax.securityEvent.SecurityEventListener;
+import org.apache.xml.security.utils.Base64;
+import org.testng.Assert;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
+
+import javax.crypto.SecretKey;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.auth.kerberos.KerberosPrincipal;
+import javax.xml.crypto.dsig.SignatureMethod;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class KerberosTest extends AbstractTestBase {
+
+    private static boolean kerberosServerStarted = false;
+
+    @BeforeClass
+    public static void setUp() throws Exception {
+
+        WSSConfig.init();
+
+        kerberosServerStarted = KerberosServiceStarter.startKerberosServer();
+
+        String basedir = System.getProperty("basedir");
+        if (basedir == null) {
+            basedir = new File(".").getCanonicalPath();
+        } else {
+            basedir += "/..";
+        }
+
+        //System.setProperty("sun.security.krb5.debug", "true");
+        System.setProperty("java.security.auth.login.config", basedir + "/integration/src/test/resources/kerberos/kerberos.jaas");
+        System.setProperty("java.security.krb5.conf", basedir + "/integration/src/test/resources/kerberos/krb5.conf");
+
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception {
+        if (kerberosServerStarted) {
+            KerberosServiceStarter.stopKerberosServer();
+        }
+    }
+
+    @Test
+    public void testKerberosSignatureOutbound() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
+        Document document;
+        {
+            WSSSecurityProperties securityProperties = new WSSSecurityProperties();
+            WSSConstants.Action[] actions = new WSSConstants.Action[]{WSSConstants.SIGNATURE_WITH_KERBEROS_TOKEN};
+            securityProperties.setOutAction(actions);
+            securityProperties.setCallbackHandler(new CallbackHandler() {
+                @Override
+                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                    if (callbacks[0] instanceof KerberosContextAndServiceNameCallback) {
+                        KerberosContextAndServiceNameCallback kerberosContextAndServiceNameCallback =
+                                (KerberosContextAndServiceNameCallback) callbacks[0];
+                        kerberosContextAndServiceNameCallback.setContextName("alice");
+                        kerberosContextAndServiceNameCallback.setServiceName("bob@service.ws.apache.org");
+                    } else if (callbacks[0] instanceof PasswordCallback) {
+                        PasswordCallback passwordCallback = (PasswordCallback) callbacks[0];
+                        if (passwordCallback.getPrompt().contains("alice")) {
+                            passwordCallback.setPassword("alice".toCharArray());
+                        }
+                    }
+                }
+            });
+
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+            OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+            XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>());
+            XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+            XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+            xmlStreamWriter.close();
+
+            document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+            NodeList nodeList = document.getElementsByTagNameNS(WSSConstants.TAG_dsig_Signature.getNamespaceURI(), WSSConstants.TAG_dsig_Signature.getLocalPart());
+            Assert.assertEquals(nodeList.getLength(), 1);
+        }
+
+        //done signature; now test sig-verification:
+        {
+            // Configure the Validator
+            WSSConfig wssConfig = WSSConfig.getNewInstance();
+            KerberosTokenValidator validator = new KerberosTokenValidator();
+            validator.setContextName("bob");
+            validator.setServiceName("bob@service.ws.apache.org");
+            wssConfig.setValidator(WSSecurityEngine.BINARY_TOKEN, validator);
+            WSSecurityEngine secEngine = new WSSecurityEngine();
+            secEngine.setWssConfig(wssConfig);
+
+            CallbackHandler callbackHandler = new CallbackHandler() {
+                @Override
+                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                    if (callbacks[0] instanceof PasswordCallback) {
+                        PasswordCallback passwordCallback = (PasswordCallback) callbacks[0];
+                        if (passwordCallback.getPrompt().contains("bob")) {
+                            passwordCallback.setPassword("bob".toCharArray());
+                        }
+                    }
+                }
+            };
+
+            List<WSSecurityEngineResult> results =
+                    secEngine.processSecurityHeader(document, null, callbackHandler, null);
+            WSSecurityEngineResult actionResult =
+                    WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
+            BinarySecurity token =
+                    (BinarySecurity) actionResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
+            Assert.assertTrue(token != null);
+
+            Principal principal = (Principal) actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
+            Assert.assertTrue(principal instanceof KerberosPrincipal);
+            Assert.assertTrue(principal.getName().contains("alice"));
+        }
+    }
+
+    @Test
+    public void testKerberosSignatureInbound() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        {
+            Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+
+            WSSecHeader secHeader = new WSSecHeader();
+            secHeader.insertSecurityHeader(doc);
+
+            KerberosSecurity bst = new KerberosSecurity(doc);
+            CallbackHandler callbackHandler = new CallbackHandler() {
+                @Override
+                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                    if (callbacks[0] instanceof PasswordCallback) {
+                        PasswordCallback passwordCallback = (PasswordCallback) callbacks[0];
+                        if (passwordCallback.getPrompt().contains("alice")) {
+                            passwordCallback.setPassword("alice".toCharArray());
+                        }
+                    }
+                }
+            };
+            bst.retrieveServiceTicket("alice", callbackHandler, "bob@service.ws.apache.org");
+            bst.setID("Id-" + bst.hashCode());
+
+            WSSecSignature sign = new WSSecSignature();
+            sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);
+            sign.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
+            sign.setCustomTokenId(bst.getID());
+            sign.setCustomTokenValueType(WSConstants.WSS_GSS_KRB_V5_AP_REQ);
+
+            SecretKey secretKey = bst.getSecretKey();
+            sign.setSecretKey(secretKey.getEncoded());
+
+            sign.build(doc, null, secHeader);
+            WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement());
+
+            javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+            transformer.transform(new DOMSource(doc), new StreamResult(baos));
+        }
+
+        {
+            WSSSecurityProperties securityProperties = new WSSSecurityProperties();
+            securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+            securityProperties.setCallbackHandler(new CallbackHandler() {
+                @Override
+                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                    if (callbacks[0] instanceof PasswordCallback) {
+                        PasswordCallback passwordCallback = (PasswordCallback) callbacks[0];
+                        if (passwordCallback.getPrompt().contains("bob")) {
+                            passwordCallback.setPassword("bob".toCharArray());
+                        }
+                    } else if (callbacks[0] instanceof KerberosContextAndServiceNameCallback) {
+                        KerberosContextAndServiceNameCallback cb = (KerberosContextAndServiceNameCallback) callbacks[0];
+                        cb.setContextName("bob");
+                        cb.setServiceName("bob@service.ws.apache.org");
+                    }
+                }
+            });
+
+            final List<KerberosTokenSecurityEvent> kerberosTokenSecurityEvents = new ArrayList<KerberosTokenSecurityEvent>();
+
+            InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+            SecurityEventListener securityEventListener = new SecurityEventListener() {
+                @Override
+                public void registerSecurityEvent(SecurityEvent securityEvent) throws XMLSecurityException {
+                    if (securityEvent instanceof KerberosTokenSecurityEvent) {
+                        kerberosTokenSecurityEvents.add((KerberosTokenSecurityEvent) securityEvent);
+                    }
+                }
+            };
+            XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(
+                    new ByteArrayInputStream(baos.toByteArray())), null, securityEventListener);
+
+            Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+            //header element must still be there
+            NodeList nodeList = document.getElementsByTagNameNS(WSSConstants.TAG_dsig_Signature.getNamespaceURI(), WSSConstants.TAG_dsig_Signature.getLocalPart());
+            Assert.assertEquals(nodeList.getLength(), 1);
+            Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), WSSConstants.TAG_wsse_Security.getLocalPart());
+
+            Assert.assertEquals(1, kerberosTokenSecurityEvents.size());
+        }
+    }
+
+    @Test
+    public void testKerberosSignatureKIInbound() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        {
+            Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+
+            WSSecHeader secHeader = new WSSecHeader();
+            secHeader.insertSecurityHeader(doc);
+
+            KerberosSecurity bst = new KerberosSecurity(doc);
+            CallbackHandler callbackHandler = new CallbackHandler() {
+                @Override
+                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                    if (callbacks[0] instanceof PasswordCallback) {
+                        PasswordCallback passwordCallback = (PasswordCallback) callbacks[0];
+                        if (passwordCallback.getPrompt().contains("alice")) {
+                            passwordCallback.setPassword("alice".toCharArray());
+                        }
+                    }
+                }
+            };
+            bst.retrieveServiceTicket("alice", callbackHandler, "bob@service.ws.apache.org");
+            bst.setID("Id-" + bst.hashCode());
+
+            WSSecSignature sign = new WSSecSignature();
+            sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);
+            sign.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
+            sign.setCustomTokenValueType(WSConstants.WSS_KRB_KI_VALUE_TYPE);
+
+            SecretKey secretKey = bst.getSecretKey();
+            byte[] keyData = secretKey.getEncoded();
+            sign.setSecretKey(keyData);
+
+            byte[] digestBytes = WSSecurityUtil.generateDigest(bst.getToken());
+            sign.setCustomTokenId(Base64.encode(digestBytes));
+
+            sign.build(doc, null, secHeader);
+
+            WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement());
+
+            javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+            transformer.transform(new DOMSource(doc), new StreamResult(baos));
+        }
+
+        {
+            WSSSecurityProperties securityProperties = new WSSSecurityProperties();
+            securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+            securityProperties.setCallbackHandler(new CallbackHandler() {
+                @Override
+                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                    if (callbacks[0] instanceof PasswordCallback) {
+                        PasswordCallback passwordCallback = (PasswordCallback) callbacks[0];
+                        if (passwordCallback.getPrompt().contains("bob")) {
+                            passwordCallback.setPassword("bob".toCharArray());
+                        }
+                    } else if (callbacks[0] instanceof KerberosContextAndServiceNameCallback) {
+                        KerberosContextAndServiceNameCallback cb = (KerberosContextAndServiceNameCallback) callbacks[0];
+                        cb.setContextName("bob");
+                        cb.setServiceName("bob@service.ws.apache.org");
+                    }
+                }
+            });
+
+            final List<KerberosTokenSecurityEvent> kerberosTokenSecurityEvents = new ArrayList<KerberosTokenSecurityEvent>();
+
+            InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+            SecurityEventListener securityEventListener = new SecurityEventListener() {
+                @Override
+                public void registerSecurityEvent(SecurityEvent securityEvent) throws XMLSecurityException {
+                    if (securityEvent instanceof KerberosTokenSecurityEvent) {
+                        kerberosTokenSecurityEvents.add((KerberosTokenSecurityEvent) securityEvent);
+                    }
+                }
+            };
+            XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(
+                    new ByteArrayInputStream(baos.toByteArray())), null, securityEventListener);
+
+            Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+            //header element must still be there
+            NodeList nodeList = document.getElementsByTagNameNS(WSSConstants.TAG_dsig_Signature.getNamespaceURI(), WSSConstants.TAG_dsig_Signature.getLocalPart());
+            Assert.assertEquals(nodeList.getLength(), 1);
+            Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), WSSConstants.TAG_wsse_Security.getLocalPart());
+
+            Assert.assertEquals(1, kerberosTokenSecurityEvents.size());
+        }
+    }
+
+    @Test
+    public void testKerberosEncryptionOutbound() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
+        Document document;
+        {
+            WSSSecurityProperties securityProperties = new WSSSecurityProperties();
+            WSSConstants.Action[] actions = new WSSConstants.Action[]{WSSConstants.ENCRYPT_WITH_KERBEROS_TOKEN};
+            securityProperties.setOutAction(actions);
+            securityProperties.setCallbackHandler(new CallbackHandler() {
+                @Override
+                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                    if (callbacks[0] instanceof KerberosContextAndServiceNameCallback) {
+                        KerberosContextAndServiceNameCallback kerberosContextAndServiceNameCallback =
+                                (KerberosContextAndServiceNameCallback) callbacks[0];
+                        kerberosContextAndServiceNameCallback.setContextName("alice");
+                        kerberosContextAndServiceNameCallback.setServiceName("bob@service.ws.apache.org");
+                    } else if (callbacks[0] instanceof PasswordCallback) {
+                        PasswordCallback passwordCallback = (PasswordCallback) callbacks[0];
+                        if (passwordCallback.getPrompt().contains("alice")) {
+                            passwordCallback.setPassword("alice".toCharArray());
+                        }
+                    }
+                }
+            });
+
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+            OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+            XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>());
+            XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+            XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+            xmlStreamWriter.close();
+
+            document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+            NodeList nodeList = document.getElementsByTagNameNS(WSSConstants.TAG_xenc_ReferenceList.getNamespaceURI(), WSSConstants.TAG_xenc_ReferenceList.getLocalPart());
+            Assert.assertEquals(1, nodeList.getLength());
+        }
+
+        {
+            // Configure the Validator
+            WSSConfig wssConfig = WSSConfig.getNewInstance();
+            KerberosTokenValidator validator = new KerberosTokenValidator();
+            validator.setContextName("bob");
+            validator.setServiceName("bob@service.ws.apache.org");
+            wssConfig.setValidator(WSSecurityEngine.BINARY_TOKEN, validator);
+            WSSecurityEngine secEngine = new WSSecurityEngine();
+            secEngine.setWssConfig(wssConfig);
+
+            CallbackHandler callbackHandler = new CallbackHandler() {
+                @Override
+                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                    if (callbacks[0] instanceof PasswordCallback) {
+                        PasswordCallback passwordCallback = (PasswordCallback) callbacks[0];
+                        if (passwordCallback.getPrompt().contains("bob")) {
+                            passwordCallback.setPassword("bob".toCharArray());
+                        }
+                    }
+                }
+            };
+
+            List<WSSecurityEngineResult> results =
+                    secEngine.processSecurityHeader(document, null, callbackHandler, null);
+            WSSecurityEngineResult actionResult =
+                    WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
+            BinarySecurity token =
+                    (BinarySecurity) actionResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
+            Assert.assertTrue(token != null);
+
+            Principal principal = (Principal) actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
+            Assert.assertTrue(principal instanceof KerberosPrincipal);
+            Assert.assertTrue(principal.getName().contains("alice"));
+        }
+    }
+
+    @Test
+    public void testKerberosEncryptionInbound() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        {
+            Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+
+            WSSecHeader secHeader = new WSSecHeader();
+            secHeader.insertSecurityHeader(doc);
+
+            KerberosSecurity bst = new KerberosSecurity(doc);
+            CallbackHandler callbackHandler = new CallbackHandler() {
+                @Override
+                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                    if (callbacks[0] instanceof PasswordCallback) {
+                        PasswordCallback passwordCallback = (PasswordCallback) callbacks[0];
+                        if (passwordCallback.getPrompt().contains("alice")) {
+                            passwordCallback.setPassword("alice".toCharArray());
+                        }
+                    }
+                }
+            };
+            bst.retrieveServiceTicket("alice", callbackHandler, "bob@service.ws.apache.org");
+            bst.setID("Id-" + bst.hashCode());
+
+            WSSecEncrypt builder = new WSSecEncrypt();
+            builder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+            SecretKey secretKey = bst.getSecretKey();
+            builder.setSymmetricKey(secretKey);
+            builder.setEncryptSymmKey(false);
+            builder.setCustomReferenceValue(WSConstants.WSS_GSS_KRB_V5_AP_REQ);
+            builder.setEncKeyId(bst.getID());
+            builder.build(doc, null, secHeader);
+            WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement());
+
+            javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+            transformer.transform(new DOMSource(doc), new StreamResult(baos));
+        }
+
+        {
+            WSSSecurityProperties securityProperties = new WSSSecurityProperties();
+            securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+            securityProperties.setCallbackHandler(new CallbackHandler() {
+                @Override
+                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                    if (callbacks[0] instanceof PasswordCallback) {
+                        PasswordCallback passwordCallback = (PasswordCallback) callbacks[0];
+                        if (passwordCallback.getPrompt().contains("bob")) {
+                            passwordCallback.setPassword("bob".toCharArray());
+                        }
+                    } else if (callbacks[0] instanceof KerberosContextAndServiceNameCallback) {
+                        KerberosContextAndServiceNameCallback cb = (KerberosContextAndServiceNameCallback) callbacks[0];
+                        cb.setContextName("bob");
+                        cb.setServiceName("bob@service.ws.apache.org");
+                    }
+                }
+            });
+
+            final List<KerberosTokenSecurityEvent> kerberosTokenSecurityEvents = new ArrayList<KerberosTokenSecurityEvent>();
+
+            InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+            SecurityEventListener securityEventListener = new SecurityEventListener() {
+                @Override
+                public void registerSecurityEvent(SecurityEvent securityEvent) throws XMLSecurityException {
+                    if (securityEvent instanceof KerberosTokenSecurityEvent) {
+                        kerberosTokenSecurityEvents.add((KerberosTokenSecurityEvent) securityEvent);
+                    }
+                }
+            };
+            XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(
+                    new ByteArrayInputStream(baos.toByteArray())), null, securityEventListener);
+
+            Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+            //header element must still be there
+            NodeList nodeList = document.getElementsByTagNameNS(WSSConstants.TAG_wsse_BinarySecurityToken.getNamespaceURI(), WSSConstants.TAG_wsse_BinarySecurityToken.getLocalPart());
+            Assert.assertEquals(nodeList.getLength(), 1);
+            Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), WSSConstants.TAG_wsse_Security.getLocalPart());
+
+            //no encrypted content
+            nodeList = document.getElementsByTagNameNS(WSSConstants.TAG_xenc_EncryptedData.getNamespaceURI(), WSSConstants.TAG_xenc_EncryptedData.getLocalPart());
+            Assert.assertEquals(nodeList.getLength(), 0);
+
+            Assert.assertEquals(1, kerberosTokenSecurityEvents.size());
+        }
+    }
+
+    @Test
+    public void testKerberosEncryptionKIInbound() throws Exception {
+        if (!kerberosServerStarted) {
+            System.out.println("Skipping test because kerberos server could not be started");
+            return;
+        }
+
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        {
+            Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+
+            WSSecHeader secHeader = new WSSecHeader();
+            secHeader.insertSecurityHeader(doc);
+
+            KerberosSecurity bst = new KerberosSecurity(doc);
+            CallbackHandler callbackHandler = new CallbackHandler() {
+                @Override
+                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                    if (callbacks[0] instanceof PasswordCallback) {
+                        PasswordCallback passwordCallback = (PasswordCallback) callbacks[0];
+                        if (passwordCallback.getPrompt().contains("alice")) {
+                            passwordCallback.setPassword("alice".toCharArray());
+                        }
+                    }
+                }
+            };
+            bst.retrieveServiceTicket("alice", callbackHandler, "bob@service.ws.apache.org");
+            bst.setID("Id-" + bst.hashCode());
+
+            WSSecEncrypt builder = new WSSecEncrypt();
+            builder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+            SecretKey secretKey = bst.getSecretKey();
+            builder.setSymmetricKey(secretKey);
+            builder.setEncryptSymmKey(false);
+            builder.setCustomReferenceValue(WSConstants.WSS_KRB_KI_VALUE_TYPE);
+
+            byte[] digestBytes = WSSecurityUtil.generateDigest(bst.getToken());
+            builder.setEncKeyId(Base64.encode(digestBytes));
+
+            builder.build(doc, null, secHeader);
+
+            WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement());
+
+            javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+            transformer.transform(new DOMSource(doc), new StreamResult(baos));
+
+        }
+
+        {
+            WSSSecurityProperties securityProperties = new WSSSecurityProperties();
+            securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+            securityProperties.setCallbackHandler(new CallbackHandler() {
+                @Override
+                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+                    if (callbacks[0] instanceof PasswordCallback) {
+                        PasswordCallback passwordCallback = (PasswordCallback) callbacks[0];
+                        if (passwordCallback.getPrompt().contains("bob")) {
+                            passwordCallback.setPassword("bob".toCharArray());
+                        }
+                    } else if (callbacks[0] instanceof KerberosContextAndServiceNameCallback) {
+                        KerberosContextAndServiceNameCallback cb = (KerberosContextAndServiceNameCallback) callbacks[0];
+                        cb.setContextName("bob");
+                        cb.setServiceName("bob@service.ws.apache.org");
+                    }
+                }
+            });
+
+            final List<KerberosTokenSecurityEvent> kerberosTokenSecurityEvents = new ArrayList<KerberosTokenSecurityEvent>();
+
+            InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+            SecurityEventListener securityEventListener = new SecurityEventListener() {
+                @Override
+                public void registerSecurityEvent(SecurityEvent securityEvent) throws XMLSecurityException {
+                    if (securityEvent instanceof KerberosTokenSecurityEvent) {
+                        kerberosTokenSecurityEvents.add((KerberosTokenSecurityEvent) securityEvent);
+                    }
+                }
+            };
+            XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(
+                    new ByteArrayInputStream(baos.toByteArray())), null, securityEventListener);
+
+            Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+            //header element must still be there
+            NodeList nodeList = document.getElementsByTagNameNS(WSSConstants.TAG_wsse_BinarySecurityToken.getNamespaceURI(), WSSConstants.TAG_wsse_BinarySecurityToken.getLocalPart());
+            Assert.assertEquals(nodeList.getLength(), 1);
+            Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), WSSConstants.TAG_wsse_Security.getLocalPart());
+
+            //no encrypted content
+            nodeList = document.getElementsByTagNameNS(WSSConstants.TAG_xenc_EncryptedData.getNamespaceURI(), WSSConstants.TAG_xenc_EncryptedData.getLocalPart());
+            Assert.assertEquals(nodeList.getLength(), 0);
+
+            Assert.assertEquals(1, kerberosTokenSecurityEvents.size());
+        }
+    }
+}

Propchange: webservices/wss4j/trunk/integration/src/test/java/org/apache/ws/security/integration/test/stax/KerberosTest.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: webservices/wss4j/trunk/integration/src/test/resources/kerberos/kerberos.jaas
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/integration/src/test/resources/kerberos/kerberos.jaas?rev=1416670&view=auto
==============================================================================
--- webservices/wss4j/trunk/integration/src/test/resources/kerberos/kerberos.jaas (added)
+++ webservices/wss4j/trunk/integration/src/test/resources/kerberos/kerberos.jaas Mon Dec  3 21:26:13 2012
@@ -0,0 +1,8 @@
+
+alice {
+    com.sun.security.auth.module.Krb5LoginModule required refreshKrb5Config=true useKeyTab=false principal="alice";
+};
+
+bob {
+    com.sun.security.auth.module.Krb5LoginModule required refreshKrb5Config=true useKeyTab=false storeKey=true principal="bob/service.ws.apache.org";
+};

Added: webservices/wss4j/trunk/integration/src/test/resources/kerberos/kerberos.ldif
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/integration/src/test/resources/kerberos/kerberos.ldif?rev=1416670&view=auto
==============================================================================
--- webservices/wss4j/trunk/integration/src/test/resources/kerberos/kerberos.ldif (added)
+++ webservices/wss4j/trunk/integration/src/test/resources/kerberos/kerberos.ldif Mon Dec  3 21:26:13 2012
@@ -0,0 +1,51 @@
+dn: dc=example,dc=com
+dc: example
+objectClass: top
+objectClass: domain
+
+dn: ou=users,dc=example,dc=com
+objectClass: organizationalUnit
+objectClass: top
+ou: users
+
+# Web server identity/service principal.
+dn: uid=bob,ou=users,dc=example,dc=com
+objectclass: top
+objectclass: person
+objectclass: inetOrgPerson
+objectclass: krb5Principal
+objectclass: krb5KDCEntry
+cn: bob
+sn: bob
+uid: bob
+userpassword: bob
+krb5PrincipalName: bob/service.ws.apache.org@service.ws.apache.org
+krb5KeyVersionNumber: 0
+
+# User / client principal.
+dn: uid=alice,ou=users,dc=example,dc=com
+objectclass: top
+objectclass: person
+objectclass: inetOrgPerson
+objectclass: krb5Principal
+objectclass: krb5KDCEntry
+cn: alice
+sn: alice
+uid: alice
+userpassword: alice
+krb5PrincipalName: alice@service.ws.apache.org
+krb5KeyVersionNumber: 0
+
+# Ticket Granting Service.
+dn: uid=krbtgt,ou=users,dc=example,dc=com
+objectclass: top
+objectclass: person
+objectclass: inetOrgPerson
+objectclass: krb5Principal
+objectclass: krb5KDCEntry
+cn: KDC Service
+sn: KDC Service
+uid: krbtgt
+userpassword: randomKey
+krb5PrincipalName: krbtgt/service.ws.apache.org@service.ws.apache.org
+krb5KeyVersionNumber: 0
\ No newline at end of file

Added: webservices/wss4j/trunk/integration/src/test/resources/kerberos/krb5.conf
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/integration/src/test/resources/kerberos/krb5.conf?rev=1416670&view=auto
==============================================================================
--- webservices/wss4j/trunk/integration/src/test/resources/kerberos/krb5.conf (added)
+++ webservices/wss4j/trunk/integration/src/test/resources/kerberos/krb5.conf Mon Dec  3 21:26:13 2012
@@ -0,0 +1,7 @@
+[libdefaults]
+	default_realm = service.ws.apache.org
+
+[realms]
+	service.ws.apache.org = {
+		kdc = localhost:23749
+	}
\ No newline at end of file

Added: webservices/wss4j/trunk/integration/src/test/resources/log4j.xml
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/integration/src/test/resources/log4j.xml?rev=1416670&view=auto
==============================================================================
--- webservices/wss4j/trunk/integration/src/test/resources/log4j.xml (added)
+++ webservices/wss4j/trunk/integration/src/test/resources/log4j.xml Mon Dec  3 21:26:13 2012
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
+<log4j:configuration debug="false" xmlns:log4j="http://jakarta.apache.org/log4j/">
+    <appender name="FILE" class="org.apache.log4j.FileAppender">
+        <param name="File" value="target/logging.log"/>
+        <layout class="org.apache.log4j.PatternLayout">
+            <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/>
+        </layout>
+    </appender>
+    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
+        <layout class="org.apache.log4j.PatternLayout">
+            <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/>
+        </layout>
+    </appender>
+    <logger name="org.apache.ws.security">
+        <level value="INFO"/>
+    </logger>
+    <root>
+        <level value="INFO"/>
+        <appender-ref ref="FILE"/>
+        <!--<appender-ref ref="STDOUT"/>-->
+    </root>
+</log4j:configuration>

Propchange: webservices/wss4j/trunk/integration/src/test/resources/log4j.xml
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision