FileDocCategorySizeDatePackage
SamlCallbackHandler.javaAPI DocExample37012Tue May 29 17:14:08 BST 2007xwss.s11.server

SamlCallbackHandler

public class SamlCallbackHandler extends Object implements CallbackHandler

Fields Summary
private String
keyStoreURL
private String
keyStorePassword
private String
keyStoreType
private String
trustStoreURL
private String
trustStorePassword
private String
trustStoreType
private KeyStore
keyStore
private KeyStore
trustStore
private static final String
fileSeparator
private UnsupportedCallbackException
unsupported
private static Element
svAssertion
private static Element
svAssertion20
private static Element
hokAssertion
private static Element
hokAssertion20
public static final String
holderOfKeyConfirmation
public static final String
senderVouchesConfirmation
public static final String
holderOfKeyConfirmation_saml20
public static final String
senderVouchesConfirmation_saml20
String
home
Constructors Summary
public SamlCallbackHandler()




      

        try {

            Properties properties = new Properties();



			setContainerHome();

            String clientPropsFile = home + fileSeparator + "xws-security" + fileSeparator + "etc" + fileSeparator + "client-security-env.properties";

   	        properties.load(new FileInputStream(clientPropsFile));

                                                                                                                                                             

                                                                                                                                                             

            this.keyStoreURL = home + properties.getProperty("keystore.url");

            this.keyStoreType = properties.getProperty("keystore.type");

            this.keyStorePassword = properties.getProperty("keystore.password");

                                                                                                                                                             

            this.trustStoreURL = home + properties.getProperty("truststore.url");

            this.trustStoreType = properties.getProperty("truststore.type");

            this.trustStorePassword = properties.getProperty("truststore.password");         

 

            initKeyStore();

            initTrustStore();			

        }catch(Exception e) {

            e.printStackTrace();

            throw new RuntimeException(e);

        }

        

    
Methods Summary
private org.w3c.dom.ElementcreateHOKSAMLAssertion()


        

        Assertion assertion = null;

        try {

                             

            SAMLAssertionFactory factory = SAMLAssertionFactory.newInstance(SAMLAssertionFactory.SAML1_1);

                                                                                                

            // create the assertion id

            String assertionID = String.valueOf(System.currentTimeMillis());

            String issuer = "CN=Assertion Issuer,OU=AI,O=Assertion Issuer,L=Waltham,ST=MA,C=US";

                                                                                                                             

                                                                                                                             

            GregorianCalendar c = new GregorianCalendar();

            long beforeTime = c.getTimeInMillis();

            // roll the time by one hour

            long offsetHours = 60*60*1000;

                                                                                                                             

            c.setTimeInMillis(beforeTime - offsetHours);

            GregorianCalendar before= (GregorianCalendar)c.clone();

                                                                                                                             

            c = new GregorianCalendar();

            long afterTime = c.getTimeInMillis();

            c.setTimeInMillis(afterTime + offsetHours);

            GregorianCalendar after = (GregorianCalendar)c.clone();

                                                                                                                             

            GregorianCalendar issueInstant = new GregorianCalendar();

            // statements

            List statements = new LinkedList();

            NameIdentifier nmId =

            factory.createNameIdentifier(

            "CN=SAML User,OU=SU,O=SAML User,L=Los Angeles,ST=CA,C=US",

            null, // not sure abt this value

            "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName");           



            //default priv key cert req

            SignatureKeyCallback.DefaultPrivKeyCertRequest request =

            new SignatureKeyCallback.DefaultPrivKeyCertRequest();

            getDefaultPrivKeyCert(request);

            

            if ( request.getX509Certificate() == null ) {

                throw new RuntimeException("Not able to resolve the Default Certificate");

            }                                                                                                                 

            PublicKey pubKey = request.getX509Certificate().getPublicKey();

            PrivateKey privKey = request.getPrivateKey();



            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();



            Document doc = docFactory.newDocumentBuilder().newDocument();



            KeyInfo keyInfo = new KeyInfo(doc);

            keyInfo.addKeyValue(pubKey);



            List subConfirmation = new ArrayList();

            subConfirmation.add(holderOfKeyConfirmation);



            SubjectConfirmation scf =

            factory.createSubjectConfirmation(subConfirmation, null, keyInfo.getElement());

                                                                                                                             

                                                                                                                             

            Subject subj = factory.createSubject(nmId, scf);

                                                                                                                             

            List attributes = new LinkedList();

            List attributeValues = new LinkedList();

            attributeValues.add("ATTRIBUTE1");

            attributes.add( factory.createAttribute(

                "attribute1",

                "urn:com:sun:xml:wss:attribute",

                attributeValues));

                                                                                                                             

            statements.add(

            factory.createAttributeStatement(subj, attributes));

                                                                                                                             

            Conditions conditions = factory.createConditions(before, after, null, null, null);

                                                                                                                             

            assertion = factory.createAssertion(assertionID, issuer, issueInstant,

            conditions, null, statements);

            assertion.setMajorVersion(BigInteger.ONE);

            assertion.setMinorVersion(BigInteger.ONE);

 

            return assertion.sign(pubKey, privKey);

        } catch (Exception e) {

            e.printStackTrace();

            throw new RuntimeException(e);

        }

	
private org.w3c.dom.ElementcreateHOKSAMLAssertion20()


        

        Assertion assertion = null;

        try {

                             

            SAMLAssertionFactory factory = SAMLAssertionFactory.newInstance(SAMLAssertionFactory.SAML2_0);

                                                                                                

            // create the assertion id

            String assertionID = String.valueOf(System.currentTimeMillis());

            //String issuer = "CN=Assertion Issuer,OU=AI,O=Assertion Issuer,L=Waltham,ST=MA,C=US";



			GregorianCalendar c = new GregorianCalendar();

            long beforeTime = c.getTimeInMillis();

            // roll the time by one hour

            long offsetHours = 60*60*1000;

                                                                                                                             

            c.setTimeInMillis(beforeTime - offsetHours);

            GregorianCalendar before= (GregorianCalendar)c.clone();

                                                                                                                             

            c = new GregorianCalendar();

            long afterTime = c.getTimeInMillis();

            c.setTimeInMillis(afterTime + offsetHours);

            GregorianCalendar after = (GregorianCalendar)c.clone();

                                                                                                                             

            GregorianCalendar issueInstant = new GregorianCalendar();

            // statements

            List statements = new LinkedList();

            NameID nmId = factory.createNameID("CN=SAML User,OU=SU,O=SAML User,L=Los Angeles,ST=CA,C=US",

            null, // not sure abt this value

            "urn:oasis:names:tc:SAML:2.0:nameid-format:X509SubjectName");           



            //default priv key cert req

            SignatureKeyCallback.DefaultPrivKeyCertRequest request =

	            new SignatureKeyCallback.DefaultPrivKeyCertRequest();

            getDefaultPrivKeyCert(request);

            

            if ( request.getX509Certificate() == null ) {

                throw new RuntimeException("Not able to resolve the Default Certificate");

            }                                                                                                                 

            PublicKey pubKey = request.getX509Certificate().getPublicKey();

            PrivateKey privKey = request.getPrivateKey();



            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

            Document doc = docFactory.newDocumentBuilder().newDocument();



            KeyInfo keyInfo = new KeyInfo(doc);

            keyInfo.addKeyValue(pubKey);



            List subConfirmation = new ArrayList();

            subConfirmation.add(holderOfKeyConfirmation_saml20);

			SubjectConfirmationData scd = factory.createSubjectConfirmationData(null, null, null, null, null, keyInfo.getElement());



            SubjectConfirmation scf = factory.createSubjectConfirmation(nmId, scd, holderOfKeyConfirmation_saml20);

                                                                                                                             

                                                                                                                             

            Subject subj = factory.createSubject(nmId, scf);

                                                                                                                             

            List attributes = new LinkedList();

            List attributeValues = new LinkedList();

            attributeValues.add("ATTRIBUTE1");

            attributes.add( factory.createAttribute(

                "attribute1",

                attributeValues));

                                                                                                                             

            statements.add(factory.createAttributeStatement(attributes));

                                                                                                                             

            Conditions conditions = factory.createConditions(before, after, null, null, null);

                                                                                                                             

            assertion = factory.createAssertion(assertionID, nmId, issueInstant,

				            conditions, null, subj, statements);

            assertion.setVersion("2.0");

 

            return assertion.sign(pubKey, privKey);

        } catch (Exception e) {

            e.printStackTrace();

            throw new RuntimeException(e);

        }

        

    
private static org.w3c.dom.ElementcreateSVSAMLAssertion()


        Assertion assertion = null;

        try {

            // create the assertion id

            String assertionID = String.valueOf(System.currentTimeMillis());

            String issuer = "CN=Assertion Issuer,OU=AI,O=Assertion Issuer,L=Waltham,ST=MA,C=US";

            

            

            GregorianCalendar c = new GregorianCalendar();

            long beforeTime = c.getTimeInMillis();

            // roll the time by one hour

            long offsetHours = 60*60*1000;



            c.setTimeInMillis(beforeTime - offsetHours);

            GregorianCalendar before= (GregorianCalendar)c.clone();

            

            c = new GregorianCalendar();

            long afterTime = c.getTimeInMillis();

            c.setTimeInMillis(afterTime + offsetHours);

            GregorianCalendar after = (GregorianCalendar)c.clone();

            

            GregorianCalendar issueInstant = new GregorianCalendar();

            // statements

            List statements = new LinkedList();





            SAMLAssertionFactory factory = SAMLAssertionFactory.newInstance(SAMLAssertionFactory.SAML1_1);



            NameIdentifier nmId =

            factory.createNameIdentifier(

            "CN=SAML User,OU=SU,O=SAML User,L=Los Angeles,ST=CA,C=US",

            null, // not sure abt this value

            "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName");



            SubjectConfirmation scf =

            factory.createSubjectConfirmation("urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");

           

 

            Subject subj = factory.createSubject(nmId, scf);

           

            List attributes = new LinkedList();



            List attributeValues = new LinkedList();

            attributeValues.add("ATTRIBUTE1");

            attributes.add( factory.createAttribute(

                "attribute1",

                "urn:com:sun:xml:wss:attribute",

                 attributeValues));



            statements.add(

            factory.createAttributeStatement(subj, attributes));

            

            Conditions conditions = factory.createConditions(before, after, null, null, null);

            

            assertion = factory.createAssertion(assertionID, issuer, issueInstant,

            conditions, null, statements);

            assertion.setMajorVersion(BigInteger.ONE);

            assertion.setMinorVersion(BigInteger.ONE);

            return assertion.toElement(null);

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    
private static org.w3c.dom.ElementcreateSVSAMLAssertion20()


        Assertion assertion = null;

        try {

            // create the assertion id

            String aID = String.valueOf(System.currentTimeMillis());                        

            

            GregorianCalendar c = new GregorianCalendar();

            long beforeTime = c.getTimeInMillis();

            // roll the time by one hour

            long offsetHours = 60*60*1000;



            c.setTimeInMillis(beforeTime - offsetHours);

            GregorianCalendar before= (GregorianCalendar)c.clone();

            

            c = new GregorianCalendar();

            long afterTime = c.getTimeInMillis();

            c.setTimeInMillis(afterTime + offsetHours);

            GregorianCalendar after = (GregorianCalendar)c.clone();

            

            GregorianCalendar issueInstant = new GregorianCalendar();

            // statements

            List statements = new LinkedList();



            SAMLAssertionFactory factory = SAMLAssertionFactory.newInstance(SAMLAssertionFactory.SAML2_0);



            NameID nmId = factory.createNameID(

            "CN=SAML User,OU=SU,O=SAML User,L=Los Angeles,ST=CA,C=US",

            null, // not sure abt this value

            "urn:oasis:names:tc:SAML:2.0:nameid-format:X509SubjectName");

                        

            SubjectConfirmation scf =

            factory.createSubjectConfirmation(nmId, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches");

           

            Subject subj = factory.createSubject(nmId, scf);

           

            List attributes = new LinkedList();



            List attributeValues = new LinkedList();

            attributeValues.add("ATTRIBUTE1");

            attributes.add( factory.createAttribute(

                "attribute1", attributeValues));



            statements.add(

            factory.createAttributeStatement(attributes));

            

            Conditions conditions = factory.createConditions(before, after, null, null, null, null);

            

            assertion = factory.createAssertion(aID, nmId, issueInstant, conditions, null, subj, statements);

            assertion.setVersion("2.0");            

 

            return assertion.toElement(null);

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    
private java.security.cert.X509CertificategetCertificateFromKeyStore(java.security.PublicKey pk)


        try {

            Enumeration aliases = keyStore.aliases();

            while (aliases.hasMoreElements()) {

                String alias = (String) aliases.nextElement();

                Certificate cert = keyStore.getCertificate(alias);

                if (cert == null || !"X.509".equals(cert.getType())) {

                    continue;

                }

                X509Certificate x509Cert = (X509Certificate) cert;

                if (x509Cert.getPublicKey().equals(pk)) {

                    return x509Cert;

                }

            }

        } catch (Exception e) {

            throw new IOException(e.getMessage());

        }

        return null;

    
private java.security.cert.X509CertificategetCertificateFromTrustStore(java.security.PublicKey pk)


        try {

            Enumeration aliases = trustStore.aliases();

            while (aliases.hasMoreElements()) {

                String alias = (String) aliases.nextElement();

                Certificate cert = trustStore.getCertificate(alias);

                if (cert == null || !"X.509".equals(cert.getType())) {

                    continue;

                }

                X509Certificate x509Cert = (X509Certificate) cert;

                if (x509Cert.getPublicKey().equals(pk)) {

                    return x509Cert;

                }

            }

        } catch (Exception e) {

            throw new IOException(e.getMessage());

        }

        return null;

    
private java.lang.StringgetContainerHome()


        String _home = "";

        String fileSeparator = System.getProperty("file.separator");

        String contHome = System.getProperty("catalina.home");

        if (contHome != null) {

            String isAS = System.getProperty("com.sun.aas.instanceRoot");

            if (isAS != null) {

                _home = contHome + fileSeparator +

                        ".." + fileSeparator + "..";

            } else {

                _home = contHome;

            }

        } else {

            _home = System.getProperty("jwsdp.home");

            if (_home == null) {

                _home = System.getProperty("as.home");

            }

        }

        return _home;

    
private voidgetDefaultPrivKeyCert(SignatureKeyCallback.DefaultPrivKeyCertRequest request)


        

        String uniqueAlias = null;

        try {

            Enumeration aliases = keyStore.aliases();

            while (aliases.hasMoreElements()) {

                String currentAlias = (String) aliases.nextElement();

                if (keyStore.isKeyEntry(currentAlias)) {

                    Certificate thisCertificate = keyStore.getCertificate(currentAlias);

                    if (thisCertificate != null) {

                        if (thisCertificate instanceof X509Certificate) {

                            if (uniqueAlias == null) {

                                uniqueAlias = currentAlias;

                            } else {

                                // Not unique!

                                uniqueAlias = null;

                                break;

                            }

                        }

                    }

                }

            }

            if (uniqueAlias != null) {

                request.setX509Certificate(

                (X509Certificate) keyStore.getCertificate(uniqueAlias));

                request.setPrivateKey(

                (PrivateKey) keyStore.getKey(uniqueAlias, keyStorePassword.toCharArray()));

            }

        } catch (Exception e) {

            throw new IOException(e.getMessage());

        }

    
private static java.util.DategetFreshnessAndSkewAdjustedDate(long maxClockSkew, long timestampFreshnessLimit)


        Calendar c = new GregorianCalendar();

        long offset = c.get(Calendar.ZONE_OFFSET);

        if (c.getTimeZone().inDaylightTime(c.getTime())) {

            offset += c.getTimeZone().getDSTSavings();

        }

        long beforeTime = c.getTimeInMillis();

        long currentTime = beforeTime - offset;

        

        long adjustedTime = currentTime - maxClockSkew - timestampFreshnessLimit;

        c.setTimeInMillis(adjustedTime);

        

        return c.getTime();

    
private static java.util.DategetGMTDateWithSkewAdjusted(java.util.Calendar c, long maxClockSkew, boolean addSkew)


        long offset = c.get(Calendar.ZONE_OFFSET);

        if (c.getTimeZone().inDaylightTime(c.getTime())) {

            offset += c.getTimeZone().getDSTSavings();

        }

        long beforeTime = c.getTimeInMillis();

        long currentTime = beforeTime - offset;

        

        if (addSkew)

            currentTime = currentTime + maxClockSkew;

        else

            currentTime = currentTime - maxClockSkew;

        

        c.setTimeInMillis(currentTime);

        return c.getTime();

    
private java.security.PrivateKeygetPrivateKeyFromKeyStore(java.security.PublicKey pk)


        try {

            Enumeration aliases = keyStore.aliases();

            while (aliases.hasMoreElements()) {

                String alias = (String) aliases.nextElement();

                if (!keyStore.isKeyEntry(alias)) {

                    continue;

                } else {

                // Just returning the first one here

                PrivateKey key =(PrivateKey)keyStore.getKey(alias, "changeit".toCharArray());

                return key;

                }

            }

        } catch (Exception e) {

            throw new IOException(e.getMessage());

        }

        return null;

    
public voidhandle(javax.security.auth.callback.Callback[] callbacks)


        for (int i=0; i < callbacks.length; i++) {

            if (callbacks[i] instanceof SAMLCallback) {

				try{

					SAMLCallback samlCallback = (SAMLCallback)callbacks[i];

					if (samlCallback.getConfirmationMethod().equals(samlCallback.SV_ASSERTION_TYPE)){

						samlCallback.setAssertionElement(createSVSAMLAssertion());

						svAssertion=samlCallback.getAssertionElement();

					}else if (samlCallback.getConfirmationMethod().equals(samlCallback.HOK_ASSERTION_TYPE)){

						samlCallback.setAssertionElement(createHOKSAMLAssertion());

						//samlCallback.setAssertionElement(createHOKSAMLAssertion20());

						hokAssertion=samlCallback.getAssertionElement();

					}else{

						throw new Exception("SAML Assertion Type is not matched.");

					}

				}catch(Exception ex){

					ex.printStackTrace();

				}

            } else {

                throw unsupported;

            }

        }

    
private voidinitKeyStore()


        try {

            keyStore = KeyStore.getInstance(keyStoreType);

            keyStore.load(new FileInputStream(keyStoreURL), keyStorePassword.toCharArray());

        } catch (Exception e) {

            throw new IOException(e.getMessage());

        }

    
private voidinitTrustStore()


        try {

            trustStore = KeyStore.getInstance(trustStoreType);

            trustStore.load(new FileInputStream(trustStoreURL), trustStorePassword.toCharArray());

        } catch (Exception e) {

            throw new IOException(e.getMessage());

        }

    
public voidsetContainerHome()


        this.home = System.getProperty("WSIT_HOME");

        if (this.home == null) {

            this.home = System.getProperty("xtest.sjsas.home");

        }

        if (this.home == null) {

            this.home = System.getProperty("tomcat.home");

        }

        if (this.home == null) {

            System.out.println("WARNING: Could not locate container.home in PlugFestServerCallbackHandler");

        }

                                                                                                                                                             

    
public voidvalidateCreationTime(java.util.Date created, long maxClockSkew, long timestampFreshnessLimit)




        Date current = getFreshnessAndSkewAdjustedDate(maxClockSkew, timestampFreshnessLimit);

            

        if (created.before(current)) {

            throw new TimestampValidationCallback.TimestampValidationException(

                "The creation time is older than " +

                " currenttime - timestamp-freshness-limit - max-clock-skew");

        }

            

        Date currentTime =

            getGMTDateWithSkewAdjusted(new GregorianCalendar(), maxClockSkew, true);

        if (currentTime.before(created)) {

            throw new TimestampValidationCallback.TimestampValidationException(

                "The creation time is ahead of the current time.");

        }

    
public voidvalidateExpirationTime(java.util.Date expires, long maxClockSkew, long timestampFreshnessLimit)


                

        Date currentTime =

            getGMTDateWithSkewAdjusted(new GregorianCalendar(), maxClockSkew, false);

        if (expires.before(currentTime)) {

            throw new TimestampValidationCallback.TimestampValidationException(

                "The current time is ahead of the expiration time in Timestamp");

        }