Picketlink SVN: r798 - idm/trunk/picketlink-idm-core/src/main/java/org/picketlink/idm/impl/repository.
by picketlink-commits@lists.jboss.org
Author: bdaw
Date: 2011-03-08 02:37:27 -0500 (Tue, 08 Mar 2011)
New Revision: 798
Modified:
idm/trunk/picketlink-idm-core/src/main/java/org/picketlink/idm/impl/repository/FallbackIdentityStoreRepository.java
Log:
- more on many ldap servers support
Modified: idm/trunk/picketlink-idm-core/src/main/java/org/picketlink/idm/impl/repository/FallbackIdentityStoreRepository.java
===================================================================
--- idm/trunk/picketlink-idm-core/src/main/java/org/picketlink/idm/impl/repository/FallbackIdentityStoreRepository.java 2011-03-04 14:24:38 UTC (rev 797)
+++ idm/trunk/picketlink-idm-core/src/main/java/org/picketlink/idm/impl/repository/FallbackIdentityStoreRepository.java 2011-03-08 07:37:27 UTC (rev 798)
@@ -346,6 +346,30 @@
return resolveIdentityStore(io.getIdentityType());
}
+ /**
+ * Should return mapped store which actually contain given IdentityObject.
+ *
+ * @param io
+ * @return may return null
+ * @throws IdentityException
+ */
+ IdentityStore resolveFirstIdentityStoreWithIO(IdentityObject io, IdentityStoreInvocationContext ic) throws IdentityException
+ {
+ List<IdentityStore> mappedStores = resolveIdentityStores(io.getIdentityType());
+
+ for (IdentityStore mappedStore : mappedStores)
+ {
+ IdentityStoreInvocationContext mappedContext = resolveInvocationContext(mappedStore, ic);
+
+ if (hasIdentityObject(mappedContext, mappedStore, io))
+ {
+ return mappedStore;
+ }
+ }
+
+ return null;
+ }
+
IdentityStore resolveIdentityStore(IdentityObjectType iot)
{
@@ -810,24 +834,21 @@
boolean parent,
IdentityObjectSearchCriteria criteria) throws IdentityException
{
- // Check in the mapped store and merge with default
try
{
- //List<IdentityStore> mappedStores = resolveIdentityStores(identity.getIdentityType());
- IdentityStore mappedStore = resolveIdentityStore(identity.getIdentityType());
+ List<IdentityStore> mappedStores = resolveIdentityStores(identity.getIdentityType());
- IdentityStoreInvocationContext mappedCtx = resolveInvocationContext(mappedStore, invocationCxt);
-
IdentityStoreInvocationContext defaultCtx = resolveInvocationContext(defaultIdentityStore, invocationCxt);
- //if (mappedStores.size() == 1 && mappedStores.contains(defaultIdentityStore))
- if (mappedStore.equals(defaultIdentityStore))
+ // Maybe only default store match
+ if (mappedStores.size() == 1 && mappedStores.contains(defaultIdentityStore))
{
return defaultIdentityStore.findIdentityObject(defaultCtx, identity, relationshipType, parent, criteria);
}
+ // For the merge no paging
IdentitySearchCriteriaImpl c = null;
if (criteria != null)
@@ -838,38 +859,48 @@
Collection<IdentityObject> results = new LinkedList<IdentityObject>();
- if (hasIdentityObject(mappedCtx, mappedStore, identity)
- && (relationshipType == null
- || !RoleManagerImpl.ROLE.getName().equals(relationshipType.getName())
- || mappedStore.getSupportedFeatures().isNamedRelationshipsSupported())
- )
+ // Filter out duplicates results
+ HashSet<IdentityObject> merged = new HashSet<IdentityObject>();
+
+ for (IdentityStore mappedStore : mappedStores)
{
- // If object present in identity store then don't apply page in criteria
- if (hasIdentityObject(defaultCtx, defaultIdentityStore, identity))
+ IdentityStoreInvocationContext mappedCtx = resolveInvocationContext(mappedStore, invocationCxt);
+
+ // If object is in the store but there is no rel type provided or it is not a role
+ // So don't try to look for roles where they are not supported...
+ if (hasIdentityObject(mappedCtx, mappedStore, identity)
+ && (relationshipType == null
+ || !RoleManagerImpl.ROLE.getName().equals(relationshipType.getName())
+ || mappedStore.getSupportedFeatures().isNamedRelationshipsSupported())
+ )
{
- results = mappedStore.findIdentityObject(mappedCtx, identity, relationshipType, parent, c);
+ // If object present in identity store then don't apply page in criteria
+ if (hasIdentityObject(defaultCtx, defaultIdentityStore, identity))
+ {
+ results = mappedStore.findIdentityObject(mappedCtx, identity, relationshipType, parent, c);
+ // add with filter of duplicate
+ merged.addAll(results);
+ }
+
+ // Otherwise if there was only mapped store simply return results as it shouldn't be present
+ // in default anyway...
+ else if (mappedStores.size() == 1)
+ {
+ return mappedStore.findIdentityObject(mappedCtx, identity, relationshipType, parent, criteria);
+ }
}
- // Otherwise simply return results
- else
- {
- return mappedStore.findIdentityObject(mappedCtx, identity, relationshipType, parent, criteria);
- }
}
-
+ // So always check with default
Collection<IdentityObject> objects = defaultIdentityStore.findIdentityObject(defaultCtx, identity, relationshipType, parent, c);
// If default store contain related relationships merge and sort/page once more
if (objects != null && objects.size() != 0)
{
-
- // Filter out duplicates
- HashSet<IdentityObject> merged = new HashSet<IdentityObject>();
- merged.addAll(results);
merged.addAll(objects);
-
+ // So as things were merged criteria need to be reapplied
if (criteria != null)
{
@@ -917,17 +948,18 @@
{
try
{
- IdentityStore fromStore = resolveIdentityStore(fromIdentity);
+ IdentityStore fromStore = resolveFirstIdentityStoreWithIO(fromIdentity, invocationCxt);
- IdentityStore toStore = resolveIdentityStore(toIdentity);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(toIdentity, invocationCxt);
- IdentityStoreInvocationContext toTargetCtx = resolveInvocationContext(toStore, invocationCxt);
+ IdentityStoreInvocationContext toTargetCtx =
+ toStore != null ? resolveInvocationContext(toStore, invocationCxt): null;
IdentityStoreInvocationContext defaultTargetCtx = resolveInvocationContext(defaultIdentityStore, invocationCxt);
- if (fromStore == toStore && !isIdentityStoreReadOnly(fromStore)
- && hasIdentityObject(toTargetCtx, fromStore, fromIdentity)
- && hasIdentityObject(toTargetCtx, fromStore, toIdentity))
+ // Check if stores are not null so io exists in one of mappings.
+ if ((fromStore != null && toStore != null) &&
+ fromStore == toStore && !isIdentityStoreReadOnly(fromStore))
{
// If relationship is named and target store doesn't support named relationships it need to be put in default store anyway
if (relationshipName == null ||
@@ -963,17 +995,18 @@
{
try
{
- IdentityStore fromStore = resolveIdentityStore(fromIdentity);
+ IdentityStore fromStore = resolveFirstIdentityStoreWithIO(fromIdentity, invocationCxt);
- IdentityStore toStore = resolveIdentityStore(toIdentity);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(toIdentity, invocationCxt);
- IdentityStoreInvocationContext toTargetCtx = resolveInvocationContext(toStore, invocationCxt);
+ IdentityStoreInvocationContext toTargetCtx =
+ toStore != null ? resolveInvocationContext(toStore, invocationCxt): null;
IdentityStoreInvocationContext defaultTargetCtx = resolveInvocationContext(defaultIdentityStore, invocationCxt);
- if (fromStore == toStore && !isIdentityStoreReadOnly(fromStore)
- && hasIdentityObject(toTargetCtx, toStore, fromIdentity)
- && hasIdentityObject(toTargetCtx, toStore, toIdentity))
+ // Check if stores are not null so io exists in one of mappings.
+ if ((fromStore != null && toStore != null) &&
+ fromStore == toStore && !isIdentityStoreReadOnly(fromStore))
{
if (relationshipName == null ||
(relationshipName != null && fromStore.getSupportedFeatures().isNamedRelationshipsSupported()))
@@ -1021,18 +1054,18 @@
{
try
{
- IdentityStore fromStore = resolveIdentityStore(identity1);
+ IdentityStore fromStore = resolveFirstIdentityStoreWithIO(identity1, invocationCtx);
- IdentityStore toStore = resolveIdentityStore(identity2);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(identity2, invocationCtx);
- IdentityStoreInvocationContext toTargetCtx = resolveInvocationContext(toStore, invocationCtx);
+ IdentityStoreInvocationContext toTargetCtx =
+ toStore != null ? resolveInvocationContext(toStore, invocationCtx): null;
IdentityStoreInvocationContext defaultTargetCtx = resolveInvocationContext(defaultIdentityStore, invocationCtx);
- if (fromStore == toStore && !isIdentityStoreReadOnly(fromStore)
- && hasIdentityObject(toTargetCtx, toStore, identity1)
- && hasIdentityObject(toTargetCtx, toStore, identity2))
+ // Check if stores are not null so io exists in one of mappings.
+ if ((fromStore != null && toStore != null) && fromStore == toStore && !isIdentityStoreReadOnly(fromStore))
{
fromStore.removeRelationships(toTargetCtx, identity1, identity2, named);
return;
@@ -1068,19 +1101,20 @@
try
{
- IdentityStore fromStore = resolveIdentityStore(fromIdentity);
+ IdentityStore fromStore = resolveFirstIdentityStoreWithIO(fromIdentity, invocationCxt);
- IdentityStore toStore = resolveIdentityStore(toIdentity);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(toIdentity, invocationCxt);
- IdentityStoreInvocationContext toTargetCtx = resolveInvocationContext(toStore, invocationCxt);
+ IdentityStoreInvocationContext toTargetCtx =
+ toStore != null ? resolveInvocationContext(toStore, invocationCxt): null;
IdentityStoreInvocationContext defaultTargetCtx = resolveInvocationContext(defaultIdentityStore, invocationCxt);
- if (fromStore == toStore &&
+ // Check if stores are not null so io exists in one of mappings.
+ if ((fromStore != null && toStore != null) &&
+ fromStore == toStore &&
(!RoleManagerImpl.ROLE.getName().equals(relationshipType.getName()) ||
- fromStore.getSupportedFeatures().isNamedRelationshipsSupported())
- && hasIdentityObject(toTargetCtx, toStore, fromIdentity)
- && hasIdentityObject(toTargetCtx, toStore, toIdentity))
+ fromStore.getSupportedFeatures().isNamedRelationshipsSupported()))
{
return fromStore.resolveRelationships(toTargetCtx, fromIdentity, toIdentity, relationshipType);
@@ -1369,10 +1403,12 @@
{
try
{
- IdentityStore fromStore = resolveIdentityStore(relationship.getFromIdentityObject());
- IdentityStore toStore = resolveIdentityStore(relationship.getToIdentityObject());
+ IdentityStore fromStore = resolveFirstIdentityStoreWithIO(relationship.getFromIdentityObject(), ctx);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(relationship.getToIdentityObject(), ctx);
- if (fromStore == toStore && toStore.getSupportedFeatures().isNamedRelationshipsSupported() && !isIdentityStoreReadOnly(fromStore))
+ if (fromStore != null && toStore != null &&
+ fromStore == toStore && toStore.getSupportedFeatures().isNamedRelationshipsSupported() &&
+ !isIdentityStoreReadOnly(fromStore))
{
fromStore.setRelationshipProperties(resolveInvocationContext(fromStore, ctx), relationship, properties);
return;
@@ -1394,10 +1430,11 @@
{
try
{
- IdentityStore fromStore = resolveIdentityStore(relationship.getFromIdentityObject());
- IdentityStore toStore = resolveIdentityStore(relationship.getToIdentityObject());
+ IdentityStore fromStore = resolveFirstIdentityStoreWithIO(relationship.getFromIdentityObject(), ctx);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(relationship.getToIdentityObject(), ctx);
- if (fromStore == toStore && toStore.getSupportedFeatures().isNamedRelationshipsSupported() && !isIdentityStoreReadOnly(fromStore))
+ if (fromStore != null && toStore != null && fromStore == toStore &&
+ toStore.getSupportedFeatures().isNamedRelationshipsSupported() && !isIdentityStoreReadOnly(fromStore))
{
fromStore.removeRelationshipProperties(resolveInvocationContext(fromStore, ctx), relationship, properties);
return;
@@ -1419,15 +1456,16 @@
{
try
{
- IdentityStore toStore = resolveIdentityStore(identityObject);
- IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, ctx);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(identityObject, ctx);
- if (hasIdentityObject(targetCtx, toStore, identityObject))
+ if (toStore != null)
{
+ IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, ctx);
+
return toStore.validateCredential(targetCtx, identityObject, credential);
}
- targetCtx = resolveInvocationContext(defaultIdentityStore, ctx);
+ IdentityStoreInvocationContext targetCtx = resolveInvocationContext(defaultIdentityStore, ctx);
if (toStore != defaultIdentityStore && hasIdentityObject(targetCtx, defaultIdentityStore, identityObject))
{
@@ -1450,16 +1488,17 @@
{
try
{
- IdentityStore toStore = resolveIdentityStore(identityObject);
- IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, ctx);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(identityObject, ctx);
- if (hasIdentityObject(targetCtx, toStore, identityObject))
+ if (toStore != null)
{
+ IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, ctx);
+
toStore.updateCredential(targetCtx, identityObject, credential);
return;
}
- targetCtx = resolveInvocationContext(defaultIdentityStore, ctx);
+ IdentityStoreInvocationContext targetCtx = resolveInvocationContext(defaultIdentityStore, ctx);
if (toStore != defaultIdentityStore && hasIdentityObject(targetCtx, defaultIdentityStore, identityObject))
{
@@ -1483,6 +1522,8 @@
{
Set<String> results;
+
+ // TODO: just get the first mapped store and use... should it merge supported attrs from different mapped stores?
IdentityStore toStore = resolveIdentityStore(identityType);
IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, invocationContext);
@@ -1513,6 +1554,8 @@
try
{
+
+ // TODO: just get the first mapped store and use... should it merge supported attrs from different mapped stores?
IdentityStore targetStore = resolveIdentityStore(identityObjectType);
IdentityStoreInvocationContext targetCtx = resolveInvocationContext(targetStore, invocationContext);
@@ -1557,15 +1600,16 @@
{
IdentityObjectAttribute result = null;
- IdentityStore toStore = resolveIdentityStore(identity);
- IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, invocationContext);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(identity, invocationContext);
- if (hasIdentityObject(targetCtx, toStore, identity))
+ if (toStore != null)
{
+ IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, invocationContext);
+
result = toStore.getAttribute(targetCtx, identity, name);
}
- if (result == null && toStore != defaultAttributeStore)
+ if (result == null && (toStore == null || toStore != defaultAttributeStore))
{
IdentityStoreInvocationContext defaultCtx = resolveInvocationContext(defaultAttributeStore, invocationContext);
@@ -1590,16 +1634,16 @@
{
Map<String, IdentityObjectAttribute> results = new HashMap<String, IdentityObjectAttribute>();
- IdentityStore toStore = resolveIdentityStore(identity);
- IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, invocationContext);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(identity, invocationContext);
- if (hasIdentityObject(targetCtx, toStore, identity))
+ if (toStore != null)
{
+ IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, invocationContext);
results = toStore.getAttributes(targetCtx, identity);
}
- if (toStore != defaultAttributeStore)
+ if (toStore == null || toStore != defaultAttributeStore)
{
IdentityStoreInvocationContext defaultCtx = resolveInvocationContext(defaultAttributeStore, invocationContext);
@@ -1636,14 +1680,14 @@
IdentityObjectAttribute[] attributesToAdd = null;
- IdentityStore toStore = resolveIdentityStore(identity);
- IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, invocationCtx);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(identity, invocationCtx);
// Put supported attrs to the main store
- if (toStore != defaultAttributeStore
- && !isIdentityStoreReadOnly(toStore)
- && hasIdentityObject(targetCtx, toStore, identity))
+ if (toStore != null && toStore != defaultAttributeStore
+ && !isIdentityStoreReadOnly(toStore))
{
+ IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, invocationCtx);
+
Set<String> supportedAttrs = toStore.getSupportedAttributeNames(targetCtx, identity.getIdentityType());
// Filter out supported and not supported attributes
@@ -1714,14 +1758,16 @@
ArrayList<IdentityObjectAttribute> leftAttrs = new ArrayList<IdentityObjectAttribute>();
IdentityObjectAttribute[] attributesToAdd = null;
- IdentityStore toStore = resolveIdentityStore(identity);
- IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, invocationCtx);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(identity, invocationCtx);
// Put supported attrs to the main store
- if (toStore != defaultAttributeStore
- && !isIdentityStoreReadOnly(toStore)
- && hasIdentityObject(targetCtx, toStore, identity))
+ if (toStore != null &&
+ toStore != defaultAttributeStore
+ && !isIdentityStoreReadOnly(toStore))
{
+ IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, invocationCtx);
+
+
Set<String> supportedAttrs = toStore.getSupportedAttributeNames(targetCtx, identity.getIdentityType());
// Filter out supported and not supported attributes
@@ -1794,14 +1840,16 @@
List<String> filteredAttrs = new LinkedList<String>();
List<String> leftAttrs = new LinkedList<String>();
- IdentityStore toStore = resolveIdentityStore(identity);
- IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, invocationCtx);
+ IdentityStore toStore = resolveFirstIdentityStoreWithIO(identity, invocationCtx);
// Put supported attrs to the main store
- if (toStore != defaultAttributeStore
- && !isIdentityStoreReadOnly(toStore)
- && hasIdentityObject(targetCtx, toStore, identity))
+ if (toStore != null &&
+ toStore != defaultAttributeStore &&
+ !isIdentityStoreReadOnly(toStore))
{
+
+ IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, invocationCtx);
+
Set<String> supportedAttrs = toStore.getSupportedAttributeNames(targetCtx, identity.getIdentityType());
// Filter out supported and not supported attributes
@@ -1865,30 +1913,36 @@
{
try
{
- List<String> filteredAttrs = new LinkedList<String>();
- List<String> leftAttrs = new LinkedList<String>();
- IdentityStore toStore = resolveIdentityStore(identityObjectType);
- IdentityStoreInvocationContext targetCtx = resolveInvocationContext(toStore, invocationCtx);
+ Collection<IdentityStore> mappedStores = resolveIdentityStores(identityObjectType);
IdentityObject result = null;
- // Put supported attrs to the main store
- if (toStore != defaultAttributeStore)
+ for (IdentityStore mappedStore : mappedStores)
{
- Set<String> supportedAttrs = toStore.getSupportedAttributeNames(targetCtx, identityObjectType);
+ if (mappedStore != defaultAttributeStore)
+ {
- if (supportedAttrs.contains(attribute.getName()))
- {
- result = toStore.findIdentityObjectByUniqueAttribute(targetCtx, identityObjectType, attribute);
+ IdentityStoreInvocationContext targetCtx = resolveInvocationContext(mappedStore, invocationCtx);
+
+ Set<String> supportedAttrs = mappedStore.getSupportedAttributeNames(targetCtx, identityObjectType);
+
+ if (supportedAttrs.contains(attribute.getName()))
+ {
+ result = mappedStore.findIdentityObjectByUniqueAttribute(targetCtx, identityObjectType, attribute);
+ }
+
+ // First with any result win
+ if (result != null)
+ {
+ return result;
+ }
}
}
- if (result != null)
- {
- return result;
- }
+
+ // And if we are still here just go with default
IdentityStoreInvocationContext defaultCtx = resolveInvocationContext(defaultAttributeStore, invocationCtx);
if (isAllowNotDefinedAttributes())
@@ -1900,7 +1954,7 @@
Set<String> supportedAttrs = defaultAttributeStore.getSupportedAttributeNames(defaultCtx, identityObjectType);
if (supportedAttrs.contains(attribute.getName()))
{
- return toStore.findIdentityObjectByUniqueAttribute(defaultCtx, identityObjectType, attribute);
+ return defaultAttributeStore.findIdentityObjectByUniqueAttribute(defaultCtx, identityObjectType, attribute);
}
}
13 years, 10 months
Picketlink SVN: r795 - federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp.
by picketlink-commits@lists.jboss.org
Author: anil.saldhana(a)jboss.com
Date: 2011-03-03 12:23:51 -0500 (Thu, 03 Mar 2011)
New Revision: 795
Modified:
federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java
federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java
federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java
federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SecurityActions.java
Log:
PLFED-154: adapt to the FormAuthenticator changes that have happened due to Servlet3 spec changes
Modified: federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java
===================================================================
--- federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java 2011-03-03 15:01:17 UTC (rev 794)
+++ federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java 2011-03-03 17:23:51 UTC (rev 795)
@@ -23,7 +23,9 @@
import java.io.IOException;
import java.io.InputStream;
+import java.lang.reflect.Method;
import java.security.GeneralSecurityException;
+import java.security.Principal;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
@@ -37,10 +39,10 @@
import javax.xml.crypto.dsig.CanonicalizationMethod;
import org.apache.catalina.LifecycleException;
+import org.apache.catalina.authenticator.AuthenticatorBase;
import org.apache.catalina.authenticator.FormAuthenticator;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
-import org.apache.catalina.deploy.LoginConfig;
import org.apache.log4j.Logger;
import org.picketlink.identity.federation.api.saml.v2.metadata.MetaDataExtractor;
import org.picketlink.identity.federation.core.config.SPType;
@@ -110,6 +112,20 @@
protected String canonicalizationMethod = CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS;
+ /**
+ * Servlet3 related changes forced Tomcat to change the authenticate method
+ * signature in the FormAuthenticator. For now, we use reflection for forward
+ * compatibility. This has to be changed in future.
+ */
+ private Method theSuperRegisterMethod = null;
+
+ /**
+ * If it is determined that we are running in a Tomcat6/JBAS5 environment,
+ * there is no need to seek the super.register method that conforms to
+ * the servlet3 spec changes
+ */
+ private boolean seekSuperRegisterMethod = true;
+
public BaseFormAuthenticator()
{
super();
@@ -161,25 +177,6 @@
return request.getParameter("SAMLResponse") != null;
}
- /**
- * Authenticate the request
- * @param request
- * @param response
- * @param config
- * @return
- * @throws IOException
- * @throws {@link RuntimeException} when the response is not of type catalina response object
- */
- public boolean authenticate(Request request, HttpServletResponse response, LoginConfig config) throws IOException
- {
- if (response instanceof Response)
- {
- Response catalinaResponse = (Response) response;
- return authenticate(request, catalinaResponse, config);
- }
- throw new RuntimeException("Response was not of type catalina response");
- }
-
@Override
public void start() throws LifecycleException
{
@@ -206,6 +203,48 @@
return idpCertificate;
}
+ /**
+ * This method is a hack!!!
+ * Tomcat on account of Servlet3 changed their authenticator method signatures
+ * We utilize Java Reflection to identify the super register method on the first
+ * call and save it. Subsquent invocations utilize the saved {@link Method}
+ * @see org.apache.catalina.authenticator.AuthenticatorBase#register(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response, java.security.Principal, java.lang.String, java.lang.String, java.lang.String)
+ */
+ @Override
+ protected void register(Request request, Response response, Principal principal, String arg3, String arg4,
+ String arg5)
+ {
+ //Try the JBossAS6 version
+ if (theSuperRegisterMethod == null && seekSuperRegisterMethod)
+ {
+ Class<?>[] args = new Class[]
+ {Request.class, HttpServletResponse.class, Principal.class, String.class, String.class, String.class};
+ Class<?> superClass = getAuthenticatorBaseClass();
+ theSuperRegisterMethod = SecurityActions.getMethod(superClass, "register", args);
+ }
+ try
+ {
+ if (theSuperRegisterMethod != null)
+ {
+ Object[] callArgs = new Object[]
+ {request, response, principal, arg3, arg4, arg5};
+ theSuperRegisterMethod.invoke(this, callArgs);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException(e);
+ }
+
+ //Try the older version
+ if (theSuperRegisterMethod == null)
+ {
+ seekSuperRegisterMethod = false; //Don't try to seek super register method on next invocation
+ super.register(request, response, principal, arg3, arg4, arg5);
+ return;
+ }
+ }
+
//Mock test purpose
public void testStart() throws LifecycleException
{
@@ -410,4 +449,15 @@
chainConfigOptions.put(GeneralConstants.CANONICALIZATION_METHOD, canonicalizationMethod);
chainConfigOptions.put(GeneralConstants.ROLE_VALIDATOR_IGNORE, "false"); //No validator as tomcat realm does validn
}
+
+ private Class<?> getAuthenticatorBaseClass()
+ {
+ Class<?> myClass = getClass();
+ do
+ {
+ myClass = myClass.getSuperclass();
+ }
+ while (myClass != AuthenticatorBase.class);
+ return myClass;
+ }
}
\ No newline at end of file
Modified: federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java
===================================================================
--- federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java 2011-03-03 15:01:17 UTC (rev 794)
+++ federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java 2011-03-03 17:23:51 UTC (rev 795)
@@ -30,6 +30,7 @@
import java.util.Set;
import javax.servlet.RequestDispatcher;
+import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.Session;
import org.apache.catalina.authenticator.Constants;
@@ -95,6 +96,25 @@
jbossEnv = detector.isJboss();
}
+ /**
+ * Authenticate the request
+ * @param request
+ * @param response
+ * @param config
+ * @return
+ * @throws IOException
+ * @throws {@link RuntimeException} when the response is not of type catalina response object
+ */
+ public boolean authenticate(Request request, HttpServletResponse response, LoginConfig config) throws IOException
+ {
+ if (response instanceof Response)
+ {
+ Response catalinaResponse = (Response) response;
+ return authenticate(request, catalinaResponse, config);
+ }
+ throw new RuntimeException("Response was not of type catalina response");
+ }
+
@Override
public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
{
Modified: federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java
===================================================================
--- federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java 2011-03-03 15:01:17 UTC (rev 794)
+++ federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java 2011-03-03 17:23:51 UTC (rev 795)
@@ -33,6 +33,7 @@
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.Session;
import org.apache.catalina.authenticator.Constants;
@@ -91,6 +92,25 @@
jbossEnv = detector.isJboss();
}
+ /**
+ * Authenticate the request
+ * @param request
+ * @param response
+ * @param config
+ * @return
+ * @throws IOException
+ * @throws {@link RuntimeException} when the response is not of type catalina response object
+ */
+ public boolean authenticate(Request request, HttpServletResponse response, LoginConfig config) throws IOException
+ {
+ if (response instanceof Response)
+ {
+ Response catalinaResponse = (Response) response;
+ return authenticate(request, catalinaResponse, config);
+ }
+ throw new RuntimeException("Response was not of type catalina response");
+ }
+
@Override
public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
{
Modified: federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SecurityActions.java
===================================================================
--- federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SecurityActions.java 2011-03-03 15:01:17 UTC (rev 794)
+++ federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SecurityActions.java 2011-03-03 17:23:51 UTC (rev 795)
@@ -21,6 +21,7 @@
*/
package org.picketlink.identity.federation.bindings.tomcat.sp;
+import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
@@ -45,4 +46,30 @@
}
});
}
+
+ /**
+ * Use reflection to get the {@link Method} on a {@link Class} with the
+ * given parameter types
+ * @param clazz
+ * @param methodName
+ * @param parameterTypes
+ * @return
+ */
+ static Method getMethod(final Class<?> clazz, final String methodName, final Class<?>[] parameterTypes)
+ {
+ return AccessController.doPrivileged(new PrivilegedAction<Method>()
+ {
+ public Method run()
+ {
+ try
+ {
+ return clazz.getDeclaredMethod(methodName, parameterTypes);
+ }
+ catch (Exception e)
+ {
+ return null;
+ }
+ }
+ });
+ }
}
13 years, 10 months
Picketlink SVN: r794 - in federation/trunk: picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/interfaces and 2 other directories.
by picketlink-commits@lists.jboss.org
Author: anil.saldhana(a)jboss.com
Date: 2011-03-03 10:01:17 -0500 (Thu, 03 Mar 2011)
New Revision: 794
Modified:
federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/impl/BaseHandlerConfig.java
federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/impl/DefaultSAML2HandlerChainConfig.java
federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/interfaces/SAML2MapBasedConfig.java
federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java
federation/trunk/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/saml/handlers/SAML2AuthenticationHandlerUnitTestCase.java
federation/trunk/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/saml/handlers/SAML2SignatureHandlerUnitTestCase.java
Log:
PLFED-156: nameid format customization
Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/impl/BaseHandlerConfig.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/impl/BaseHandlerConfig.java 2011-03-03 12:52:05 UTC (rev 793)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/impl/BaseHandlerConfig.java 2011-03-03 15:01:17 UTC (rev 794)
@@ -41,7 +41,7 @@
{
return params.containsKey(key);
}
-
+
/**
* @see SAML2HandlerChainConfig#getParameter(String)
*/
@@ -50,6 +50,13 @@
return params.get(parameterName);
}
+ /**
+ * @see org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2MapBasedConfig#addParameter(java.lang.String, java.lang.Object)
+ */
+ public void addParameter(String parameterName, Object value)
+ {
+ this.params.put(parameterName, value);
+ }
public void set(Map<String, Object> options)
{
Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/impl/DefaultSAML2HandlerChainConfig.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/impl/DefaultSAML2HandlerChainConfig.java 2011-03-03 12:52:05 UTC (rev 793)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/impl/DefaultSAML2HandlerChainConfig.java 2011-03-03 15:01:17 UTC (rev 794)
@@ -30,15 +30,14 @@
* @author Anil.Saldhana(a)redhat.com
* @since Oct 10, 2009
*/
-public class DefaultSAML2HandlerChainConfig extends BaseHandlerConfig
-implements SAML2HandlerChainConfig
-{
+public class DefaultSAML2HandlerChainConfig extends BaseHandlerConfig implements SAML2HandlerChainConfig
+{
public DefaultSAML2HandlerChainConfig()
- {
+ {
}
-
- public DefaultSAML2HandlerChainConfig(Map<String,Object> map)
+
+ public DefaultSAML2HandlerChainConfig(Map<String, Object> map)
{
- this.params = map;
+ this.params.putAll(map);
}
}
\ No newline at end of file
Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/interfaces/SAML2MapBasedConfig.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/interfaces/SAML2MapBasedConfig.java 2011-03-03 12:52:05 UTC (rev 793)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/interfaces/SAML2MapBasedConfig.java 2011-03-03 15:01:17 UTC (rev 794)
@@ -35,17 +35,24 @@
* @return
*/
boolean containsKey(String key);
-
+
/**
* Get a parameter from the chain config
* @param parameterName
* @return
*/
- public Object getParameter(String parameterName);
-
+ public Object getParameter(String parameterName);
+
/**
+ * Add a parameter
+ * @param parameterName
+ * @param value
+ */
+ public void addParameter(String parameterName, Object value);
+
+ /**
* Set the options
* @param options
*/
- void set(Map<String,Object> options);
+ void set(Map<String, Object> options);
}
\ No newline at end of file
Modified: federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java
===================================================================
--- federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java 2011-03-03 12:52:05 UTC (rev 793)
+++ federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java 2011-03-03 15:01:17 UTC (rev 794)
@@ -333,7 +333,7 @@
String id = IDGenerator.create("ID_");
//Check if there is a nameid policy
- String nameIDFormat = (String) request.getOptions().get(GeneralConstants.NAMEID_FORMAT);
+ String nameIDFormat = (String) handlerConfig.getParameter(GeneralConstants.NAMEID_FORMAT);
if (StringUtil.isNotNull(nameIDFormat))
{
samlRequest.setNameIDFormat(nameIDFormat);
Modified: federation/trunk/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/saml/handlers/SAML2AuthenticationHandlerUnitTestCase.java
===================================================================
--- federation/trunk/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/saml/handlers/SAML2AuthenticationHandlerUnitTestCase.java 2011-03-03 12:52:05 UTC (rev 793)
+++ federation/trunk/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/saml/handlers/SAML2AuthenticationHandlerUnitTestCase.java 2011-03-03 15:01:17 UTC (rev 794)
@@ -88,6 +88,7 @@
SAML2HandlerChainConfig chainConfig = new DefaultSAML2HandlerChainConfig();
SAML2HandlerConfig handlerConfig = new DefaultSAML2HandlerConfig();
+ handlerConfig.addParameter(GeneralConstants.NAMEID_FORMAT, JBossSAMLURIConstants.NAMEID_FORMAT_PERSISTENT.get());
Map<String, Object> chainOptions = new HashMap<String, Object>();
SPType spType = new SPType();
@@ -116,7 +117,6 @@
SAML2HandlerRequest request = new DefaultSAML2HandlerRequest(httpContext, issuerInfo.getIssuer(), docHolder,
SAML2Handler.HANDLER_TYPE.SP);
request.setTypeOfRequestToBeGenerated(GENERATE_REQUEST_TYPE.AUTH);
- request.addOption(GeneralConstants.NAMEID_FORMAT, JBossSAMLURIConstants.NAMEID_FORMAT_PERSISTENT.get());
SAML2HandlerResponse response = new DefaultSAML2HandlerResponse();
handler.generateSAMLRequest(request, response);
Modified: federation/trunk/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/saml/handlers/SAML2SignatureHandlerUnitTestCase.java
===================================================================
--- federation/trunk/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/saml/handlers/SAML2SignatureHandlerUnitTestCase.java 2011-03-03 12:52:05 UTC (rev 793)
+++ federation/trunk/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/saml/handlers/SAML2SignatureHandlerUnitTestCase.java 2011-03-03 15:01:17 UTC (rev 794)
@@ -41,8 +41,8 @@
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerChainConfig;
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerConfig;
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerRequest;
+import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerRequest.GENERATE_REQUEST_TYPE;
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerResponse;
-import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerRequest.GENERATE_REQUEST_TYPE;
import org.picketlink.identity.federation.newmodel.saml.v2.protocol.AuthnRequestType;
import org.picketlink.identity.federation.web.constants.GeneralConstants;
import org.picketlink.identity.federation.web.core.HTTPContext;
@@ -71,60 +71,62 @@
String issuerValue = "http://sp";
AuthnRequestType authnRequest = saml2Request.createAuthnRequestType(id, assertionConsumerURL, destination,
issuerValue);
-
+
Document authDoc = saml2Request.convert(authnRequest);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
KeyPair keypair = kpg.genKeyPair();
-
+
SAML2SignatureGenerationHandler handler = new SAML2SignatureGenerationHandler();
-
+
SAML2HandlerChainConfig chainConfig = new DefaultSAML2HandlerChainConfig();
SAML2HandlerConfig handlerConfig = new DefaultSAML2HandlerConfig();
-
- Map<String,Object> chainOptions = new HashMap<String, Object>();
- IDPType idpType = new IDPType();
+
+ Map<String, Object> chainOptions = new HashMap<String, Object>();
+ IDPType idpType = new IDPType();
chainOptions.put(GeneralConstants.CONFIGURATION, idpType);
chainOptions.put(GeneralConstants.KEYPAIR, keypair);
- chainConfig.set(chainOptions);
-
+ chainConfig.set(chainOptions);
+
//Initialize the handler
handler.initChainConfig(chainConfig);
handler.initHandlerConfig(handlerConfig);
-
+
//Create a Protocol Context
MockHttpSession session = new MockHttpSession();
MockServletContext servletContext = new MockServletContext();
MockHttpServletRequest servletRequest = new MockHttpServletRequest(session, "POST");
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
HTTPContext httpContext = new HTTPContext(servletRequest, servletResponse, servletContext);
-
+
SAMLDocumentHolder docHolder = new SAMLDocumentHolder(authnRequest, authDoc);
IssuerInfoHolder issuerInfo = new IssuerInfoHolder("http://localhost:8080/idp/");
- SAML2HandlerRequest request = new DefaultSAML2HandlerRequest(httpContext,
- issuerInfo.getIssuer(), docHolder, SAML2Handler.HANDLER_TYPE.IDP);
+ SAML2HandlerRequest request = new DefaultSAML2HandlerRequest(httpContext, issuerInfo.getIssuer(), docHolder,
+ SAML2Handler.HANDLER_TYPE.IDP);
request.setTypeOfRequestToBeGenerated(GENERATE_REQUEST_TYPE.AUTH);
-
+
SAML2HandlerResponse response = new DefaultSAML2HandlerResponse();
-
- request.addOption(GeneralConstants.SENDER_PUBLIC_KEY, keypair.getPublic());
-
- (new SAML2AuthenticationHandler()).generateSAMLRequest(request, response);
+
+ request.addOption(GeneralConstants.SENDER_PUBLIC_KEY, keypair.getPublic());
+
+ SAML2AuthenticationHandler authHandler = new SAML2AuthenticationHandler();
+ authHandler.initHandlerConfig(handlerConfig);
+ authHandler.generateSAMLRequest(request, response);
+
handler.generateSAMLRequest(request, response);
Document signedDoc = response.getResultingDocument();
-
+
assertNotNull("Signed Doc is not null", signedDoc);
SAMLDocumentHolder signedHolder = new SAMLDocumentHolder(signedDoc);
- request = new DefaultSAML2HandlerRequest(httpContext,
- issuerInfo.getIssuer(), signedHolder,
+ request = new DefaultSAML2HandlerRequest(httpContext, issuerInfo.getIssuer(), signedHolder,
SAML2Handler.HANDLER_TYPE.SP);
-
- request.addOption(GeneralConstants.SENDER_PUBLIC_KEY, keypair.getPublic());
-
+
+ request.addOption(GeneralConstants.SENDER_PUBLIC_KEY, keypair.getPublic());
+
SAML2SignatureValidationHandler validHandler = new SAML2SignatureValidationHandler();
validHandler.initChainConfig(chainConfig);
validHandler.initHandlerConfig(handlerConfig);
-
- validHandler.handleStatusResponseType(request, response);
- }
+
+ validHandler.handleStatusResponseType(request, response);
+ }
}
\ No newline at end of file
13 years, 10 months
Picketlink SVN: r792 - integration-tests/trunk/picketlink-sts-tests.
by picketlink-commits@lists.jboss.org
Author: anil.saldhana(a)jboss.com
Date: 2011-03-02 22:32:21 -0500 (Wed, 02 Mar 2011)
New Revision: 792
Modified:
integration-tests/trunk/picketlink-sts-tests/ant-build.xml
Log:
add openid dep
Modified: integration-tests/trunk/picketlink-sts-tests/ant-build.xml
===================================================================
--- integration-tests/trunk/picketlink-sts-tests/ant-build.xml 2011-03-03 00:04:51 UTC (rev 791)
+++ integration-tests/trunk/picketlink-sts-tests/ant-build.xml 2011-03-03 03:32:21 UTC (rev 792)
@@ -17,6 +17,8 @@
<copy file="${localRepository}/org/picketlink/picketlink-bindings/${version}/picketlink-bindings-${version}.jar" todir="${JBAS_DEPLOY}/picketlink"/>
<copy file="${localRepository}/org/picketlink/picketlink-bindings-jboss/${version}/picketlink-bindings-jboss-${version}.jar" todir="${JBAS_DEPLOY}/picketlink"/>
<copy file="${localRepository}/org/picketlink/picketlink-fed/${version}/picketlink-fed-${version}.jar" todir="${JBAS_DEPLOY}/picketlink"/>
+ <copy file="${localRepository}/org/openid4java/openid4java-nodeps/0.9.5/openid4java-nodeps-0.9.5.jar" todir="${JBAS_DEPLOY}/picketlink"/>
+
<unzip src="${localRepository}/org/picketlink/picketlink-fed-webapps-assembly/${version}/picketlink-fed-webapps-assembly-${version}.zip"
dest="${JBAS_DEPLOY}"/>
<!-- the following props file needs to be copied to JBAS conf and is used by the cache invalidation test -->
13 years, 10 months
Picketlink SVN: r791 - federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2.
by picketlink-commits@lists.jboss.org
Author: anil.saldhana(a)jboss.com
Date: 2011-03-02 19:04:51 -0500 (Wed, 02 Mar 2011)
New Revision: 791
Modified:
federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java
Log:
javadoc
Modified: federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java
===================================================================
--- federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java 2011-03-02 22:24:29 UTC (rev 790)
+++ federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java 2011-03-03 00:04:51 UTC (rev 791)
@@ -85,8 +85,11 @@
* </p>
* <p>
* Configuration Options:
- * @see SAML2Handler#DISABLE_AUTHN_STATEMENT Setting a value will disable the generation of an AuthnStatement
- * @see SAML2Handler#DISABLE_SENDING_ROLES Setting any value will disable the generation and return of roles to SP
+ * @see SAML2Handler#DISABLE_AUTHN_STATEMENT Setting a value will disable the generation of an AuthnStatement (IDP Setting)
+ * @see SAML2Handler#DISABLE_SENDING_ROLES Setting any value will disable the generation and return of roles to SP (IDP Setting)
+ * @see SAML2Handler#DISABLE_ROLE_PICKING Setting to true will disable picking IDP attribute statements (SP Setting)
+ * @see SAML2Handler#ROLE_KEY a csv list of strings that represent the roles coming from IDP (SP Setting)
+ * @see GeneralConstants#NAMEID_FORMAT Setting to a value will provide the nameid format to be sent to IDP (SP Setting)
* </p>
*
* @author Anil.Saldhana(a)redhat.com
13 years, 10 months
Picketlink SVN: r790 - federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2.
by picketlink-commits@lists.jboss.org
Author: anil.saldhana(a)jboss.com
Date: 2011-03-02 17:24:29 -0500 (Wed, 02 Mar 2011)
New Revision: 790
Modified:
federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java
Log:
PLFED-140: use the Name rather than NameFormat
Modified: federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java
===================================================================
--- federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java 2011-03-02 22:10:46 UTC (rev 789)
+++ federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java 2011-03-02 22:24:29 UTC (rev 790)
@@ -546,7 +546,7 @@
AttributeType attr = obj.getAttribute();
if (roleKeys.size() > 0)
{
- if (!roleKeys.contains(attr.getNameFormat()))
+ if (!roleKeys.contains(attr.getName()))
continue;
}
List<Object> attributeValues = attr.getAttributeValue();
13 years, 10 months
Picketlink SVN: r789 - in federation/trunk: picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants and 2 other directories.
by picketlink-commits@lists.jboss.org
Author: anil.saldhana(a)jboss.com
Date: 2011-03-02 17:10:46 -0500 (Wed, 02 Mar 2011)
New Revision: 789
Modified:
federation/trunk/picketlink-fed-api/src/main/java/org/picketlink/identity/federation/api/saml/v2/request/SAML2Request.java
federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants/GeneralConstants.java
federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java
federation/trunk/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/saml/handlers/SAML2AuthenticationHandlerUnitTestCase.java
Log:
PLFED-156: nameid format customization
Modified: federation/trunk/picketlink-fed-api/src/main/java/org/picketlink/identity/federation/api/saml/v2/request/SAML2Request.java
===================================================================
--- federation/trunk/picketlink-fed-api/src/main/java/org/picketlink/identity/federation/api/saml/v2/request/SAML2Request.java 2011-03-02 17:26:35 UTC (rev 788)
+++ federation/trunk/picketlink-fed-api/src/main/java/org/picketlink/identity/federation/api/saml/v2/request/SAML2Request.java 2011-03-02 22:10:46 UTC (rev 789)
@@ -28,7 +28,7 @@
import java.io.OutputStream;
import java.io.Writer;
import java.net.URI;
-
+
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.parsers.ParserConfigurationException;
@@ -63,8 +63,19 @@
public class SAML2Request
{
private SAMLDocumentHolder samlDocumentHolder = null;
-
+
+ private String nameIDFormat = JBossSAMLURIConstants.NAMEID_FORMAT_TRANSIENT.get();
+
/**
+ * Set the NameIDFormat
+ * @param nameIDFormat
+ */
+ public void setNameIDFormat(String nameIDFormat)
+ {
+ this.nameIDFormat = nameIDFormat;
+ }
+
+ /**
* Create an authentication request
* @param id
* @param assertionConsumerURL
@@ -73,38 +84,36 @@
* @return
* @throws ConfigurationException
*/
- public AuthnRequestType createAuthnRequestType(String id,
- String assertionConsumerURL,
- String destination,
- String issuerValue) throws ConfigurationException
+ public AuthnRequestType createAuthnRequestType(String id, String assertionConsumerURL, String destination,
+ String issuerValue) throws ConfigurationException
{
- XMLGregorianCalendar issueInstant = XMLTimeUtil.getIssueInstant();
-
+ XMLGregorianCalendar issueInstant = XMLTimeUtil.getIssueInstant();
+
String version = JBossSAMLConstants.VERSION_2_0.get();
- AuthnRequestType authnRequest = new AuthnRequestType( id, version, issueInstant );
- authnRequest.setAssertionConsumerServiceURL( URI.create( assertionConsumerURL ));
- authnRequest.setProtocolBinding( URI.create( JBossSAMLConstants.HTTP_POST_BINDING.get() ));
- if( destination != null )
+ AuthnRequestType authnRequest = new AuthnRequestType(id, version, issueInstant);
+ authnRequest.setAssertionConsumerServiceURL(URI.create(assertionConsumerURL));
+ authnRequest.setProtocolBinding(URI.create(JBossSAMLConstants.HTTP_POST_BINDING.get()));
+ if (destination != null)
{
- authnRequest.setDestination( URI.create( destination ));
- }
-
+ authnRequest.setDestination(URI.create(destination));
+ }
+
//Create an issuer
NameIDType issuer = new NameIDType();
issuer.setValue(issuerValue);
-
+
authnRequest.setIssuer(issuer);
-
+
//Create a default NameIDPolicy
NameIDPolicyType nameIDPolicy = new NameIDPolicyType();
- nameIDPolicy.setAllowCreate( Boolean.TRUE );
- nameIDPolicy.setFormat( URI.create( JBossSAMLURIConstants.NAMEID_FORMAT_TRANSIENT.get() ));
-
- authnRequest.setNameIDPolicy( nameIDPolicy );
-
- return authnRequest;
+ nameIDPolicy.setAllowCreate(Boolean.TRUE);
+ nameIDPolicy.setFormat(URI.create(this.nameIDFormat));
+
+ authnRequest.setNameIDPolicy(nameIDPolicy);
+
+ return authnRequest;
}
-
+
/**
* Get AuthnRequestType from a file
* @param fileName file with the serialized AuthnRequestType
@@ -115,38 +124,38 @@
* @throws IllegalArgumentException if the input fileName is null
* IllegalStateException if the InputStream from the fileName is null
*/
- public AuthnRequestType getAuthnRequestType(String fileName) throws ConfigurationException, ProcessingException, ParsingException
- {
- if(fileName == null)
+ public AuthnRequestType getAuthnRequestType(String fileName) throws ConfigurationException, ProcessingException,
+ ParsingException
+ {
+ if (fileName == null)
throw new IllegalArgumentException("fileName is null");
ClassLoader tcl = SecurityActions.getContextClassLoader();
InputStream is = tcl.getResourceAsStream(fileName);
return getAuthnRequestType(is);
- }
-
+ }
+
/**
* Get the Underlying SAML2Object from the input stream
* @param is
* @return
* @throws IOException
* @throws ParsingException
- */
- public SAML2Object getSAML2ObjectFromStream(InputStream is)
- throws ConfigurationException, ParsingException,
- ProcessingException
+ */
+ public SAML2Object getSAML2ObjectFromStream(InputStream is) throws ConfigurationException, ParsingException,
+ ProcessingException
{
- if(is == null)
- throw new IllegalStateException("InputStream is null");
+ if (is == null)
+ throw new IllegalStateException("InputStream is null");
- Document samlDocument = DocumentUtil.getDocument(is);
+ Document samlDocument = DocumentUtil.getDocument(is);
SAMLParser samlParser = new SAMLParser();
- SAML2Object requestType = (SAML2Object) samlParser.parse( DocumentUtil.getNodeAsStream( samlDocument ));
+ SAML2Object requestType = (SAML2Object) samlParser.parse(DocumentUtil.getNodeAsStream(samlDocument));
samlDocumentHolder = new SAMLDocumentHolder(requestType, samlDocument);
- return requestType;
+ return requestType;
}
-
+
/**
* Get a Request Type from Input Stream
* @param is
@@ -155,22 +164,23 @@
* @throws ConfigurationException
* @throws
* @throws IllegalArgumentException inputstream is null
- */
- public RequestAbstractType getRequestType(InputStream is)
- throws ParsingException, ConfigurationException, ProcessingException
+ */
+ public RequestAbstractType getRequestType(InputStream is) throws ParsingException, ConfigurationException,
+ ProcessingException
{
- if(is == null)
- throw new IllegalStateException("InputStream is null");
+ if (is == null)
+ throw new IllegalStateException("InputStream is null");
- Document samlDocument = DocumentUtil.getDocument( is );
+ Document samlDocument = DocumentUtil.getDocument(is);
SAMLParser samlParser = new SAMLParser();
- RequestAbstractType requestType = (RequestAbstractType) samlParser.parse( DocumentUtil.getNodeAsStream(samlDocument));
+ RequestAbstractType requestType = (RequestAbstractType) samlParser.parse(DocumentUtil
+ .getNodeAsStream(samlDocument));
samlDocumentHolder = new SAMLDocumentHolder(requestType, samlDocument);
- return requestType;
+ return requestType;
}
-
+
/**
* Get the AuthnRequestType from an input stream
* @param is Inputstream containing the AuthnRequest
@@ -179,20 +189,20 @@
* @throws ProcessingException
* @throws ConfigurationException
* @throws IllegalArgumentException inputstream is null
- */
- public AuthnRequestType getAuthnRequestType(InputStream is) throws ConfigurationException, ProcessingException, ParsingException
+ */
+ public AuthnRequestType getAuthnRequestType(InputStream is) throws ConfigurationException, ProcessingException,
+ ParsingException
{
- if(is == null)
- throw new IllegalStateException("InputStream is null");
-
- Document samlDocument = DocumentUtil.getDocument( is );
+ if (is == null)
+ throw new IllegalStateException("InputStream is null");
+ Document samlDocument = DocumentUtil.getDocument(is);
+
SAMLParser samlParser = new SAMLParser();
- AuthnRequestType requestType = (AuthnRequestType) samlParser.parse( DocumentUtil.getNodeAsStream(samlDocument));
+ AuthnRequestType requestType = (AuthnRequestType) samlParser.parse(DocumentUtil.getNodeAsStream(samlDocument));
samlDocumentHolder = new SAMLDocumentHolder(requestType, samlDocument);
return requestType;
- }
-
+ }
/**
* Get the parsed {@code SAMLDocumentHolder}
@@ -201,28 +211,28 @@
public SAMLDocumentHolder getSamlDocumentHolder()
{
return samlDocumentHolder;
- }
-
+ }
+
/**
* Create a Logout Request
* @param issuer
* @return
* @throws ConfigurationException
*/
- public LogoutRequestType createLogoutRequest(String issuer) throws ConfigurationException
- {
- LogoutRequestType lrt = new LogoutRequestType( IDGenerator.create("ID_"), JBossSAMLConstants.VERSION_2_0.get(),
- XMLTimeUtil.getIssueInstant() );
-
+ public LogoutRequestType createLogoutRequest(String issuer) throws ConfigurationException
+ {
+ LogoutRequestType lrt = new LogoutRequestType(IDGenerator.create("ID_"), JBossSAMLConstants.VERSION_2_0.get(),
+ XMLTimeUtil.getIssueInstant());
+
//Create an issuer
- NameIDType issuerNameID = new NameIDType();
+ NameIDType issuerNameID = new NameIDType();
issuerNameID.setValue(issuer);
-
+
lrt.setIssuer(issuerNameID);
-
+
return lrt;
}
-
+
/**
* Return the DOM object
* @param rat
@@ -231,79 +241,80 @@
* @throws ParsingException
* @throws ConfigurationException
*/
- public Document convert(RequestAbstractType rat)
- throws ProcessingException, ConfigurationException, ParsingException
+ public Document convert(RequestAbstractType rat) throws ProcessingException, ConfigurationException,
+ ParsingException
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
-
+
SAMLRequestWriter writer = new SAMLRequestWriter(StaxUtil.getXMLStreamWriter(bos));
- if( rat instanceof AuthnRequestType )
+ if (rat instanceof AuthnRequestType)
{
- writer.write( (AuthnRequestType) rat);
- }
- else if( rat instanceof LogoutRequestType )
+ writer.write((AuthnRequestType) rat);
+ }
+ else if (rat instanceof LogoutRequestType)
{
- writer.write( (LogoutRequestType) rat);
+ writer.write((LogoutRequestType) rat);
}
-
- return DocumentUtil.getDocument( new String( bos.toByteArray() ));
+
+ return DocumentUtil.getDocument(new String(bos.toByteArray()));
}
-
+
/**
* Convert a SAML2 Response into a Document
* @param responseType
* @return
* @throws ParserConfigurationException
*/
- public Document convert( ResponseType responseType) throws ProcessingException, ParsingException, ConfigurationException
+ public Document convert(ResponseType responseType) throws ProcessingException, ParsingException,
+ ConfigurationException
{
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- SAMLResponseWriter writer = new SAMLResponseWriter(StaxUtil.getXMLStreamWriter(baos));
- writer.write( responseType );
-
- ByteArrayInputStream bis = new ByteArrayInputStream( baos.toByteArray() );
- return DocumentUtil.getDocument(bis);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ SAMLResponseWriter writer = new SAMLResponseWriter(StaxUtil.getXMLStreamWriter(baos));
+ writer.write(responseType);
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
+ return DocumentUtil.getDocument(bis);
}
-
+
/**
* Marshall the AuthnRequestType to an output stream
* @param requestType
* @param os
* @throws SAXException
*/
- public void marshall(RequestAbstractType requestType, OutputStream os) throws ProcessingException
- {
- SAMLRequestWriter samlRequestWriter = new SAMLRequestWriter( StaxUtil.getXMLStreamWriter(os));
- if( requestType instanceof AuthnRequestType )
+ public void marshall(RequestAbstractType requestType, OutputStream os) throws ProcessingException
+ {
+ SAMLRequestWriter samlRequestWriter = new SAMLRequestWriter(StaxUtil.getXMLStreamWriter(os));
+ if (requestType instanceof AuthnRequestType)
{
- samlRequestWriter.write((AuthnRequestType)requestType );
+ samlRequestWriter.write((AuthnRequestType) requestType);
}
- else if( requestType instanceof LogoutRequestType )
+ else if (requestType instanceof LogoutRequestType)
{
- samlRequestWriter.write((LogoutRequestType)requestType );
+ samlRequestWriter.write((LogoutRequestType) requestType);
}
else
- throw new RuntimeException( "Unsupported" );
+ throw new RuntimeException("Unsupported");
}
-
+
/**
* Marshall the AuthnRequestType to a writer
* @param requestType
* @param writer
* @throws SAXException
*/
- public void marshall(RequestAbstractType requestType, Writer writer) throws ProcessingException
- {
- SAMLRequestWriter samlRequestWriter = new SAMLRequestWriter( StaxUtil.getXMLStreamWriter( writer ));
- if( requestType instanceof AuthnRequestType )
+ public void marshall(RequestAbstractType requestType, Writer writer) throws ProcessingException
+ {
+ SAMLRequestWriter samlRequestWriter = new SAMLRequestWriter(StaxUtil.getXMLStreamWriter(writer));
+ if (requestType instanceof AuthnRequestType)
{
- samlRequestWriter.write((AuthnRequestType)requestType );
+ samlRequestWriter.write((AuthnRequestType) requestType);
}
- else if( requestType instanceof LogoutRequestType )
+ else if (requestType instanceof LogoutRequestType)
{
- samlRequestWriter.write((LogoutRequestType)requestType );
+ samlRequestWriter.write((LogoutRequestType) requestType);
}
else
- throw new RuntimeException( "Unsupported" );
+ throw new RuntimeException("Unsupported");
}
}
\ No newline at end of file
Modified: federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants/GeneralConstants.java
===================================================================
--- federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants/GeneralConstants.java 2011-03-02 17:26:35 UTC (rev 788)
+++ federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants/GeneralConstants.java 2011-03-02 22:10:46 UTC (rev 789)
@@ -62,6 +62,8 @@
String LOGOUT_PAGE_NAME = "/logout.jsp";
+ String NAMEID_FORMAT = "NAMEID_FORMAT";
+
String PRINCIPAL_ID = "jboss_identity.principal";
String RELAY_STATE = "RelayState";
Modified: federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java
===================================================================
--- federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java 2011-03-02 17:26:35 UTC (rev 788)
+++ federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/handlers/saml2/SAML2AuthenticationHandler.java 2011-03-02 22:10:46 UTC (rev 789)
@@ -93,51 +93,55 @@
* @since Oct 8, 2009
*/
public class SAML2AuthenticationHandler extends BaseSAML2Handler
-{
+{
private static Logger log = Logger.getLogger(SAML2AuthenticationHandler.class);
- private boolean trace = log.isTraceEnabled();
-
- private IDPAuthenticationHandler idp = new IDPAuthenticationHandler();
- private SPAuthenticationHandler sp = new SPAuthenticationHandler();
-
+
+ private final boolean trace = log.isTraceEnabled();
+
+ private final IDPAuthenticationHandler idp = new IDPAuthenticationHandler();
+
+ private final SPAuthenticationHandler sp = new SPAuthenticationHandler();
+
public void handleRequestType(SAML2HandlerRequest request, SAML2HandlerResponse response) throws ProcessingException
- {
- if(request.getSAML2Object() instanceof AuthnRequestType == false)
- return ;
-
- if(getType() == HANDLER_TYPE.IDP)
+ {
+ if (request.getSAML2Object() instanceof AuthnRequestType == false)
+ return;
+
+ if (getType() == HANDLER_TYPE.IDP)
{
idp.handleRequestType(request, response);
}
else
{
sp.handleRequestType(request, response);
- }
+ }
}
-
+
+ @Override
public void handleStatusResponseType(SAML2HandlerRequest request, SAML2HandlerResponse response)
throws ProcessingException
- {
- if(request.getSAML2Object() instanceof ResponseType == false)
- return ;
-
- if(getType() == HANDLER_TYPE.IDP)
+ {
+ if (request.getSAML2Object() instanceof ResponseType == false)
+ return;
+
+ if (getType() == HANDLER_TYPE.IDP)
{
idp.handleStatusResponseType(request, response);
}
else
{
sp.handleStatusResponseType(request, response);
- }
+ }
}
+ @Override
public void generateSAMLRequest(SAML2HandlerRequest request, SAML2HandlerResponse response)
throws ProcessingException
- {
- if(GENERATE_REQUEST_TYPE.AUTH != request.getTypeOfRequestToBeGenerated())
+ {
+ if (GENERATE_REQUEST_TYPE.AUTH != request.getTypeOfRequestToBeGenerated())
return;
-
- if(getType() == HANDLER_TYPE.IDP)
+
+ if (getType() == HANDLER_TYPE.IDP)
{
idp.generateSAMLRequest(request, response);
response.setSendRequest(true);
@@ -146,38 +150,37 @@
{
sp.generateSAMLRequest(request, response);
response.setSendRequest(true);
- }
+ }
}
-
+
private class IDPAuthenticationHandler
{
- public void generateSAMLRequest(SAML2HandlerRequest request,
- SAML2HandlerResponse response) throws ProcessingException
+ public void generateSAMLRequest(SAML2HandlerRequest request, SAML2HandlerResponse response)
+ throws ProcessingException
{
-
+
}
-
-
- public void handleStatusResponseType( SAML2HandlerRequest request,
- SAML2HandlerResponse response ) throws ProcessingException
- {
+
+ public void handleStatusResponseType(SAML2HandlerRequest request, SAML2HandlerResponse response)
+ throws ProcessingException
+ {
}
-
- public void handleRequestType( SAML2HandlerRequest request,
- SAML2HandlerResponse response ) throws ProcessingException
- {
+
+ public void handleRequestType(SAML2HandlerRequest request, SAML2HandlerResponse response)
+ throws ProcessingException
+ {
HTTPContext httpContext = (HTTPContext) request.getContext();
ServletContext servletContext = httpContext.getServletContext();
-
+
AuthnRequestType art = (AuthnRequestType) request.getSAML2Object();
- if( art == null )
- throw new ProcessingException( "AuthnRequest is null" );
-
+ if (art == null)
+ throw new ProcessingException("AuthnRequest is null");
+
String destination = art.getAssertionConsumerServiceURL().toASCIIString();
-
+
HttpSession session = BaseSAML2Handler.getHttpSession(request);
Principal userPrincipal = (Principal) session.getAttribute(GeneralConstants.PRINCIPAL_ID);
- if(userPrincipal == null)
+ if (userPrincipal == null)
userPrincipal = httpContext.getRequest().getUserPrincipal();
/*
List<String> roles = (List<String>) session.getAttribute(GeneralConstants.ROLES_ID);*/
@@ -190,117 +193,117 @@
userPrincipal, roles, request.getIssuer().getValue(),
attribs,
assertionValidity, art.getID());*/
-
+
Document samlResponse = this.getResponse(request);
-
+
//Update the Identity Server
- boolean isPost = httpContext.getRequest().getMethod().equalsIgnoreCase( "POST" );
- IdentityServer identityServer = (IdentityServer) servletContext.getAttribute(GeneralConstants.IDENTITY_SERVER);
- identityServer.stack().register(session.getId(), destination, isPost );
-
+ boolean isPost = httpContext.getRequest().getMethod().equalsIgnoreCase("POST");
+ IdentityServer identityServer = (IdentityServer) servletContext
+ .getAttribute(GeneralConstants.IDENTITY_SERVER);
+ identityServer.stack().register(session.getId(), destination, isPost);
+
response.setDestination(destination);
- response.setResultingDocument(samlResponse);
+ response.setResultingDocument(samlResponse);
response.setRelayState(request.getRelayState());
- response.setPostBindingForResponse( isPost );
+ response.setPostBindingForResponse(isPost);
}
- catch(Exception e)
+ catch (Exception e)
{
log.error("Exception in processing authentication:", e);
throw new ProcessingException("authentication issue");
}
}
-
+
@SuppressWarnings("unchecked")
- public Document getResponse( SAML2HandlerRequest request ) throws ConfigurationException, ProcessingException
+ public Document getResponse(SAML2HandlerRequest request) throws ConfigurationException, ProcessingException
{
HTTPContext httpContext = (HTTPContext) request.getContext();
AuthnRequestType art = (AuthnRequestType) request.getSAML2Object();
HttpSession session = BaseSAML2Handler.getHttpSession(request);
Principal userPrincipal = (Principal) session.getAttribute(GeneralConstants.PRINCIPAL_ID);
- if(userPrincipal == null)
- userPrincipal = httpContext.getRequest().getUserPrincipal();
-
- String assertionConsumerURL = art.getAssertionConsumerServiceURL().toASCIIString();
- List<String> roles = (List<String>) session.getAttribute(GeneralConstants.ROLES_ID);
+ if (userPrincipal == null)
+ userPrincipal = httpContext.getRequest().getUserPrincipal();
+
+ String assertionConsumerURL = art.getAssertionConsumerServiceURL().toASCIIString();
+ List<String> roles = (List<String>) session.getAttribute(GeneralConstants.ROLES_ID);
String identityURL = request.getIssuer().getValue();
- Map<String, Object> attribs = (Map<String, Object>) request.getOptions().get(GeneralConstants.ATTRIBUTES);
+ Map<String, Object> attribs = (Map<String, Object>) request.getOptions().get(GeneralConstants.ATTRIBUTES);
long assertionValidity = (Long) request.getOptions().get(GeneralConstants.ASSERTIONS_VALIDITY);
String requestID = art.getID();
-
+
Document samlResponseDocument = null;
-
- if(trace)
- log.trace("AssertionConsumerURL=" + assertionConsumerURL +
- "::assertion validity=" + assertionValidity);
- ResponseType responseType = null;
-
+
+ if (trace)
+ log.trace("AssertionConsumerURL=" + assertionConsumerURL + "::assertion validity=" + assertionValidity);
+ ResponseType responseType = null;
+
SAML2Response saml2Response = new SAML2Response();
-
+
//Create a response type
String id = IDGenerator.create("ID_");
-
- IssuerInfoHolder issuerHolder = new IssuerInfoHolder(identityURL);
+
+ IssuerInfoHolder issuerHolder = new IssuerInfoHolder(identityURL);
issuerHolder.setStatusCode(JBossSAMLURIConstants.STATUS_SUCCESS.get());
IDPInfoHolder idp = new IDPInfoHolder();
idp.setNameIDFormatValue(userPrincipal.getName());
idp.setNameIDFormat(JBossSAMLURIConstants.NAMEID_FORMAT_PERSISTENT.get());
-
- String assertionID = (String) session.getAttribute( GeneralConstants.ASSERTION_ID );
-
- if( assertionID != null )
+
+ String assertionID = (String) session.getAttribute(GeneralConstants.ASSERTION_ID);
+
+ if (assertionID != null)
{
//Just renew the assertion
- AssertionType latestAssertion = (AssertionType) session.getAttribute( GeneralConstants.ASSERTION );
- if( latestAssertion != null )
- idp.setAssertion( latestAssertion );
+ AssertionType latestAssertion = (AssertionType) session.getAttribute(GeneralConstants.ASSERTION);
+ if (latestAssertion != null)
+ idp.setAssertion(latestAssertion);
}
SPInfoHolder sp = new SPInfoHolder();
sp.setResponseDestinationURI(assertionConsumerURL);
sp.setRequestID(requestID);
responseType = saml2Response.createResponseType(id, sp, idp, issuerHolder);
-
+
//Add information on the roles
- AssertionType assertion = (AssertionType) responseType.getAssertions().get(0).getAssertion();
+ AssertionType assertion = responseType.getAssertions().get(0).getAssertion();
//Create an AuthnStatementType
- if( handlerConfig.getParameter( DISABLE_AUTHN_STATEMENT ) == null )
+ if (handlerConfig.getParameter(DISABLE_AUTHN_STATEMENT) == null)
{
- AuthnStatementType authnStatement =
- StatementUtil.createAuthnStatement( XMLTimeUtil.getIssueInstant(), JBossSAMLURIConstants.AC_PASSWORD_PROTECTED_TRANSPORT.get() );
- assertion.addStatement( authnStatement );
+ AuthnStatementType authnStatement = StatementUtil.createAuthnStatement(XMLTimeUtil.getIssueInstant(),
+ JBossSAMLURIConstants.AC_PASSWORD_PROTECTED_TRANSPORT.get());
+ assertion.addStatement(authnStatement);
}
-
- if( handlerConfig.getParameter( DISABLE_SENDING_ROLES ) == null )
+
+ if (handlerConfig.getParameter(DISABLE_SENDING_ROLES) == null)
{
AttributeStatementType attrStatement = StatementUtil.createAttributeStatement(roles);
- assertion.addStatement( attrStatement );
+ assertion.addStatement(attrStatement);
}
//Add in the attributes information
- if(attribs != null && attribs.size() > 0 )
+ if (attribs != null && attribs.size() > 0)
{
AttributeStatementType attStatement = StatementUtil.createAttributeStatement(attribs);
- assertion.addStatement( attStatement );
- }
-
+ assertion.addStatement(attStatement);
+ }
+
//Add assertion to the session
- session.setAttribute( GeneralConstants.ASSERTION, assertion );
-
+ session.setAttribute(GeneralConstants.ASSERTION, assertion);
+
//Lets see how the response looks like
- if(log.isTraceEnabled())
+ if (log.isTraceEnabled())
{
StringWriter sw = new StringWriter();
try
{
saml2Response.marshall(responseType, sw);
}
- catch ( ProcessingException e)
+ catch (ProcessingException e)
{
log.trace(e);
- }
- log.trace("Response="+sw.toString());
+ }
+ log.trace("Response=" + sw.toString());
}
try
{
@@ -309,63 +312,70 @@
catch (Exception e)
{
e.printStackTrace();
- if(trace)
- log.trace(e);
- }
- return samlResponseDocument;
- }
+ if (trace)
+ log.trace(e);
+ }
+ return samlResponseDocument;
+ }
}
-
+
private class SPAuthenticationHandler
{
- public void generateSAMLRequest(SAML2HandlerRequest request,
- SAML2HandlerResponse response) throws ProcessingException
+ public void generateSAMLRequest(SAML2HandlerRequest request, SAML2HandlerResponse response)
+ throws ProcessingException
{
String issuerValue = request.getIssuer().getValue();
-
+
SAML2Request samlRequest = new SAML2Request();
String id = IDGenerator.create("ID_");
+
+ //Check if there is a nameid policy
+ String nameIDFormat = (String) request.getOptions().get(GeneralConstants.NAMEID_FORMAT);
+ if (StringUtil.isNotNull(nameIDFormat))
+ {
+ samlRequest.setNameIDFormat(nameIDFormat);
+ }
try
{
- AuthnRequestType authn = samlRequest.createAuthnRequestType(id,
- issuerValue, response.getDestination(), issuerValue);
-
+ AuthnRequestType authn = samlRequest.createAuthnRequestType(id, issuerValue, response.getDestination(),
+ issuerValue);
+
response.setResultingDocument(samlRequest.convert(authn));
response.setSendRequest(true);
}
catch (Exception e)
{
throw new ProcessingException(e);
- }
+ }
}
-
- public void handleStatusResponseType( SAML2HandlerRequest request,
- SAML2HandlerResponse response ) throws ProcessingException
- {
+
+ public void handleStatusResponseType(SAML2HandlerRequest request, SAML2HandlerResponse response)
+ throws ProcessingException
+ {
HTTPContext httpContext = (HTTPContext) request.getContext();
ResponseType responseType = (ResponseType) request.getSAML2Object();
List<RTChoiceType> assertions = responseType.getAssertions();
- if(assertions.size() == 0)
- throw new IllegalStateException("No assertions in reply from IDP");
-
- PrivateKey privateKey = (PrivateKey) request.getOptions().get( GeneralConstants.DECRYPTING_KEY );
-
+ if (assertions.size() == 0)
+ throw new IllegalStateException("No assertions in reply from IDP");
+
+ PrivateKey privateKey = (PrivateKey) request.getOptions().get(GeneralConstants.DECRYPTING_KEY);
+
Object assertion = assertions.get(0).getEncryptedAssertion();
- if(assertion instanceof EncryptedAssertionType)
+ if (assertion instanceof EncryptedAssertionType)
{
- responseType = this.decryptAssertion(responseType, privateKey );
+ responseType = this.decryptAssertion(responseType, privateKey);
assertion = responseType.getAssertions().get(0).getAssertion();
}
- if( assertion == null )
+ if (assertion == null)
{
assertion = assertions.get(0).getAssertion();
}
-
+
Principal userPrincipal = handleSAMLResponse(responseType, response);
- if(userPrincipal == null)
+ if (userPrincipal == null)
{
response.setError(403, "User Principal not determined: Forbidden");
- }
+ }
else
{
//add it to the session
@@ -373,60 +383,62 @@
session.setAttribute(GeneralConstants.PRINCIPAL_ID, userPrincipal);
}
}
-
- public void handleRequestType( SAML2HandlerRequest request,
- SAML2HandlerResponse response ) throws ProcessingException
- {
+
+ public void handleRequestType(SAML2HandlerRequest request, SAML2HandlerResponse response)
+ throws ProcessingException
+ {
}
-
- private ResponseType decryptAssertion(ResponseType responseType, PrivateKey privateKey ) throws ProcessingException
+
+ private ResponseType decryptAssertion(ResponseType responseType, PrivateKey privateKey)
+ throws ProcessingException
{
- if( privateKey == null )
- throw new IllegalArgumentException( "privateKey is null" );
+ if (privateKey == null)
+ throw new IllegalArgumentException("privateKey is null");
SAML2Response saml2Response = new SAML2Response();
try
{
- Document doc = saml2Response.convert( responseType );
-
- Element enc = DocumentUtil.getElement(doc, new QName( JBossSAMLConstants.ENCRYPTED_ASSERTION.get() ));
- if( enc == null )
- throw new ProcessingException( "Null encrypted assertion element" );
- String oldID = enc.getAttribute( "ID" );
+ Document doc = saml2Response.convert(responseType);
+
+ Element enc = DocumentUtil.getElement(doc, new QName(JBossSAMLConstants.ENCRYPTED_ASSERTION.get()));
+ if (enc == null)
+ throw new ProcessingException("Null encrypted assertion element");
+ String oldID = enc.getAttribute("ID");
Document newDoc = DocumentUtil.createDocument();
Node importedNode = newDoc.importNode(enc, true);
newDoc.appendChild(importedNode);
-
- Element decryptedDocumentElement = XMLEncryptionUtil.decryptElementInDocument( newDoc, privateKey );
+
+ Element decryptedDocumentElement = XMLEncryptionUtil.decryptElementInDocument(newDoc, privateKey);
SAMLParser parser = new SAMLParser();
- AssertionType assertion = (AssertionType) parser.parse( StaxParserUtil.getXMLEventReader( DocumentUtil.getNodeAsStream(decryptedDocumentElement)));
-
- responseType.replaceAssertion( oldID, new RTChoiceType(assertion));
- return responseType;
+ AssertionType assertion = (AssertionType) parser.parse(StaxParserUtil.getXMLEventReader(DocumentUtil
+ .getNodeAsStream(decryptedDocumentElement)));
+
+ responseType.replaceAssertion(oldID, new RTChoiceType(assertion));
+ return responseType;
}
- catch ( Exception e )
- {
- throw new ProcessingException( e );
+ catch (Exception e)
+ {
+ throw new ProcessingException(e);
}
}
-
- private Principal handleSAMLResponse(ResponseType responseType, SAML2HandlerResponse response)
- throws ProcessingException
- {
- if(responseType == null)
+
+ private Principal handleSAMLResponse(ResponseType responseType, SAML2HandlerResponse response)
+ throws ProcessingException
+ {
+ if (responseType == null)
throw new IllegalArgumentException("response type is null");
-
+
StatusType statusType = responseType.getStatus();
- if(statusType == null)
+ if (statusType == null)
throw new IllegalArgumentException("Status Type from the IDP is null");
String statusValue = statusType.getStatusCode().getValue().toASCIIString();
- if(JBossSAMLURIConstants.STATUS_SUCCESS.get().equals(statusValue) == false)
+ if (JBossSAMLURIConstants.STATUS_SUCCESS.get().equals(statusValue) == false)
throw new SecurityException("IDP forbid the user");
List<RTChoiceType> assertions = responseType.getAssertions();
- if(assertions.size() == 0)
- throw new IllegalStateException("No assertions in reply from IDP");
-
+ if (assertions.size() == 0)
+ throw new IllegalStateException("No assertions in reply from IDP");
+
AssertionType assertion = assertions.get(0).getAssertion();
//Check for validity of assertion
boolean expiredAssertion;
@@ -436,45 +448,45 @@
}
catch (ConfigurationException e)
{
- throw new ProcessingException(e);
+ throw new ProcessingException(e);
}
- if(expiredAssertion)
+ if (expiredAssertion)
{
AssertionExpiredException aee = new AssertionExpiredException();
- throw new ProcessingException("Assertion has expired",aee);
- }
-
- SubjectType subject = assertion.getSubject();
+ throw new ProcessingException("Assertion has expired", aee);
+ }
+
+ SubjectType subject = assertion.getSubject();
/*JAXBElement<NameIDType> jnameID = (JAXBElement<NameIDType>) subject.getContent().get(0);
NameIDType nameID = jnameID.getValue();
*/
- if( subject == null )
- throw new ProcessingException( "Subject in the assertion is null" );
-
+ if (subject == null)
+ throw new ProcessingException("Subject in the assertion is null");
+
STSubType subType = subject.getSubType();
- if( subType == null )
- throw new RuntimeException( "Unable to find subtype via subject" );
+ if (subType == null)
+ throw new RuntimeException("Unable to find subtype via subject");
NameIDType nameID = (NameIDType) subType.getBaseID();
- if( nameID == null )
- throw new RuntimeException( "Unable to find username via subject" );
-
+ if (nameID == null)
+ throw new RuntimeException("Unable to find username via subject");
+
final String userName = nameID.getValue();
List<String> roles = new ArrayList<String>();
//Let us get the roles
Set<StatementAbstractType> statements = assertion.getStatements();
- for( StatementAbstractType statement : statements )
+ for (StatementAbstractType statement : statements)
{
- if( statement instanceof AttributeStatementType )
+ if (statement instanceof AttributeStatementType)
{
AttributeStatementType attributeStatement = (AttributeStatementType) statement;
- roles.addAll( getRoles( attributeStatement ));
+ roles.addAll(getRoles(attributeStatement));
}
}
-
+
response.setRoles(roles);
-
+
Principal principal = new Principal()
{
public String getName()
@@ -482,78 +494,79 @@
return userName;
}
};
-
- if(handlerChainConfig.getParameter(GeneralConstants.ROLE_VALIDATOR_IGNORE) == null)
+
+ if (handlerChainConfig.getParameter(GeneralConstants.ROLE_VALIDATOR_IGNORE) == null)
{
//Validate the roles
- IRoleValidator roleValidator =
- (IRoleValidator) handlerChainConfig.getParameter(GeneralConstants.ROLE_VALIDATOR);
- if(roleValidator == null)
+ IRoleValidator roleValidator = (IRoleValidator) handlerChainConfig
+ .getParameter(GeneralConstants.ROLE_VALIDATOR);
+ if (roleValidator == null)
throw new ProcessingException("Role Validator not provided");
-
+
boolean validRole = roleValidator.userInRole(principal, roles);
- if(!validRole)
+ if (!validRole)
{
- if(trace)
+ if (trace)
log.trace("Invalid role:" + roles);
principal = null;
- }
+ }
}
return principal;
- }
-
+ }
+
/**
* Get the roles from the attribute statement
* @param attributeStatement
* @return
*/
- private List<String> getRoles( AttributeStatementType attributeStatement )
+ private List<String> getRoles(AttributeStatementType attributeStatement)
{
List<String> roles = new ArrayList<String>();
-
+
//PLFED-141: Disable role picking from IDP response
- if( handlerConfig.containsKey( DISABLE_ROLE_PICKING ))
+ if (handlerConfig.containsKey(DISABLE_ROLE_PICKING))
{
- String val = (String) handlerConfig.getParameter( DISABLE_ROLE_PICKING );
- if( StringUtil.isNotNull(val) && "true".equalsIgnoreCase(val) )
+ String val = (String) handlerConfig.getParameter(DISABLE_ROLE_PICKING);
+ if (StringUtil.isNotNull(val) && "true".equalsIgnoreCase(val))
return roles;
}
-
+
//PLFED-140: which of the attribute statements represent roles?
List<String> roleKeys = new ArrayList<String>();
-
- if( handlerConfig.containsKey( ROLE_KEY ) )
+
+ if (handlerConfig.containsKey(ROLE_KEY))
{
- String roleKey = (String) handlerConfig.getParameter( ROLE_KEY );
- roleKeys.addAll( StringUtil.tokenize( roleKey ) );
+ String roleKey = (String) handlerConfig.getParameter(ROLE_KEY);
+ roleKeys.addAll(StringUtil.tokenize(roleKey));
}
-
+
List<ASTChoiceType> attList = attributeStatement.getAttributes();
- for(ASTChoiceType obj:attList)
+ for (ASTChoiceType obj : attList)
{
AttributeType attr = obj.getAttribute();
- if( roleKeys.size() > 0 )
+ if (roleKeys.size() > 0)
{
- if( !roleKeys.contains( attr.getNameFormat() ) )
+ if (!roleKeys.contains(attr.getNameFormat()))
continue;
}
List<Object> attributeValues = attr.getAttributeValue();
- if( attributeValues != null)
+ if (attributeValues != null)
{
- for( Object attrValue : attributeValues )
+ for (Object attrValue : attributeValues)
{
- if( attrValue instanceof String )
+ if (attrValue instanceof String)
{
- roles.add( (String) attrValue );
+ roles.add((String) attrValue);
}
- else if( attrValue instanceof Node )
+ else if (attrValue instanceof Node)
{
Node roleNode = (Node) attrValue;
- roles.add( roleNode.getFirstChild().getNodeValue() );
+ roles.add(roleNode.getFirstChild().getNodeValue());
}
- else throw new RuntimeException( "Unknown role object type : " + attrValue );
+ else
+ throw new RuntimeException("Unknown role object type : " + attrValue);
}
- }
+ }
}
return roles;
}
Modified: federation/trunk/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/saml/handlers/SAML2AuthenticationHandlerUnitTestCase.java
===================================================================
--- federation/trunk/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/saml/handlers/SAML2AuthenticationHandlerUnitTestCase.java 2011-03-02 17:26:35 UTC (rev 788)
+++ federation/trunk/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/saml/handlers/SAML2AuthenticationHandlerUnitTestCase.java 2011-03-02 22:10:46 UTC (rev 789)
@@ -21,6 +21,8 @@
*/
package org.picketlink.test.identity.federation.web.saml.handlers;
+import static org.junit.Assert.assertEquals;
+
import java.security.KeyPair;
import java.security.Principal;
import java.security.PublicKey;
@@ -31,6 +33,7 @@
import javax.crypto.spec.SecretKeySpec;
import javax.xml.namespace.QName;
+import org.junit.Ignore;
import org.junit.Test;
import org.picketlink.identity.federation.api.saml.v2.response.SAML2Response;
import org.picketlink.identity.federation.core.config.SPType;
@@ -47,6 +50,7 @@
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerChainConfig;
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerConfig;
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerRequest;
+import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerRequest.GENERATE_REQUEST_TYPE;
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerResponse;
import org.picketlink.identity.federation.core.saml.v2.util.AssertionUtil;
import org.picketlink.identity.federation.core.saml.v2.util.DocumentUtil;
@@ -57,6 +61,8 @@
import org.picketlink.identity.federation.newmodel.saml.v2.assertion.NameIDType;
import org.picketlink.identity.federation.newmodel.saml.v2.assertion.SubjectType;
import org.picketlink.identity.federation.newmodel.saml.v2.assertion.SubjectType.STSubType;
+import org.picketlink.identity.federation.newmodel.saml.v2.protocol.AuthnRequestType;
+import org.picketlink.identity.federation.newmodel.saml.v2.protocol.NameIDPolicyType;
import org.picketlink.identity.federation.newmodel.saml.v2.protocol.ResponseType;
import org.picketlink.identity.federation.saml.v2.SAML2Object;
import org.picketlink.identity.federation.web.constants.GeneralConstants;
@@ -76,82 +82,133 @@
public class SAML2AuthenticationHandlerUnitTestCase
{
@Test
+ public void handleNameIDCustomization() throws Exception
+ {
+ SAML2AuthenticationHandler handler = new SAML2AuthenticationHandler();
+
+ SAML2HandlerChainConfig chainConfig = new DefaultSAML2HandlerChainConfig();
+ SAML2HandlerConfig handlerConfig = new DefaultSAML2HandlerConfig();
+
+ Map<String, Object> chainOptions = new HashMap<String, Object>();
+ SPType spType = new SPType();
+ chainOptions.put(GeneralConstants.CONFIGURATION, spType);
+ chainOptions.put(GeneralConstants.ROLE_VALIDATOR_IGNORE, "true");
+ chainConfig.set(chainOptions);
+
+ //Initialize the handler
+ handler.initChainConfig(chainConfig);
+ handler.initHandlerConfig(handlerConfig);
+
+ //Create a Protocol Context
+ MockHttpSession session = new MockHttpSession();
+ MockServletContext servletContext = new MockServletContext();
+ MockHttpServletRequest servletRequest = new MockHttpServletRequest(session, "POST");
+ MockHttpServletResponse servletResponse = new MockHttpServletResponse();
+ HTTPContext httpContext = new HTTPContext(servletRequest, servletResponse, servletContext);
+
+ SAML2Object saml2Object = new SAML2Object()
+ {
+ };
+
+ SAMLDocumentHolder docHolder = new SAMLDocumentHolder(saml2Object, null);
+ IssuerInfoHolder issuerInfo = new IssuerInfoHolder("http://localhost:8080/idp/");
+
+ SAML2HandlerRequest request = new DefaultSAML2HandlerRequest(httpContext, issuerInfo.getIssuer(), docHolder,
+ SAML2Handler.HANDLER_TYPE.SP);
+ request.setTypeOfRequestToBeGenerated(GENERATE_REQUEST_TYPE.AUTH);
+ request.addOption(GeneralConstants.NAMEID_FORMAT, JBossSAMLURIConstants.NAMEID_FORMAT_PERSISTENT.get());
+
+ SAML2HandlerResponse response = new DefaultSAML2HandlerResponse();
+ handler.generateSAMLRequest(request, response);
+
+ Document samlReq = response.getResultingDocument();
+ SAMLParser parser = new SAMLParser();
+ System.out.println("Doc=" + DocumentUtil.asString(samlReq));
+ AuthnRequestType authnRequest = (AuthnRequestType) parser.parse(DocumentUtil.getNodeAsStream(samlReq));
+ NameIDPolicyType nameIDPolicy = authnRequest.getNameIDPolicy();
+ assertEquals(JBossSAMLURIConstants.NAMEID_FORMAT_PERSISTENT.get(), nameIDPolicy.getFormat().toString());
+ }
+
+ @Ignore
+ @Test
public void handleEncryptedAssertion() throws Exception
- {
+ {
SAML2AuthenticationHandler handler = new SAML2AuthenticationHandler();
-
+
SAML2HandlerChainConfig chainConfig = new DefaultSAML2HandlerChainConfig();
SAML2HandlerConfig handlerConfig = new DefaultSAML2HandlerConfig();
-
- Map<String,Object> chainOptions = new HashMap<String, Object>();
- SPType spType = new SPType();
- chainOptions.put(GeneralConstants.CONFIGURATION, spType );
- chainOptions.put( GeneralConstants.ROLE_VALIDATOR_IGNORE, "true" );
- chainConfig.set(chainOptions);
-
+
+ Map<String, Object> chainOptions = new HashMap<String, Object>();
+ SPType spType = new SPType();
+ chainOptions.put(GeneralConstants.CONFIGURATION, spType);
+ chainOptions.put(GeneralConstants.ROLE_VALIDATOR_IGNORE, "true");
+ chainConfig.set(chainOptions);
+
//Initialize the handler
handler.initChainConfig(chainConfig);
handler.initHandlerConfig(handlerConfig);
-
- //Create a Protocol Context
+
+ //Create a Protocol Context
MockHttpSession session = new MockHttpSession();
MockServletContext servletContext = new MockServletContext();
MockHttpServletRequest servletRequest = new MockHttpServletRequest(session, "POST");
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
HTTPContext httpContext = new HTTPContext(servletRequest, servletResponse, servletContext);
-
- SAML2Object saml2Object = new SAML2Object(){};
-
- KeyPair keypair = KeyStoreUtil.generateKeyPair( "RSA" );
-
-
+
+ SAML2Object saml2Object = new SAML2Object()
+ {
+ };
+
+ KeyPair keypair = KeyStoreUtil.generateKeyPair("RSA");
+
SAML2Response saml2Response = new SAML2Response();
- IssuerInfoHolder issuerInfoholder = new IssuerInfoHolder( "testIssuer" );
-
- AssertionType assertion = AssertionUtil.createAssertion( IDGenerator.create("ID_") , new NameIDType() );
+ IssuerInfoHolder issuerInfoholder = new IssuerInfoHolder("testIssuer");
+
+ AssertionType assertion = AssertionUtil.createAssertion(IDGenerator.create("ID_"), new NameIDType());
SubjectType assertionSubject = new SubjectType();
STSubType subType = new STSubType();
NameIDType anil = new NameIDType();
- anil.setValue( "anil" );
- subType.addBaseID( anil );
+ anil.setValue("anil");
+ subType.addBaseID(anil);
assertionSubject.setSubType(subType);
assertion.setSubject(assertionSubject);
-
- ResponseType responseType =
- saml2Response.createResponseType(IDGenerator.create("ID_"), issuerInfoholder, assertion);
-
+
+ ResponseType responseType = saml2Response.createResponseType(IDGenerator.create("ID_"), issuerInfoholder,
+ assertion);
+
String assertionNS = JBossSAMLURIConstants.ASSERTION_NSURI.get();
-
+
QName assertionQName = new QName(assertionNS, "EncryptedAssertion", "saml");
Document responseDoc = saml2Response.convert(responseType);
-
- byte[] secret = WSTrustUtil.createRandomSecret((int) 128 / 8);
+
+ byte[] secret = WSTrustUtil.createRandomSecret(128 / 8);
SecretKey secretKey = new SecretKeySpec(secret, "AES");
-
+
PublicKey publicKey = keypair.getPublic();
- XMLEncryptionUtil.encryptElement(new QName(assertionNS, "Assertion", "saml" ), responseDoc , publicKey, secretKey, 128, assertionQName, true);
-
- System.out.println( DocumentUtil.asString(responseDoc));
-
+ XMLEncryptionUtil.encryptElement(new QName(assertionNS, "Assertion", "saml"), responseDoc, publicKey, secretKey,
+ 128, assertionQName, true);
+
+ System.out.println(DocumentUtil.asString(responseDoc));
+
SAMLParser parser = new SAMLParser();
- saml2Object = (SAML2Object) parser.parse( DocumentUtil.getNodeAsStream(responseDoc));
-
+ saml2Object = (SAML2Object) parser.parse(DocumentUtil.getNodeAsStream(responseDoc));
+
SAMLDocumentHolder docHolder = new SAMLDocumentHolder(saml2Object, null);
IssuerInfoHolder issuerInfo = new IssuerInfoHolder("http://localhost:8080/idp/");
- SAML2HandlerRequest request = new DefaultSAML2HandlerRequest(httpContext,
- issuerInfo.getIssuer(), docHolder, SAML2Handler.HANDLER_TYPE.SP);
- request.addOption( GeneralConstants.DECRYPTING_KEY, keypair.getPrivate() );
-
+ SAML2HandlerRequest request = new DefaultSAML2HandlerRequest(httpContext, issuerInfo.getIssuer(), docHolder,
+ SAML2Handler.HANDLER_TYPE.SP);
+ request.addOption(GeneralConstants.DECRYPTING_KEY, keypair.getPrivate());
+
SAML2HandlerResponse response = new DefaultSAML2HandlerResponse();
-
+
session.setAttribute(GeneralConstants.PRINCIPAL_ID, new Principal()
{
public String getName()
{
return "Hi";
- }});
-
-
- handler.handleStatusResponseType(request, response);
- }
+ }
+ });
+
+ handler.handleStatusResponseType(request, response);
+ }
}
\ No newline at end of file
13 years, 10 months
Picketlink SVN: r788 - in picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation: configuration and 1 other directories.
by picketlink-commits@lists.jboss.org
Author: anil.saldhana(a)jboss.com
Date: 2011-03-02 12:26:35 -0500 (Wed, 02 Mar 2011)
New Revision: 788
Added:
picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/util/
picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/util/PicketLinkSeamUtil.java
picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/util/SecurityActions.java
Modified:
picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/configuration/Configuration.java
picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/configuration/SamlConfiguration.java
Log:
PLFED-155: use tccl as backup
Modified: picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/configuration/Configuration.java
===================================================================
--- picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/configuration/Configuration.java 2011-03-01 19:35:51 UTC (rev 787)
+++ picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/configuration/Configuration.java 2011-03-02 17:26:35 UTC (rev 788)
@@ -48,6 +48,7 @@
import org.picketlink.identity.federation.core.util.StringUtil;
import org.picketlink.identity.seam.federation.jaxb.config.ExternalAuthenticationConfigType;
import org.picketlink.identity.seam.federation.jaxb.config.ServiceProviderType;
+import org.picketlink.identity.seam.federation.util.PicketLinkSeamUtil;
import org.xml.sax.SAXException;
/**
@@ -96,7 +97,7 @@
{
JAXBContext jaxbContext = JAXBContext.newInstance("org.picketlink.identity.seam.federation.jaxb.config");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
- URL schemaURL = getClass().getResource("/schema/config/external-authentication-config.xsd");
+ URL schemaURL = PicketLinkSeamUtil.loadResource(getClass(), "/schema/config/external-authentication-config.xsd" );
Schema schema;
try
{
@@ -108,7 +109,7 @@
}
unmarshaller.setSchema(schema);
- JAXBElement<?> o = (JAXBElement<?>) unmarshaller.unmarshal(getClass().getResource(CONFIGURATION_FILE));
+ JAXBElement<?> o = (JAXBElement<?>) unmarshaller.unmarshal( PicketLinkSeamUtil.loadResource( getClass(), CONFIGURATION_FILE));
externalAuthenticationConfig = (ExternalAuthenticationConfigType) o.getValue();
}
catch (JAXBException e)
Modified: picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/configuration/SamlConfiguration.java
===================================================================
--- picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/configuration/SamlConfiguration.java 2011-03-01 19:35:51 UTC (rev 787)
+++ picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/configuration/SamlConfiguration.java 2011-03-02 17:26:35 UTC (rev 788)
@@ -46,6 +46,7 @@
import org.picketlink.identity.federation.newmodel.saml.v2.metadata.IDPSSODescriptorType;
import org.picketlink.identity.seam.federation.jaxb.config.SamlConfigType;
import org.picketlink.identity.seam.federation.jaxb.config.SamlIdentityProviderType;
+import org.picketlink.identity.seam.federation.util.PicketLinkSeamUtil;
/**
@@ -136,7 +137,7 @@
{
try
{
- InputStream samlEntitiesStream = getClass().getResourceAsStream( SAML_ENTITIES_FILE );
+ InputStream samlEntitiesStream = PicketLinkSeamUtil.loadResourceAsStream( getClass(), SAML_ENTITIES_FILE );
if( samlEntitiesStream == null )
throw new RuntimeException( "SAML Entities File is missing" );
@@ -206,7 +207,7 @@
InputStream keyStoreStream;
if (keyStoreUrl.startsWith(classPathPrefix))
{
- keyStoreStream = getClass().getClassLoader().getResourceAsStream(
+ keyStoreStream = PicketLinkSeamUtil.loadResourceAsStream( getClass(),
keyStoreUrl.substring(classPathPrefix.length()));
}
else
Added: picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/util/PicketLinkSeamUtil.java
===================================================================
--- picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/util/PicketLinkSeamUtil.java (rev 0)
+++ picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/util/PicketLinkSeamUtil.java 2011-03-02 17:26:35 UTC (rev 788)
@@ -0,0 +1,71 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.picketlink.identity.seam.federation.util;
+
+import java.io.InputStream;
+import java.net.URL;
+
+/**
+ * Utility class
+ * @author Anil.Saldhana(a)redhat.com
+ * @since Mar 2, 2011
+ */
+public class PicketLinkSeamUtil
+{
+ /**
+ * Get a resource first with the {@link ClassLoader}
+ * of the current class. If we do not find the resource,
+ * then we try with the Thread Context ClassLoader
+ * @param currentClass
+ * @param resource
+ * @return {@link InputStream} or null
+ */
+ public static InputStream loadResourceAsStream( Class<?> currentClass, String resource )
+ {
+ InputStream is = null;
+ ClassLoader cl = SecurityActions.getClassLoader(currentClass);
+ if( cl != null )
+ is = cl.getResourceAsStream(resource);
+ if( is == null )
+ is = SecurityActions.getTCCL().getResourceAsStream(resource);
+ return is;
+ }
+
+ /**
+ * Get a resource first with the {@link ClassLoader}
+ * of the current class. If we do not find the resource,
+ * then we try with the Thread Context ClassLoader
+ * @param currentClass
+ * @param resource
+ * @return {@link URL} or null
+ */
+ public static URL loadResource( Class<?> currentClass, String resource )
+ {
+ URL url = null;
+ ClassLoader cl = SecurityActions.getClassLoader(currentClass);
+ if( cl != null )
+ url = cl.getResource(resource);
+ if( url == null )
+ url = SecurityActions.getTCCL().getResource(resource);
+ return url;
+ }
+}
\ No newline at end of file
Added: picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/util/SecurityActions.java
===================================================================
--- picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/util/SecurityActions.java (rev 0)
+++ picketlink-seam/trunk/picketlink-seam/src/main/java/org/picketlink/identity/seam/federation/util/SecurityActions.java 2011-03-02 17:26:35 UTC (rev 788)
@@ -0,0 +1,55 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.picketlink.identity.seam.federation.util;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+
+/**
+ * Privileged Actions
+ * @author Anil.Saldhana(a)redhat.com
+ * @since Mar 2, 2011
+ */
+public class SecurityActions
+{
+ static ClassLoader getClassLoader( final Class<?> clazz )
+ {
+ return AccessController.doPrivileged( new PrivilegedAction<ClassLoader>()
+ {
+ public ClassLoader run()
+ {
+ return clazz.getClassLoader();
+ }
+ });
+ }
+
+ static ClassLoader getTCCL()
+ {
+ return AccessController.doPrivileged( new PrivilegedAction<ClassLoader>()
+ {
+ public ClassLoader run()
+ {
+ return Thread.currentThread().getContextClassLoader();
+ }
+ });
+ }
+}
\ No newline at end of file
13 years, 10 months
Picketlink SVN: r787 - in federation/trunk/picketlink-fed-core/src: main/java/org/picketlink/identity/federation/core/saml/v2/constants and 2 other directories.
by picketlink-commits@lists.jboss.org
Author: anil.saldhana(a)jboss.com
Date: 2011-03-01 14:35:51 -0500 (Tue, 01 Mar 2011)
New Revision: 787
Modified:
federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/parsers/util/SAMLParserUtil.java
federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/constants/JBossSAMLConstants.java
federation/trunk/picketlink-fed-core/src/test/java/org/picketlink/test/identity/federation/core/parser/saml/SAMLResponseParserTestCase.java
federation/trunk/picketlink-fed-core/src/test/resources/parser/saml2/saml2-response.xml
Log:
PLFED-152: consider SubjectLocality
Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/parsers/util/SAMLParserUtil.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/parsers/util/SAMLParserUtil.java 2011-03-01 19:10:15 UTC (rev 786)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/parsers/util/SAMLParserUtil.java 2011-03-01 19:35:51 UTC (rev 787)
@@ -37,7 +37,7 @@
import org.picketlink.identity.federation.core.exceptions.ParsingException;
import org.picketlink.identity.federation.core.saml.v2.constants.JBossSAMLConstants;
import org.picketlink.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
-import org.picketlink.identity.federation.core.saml.v2.util.XMLTimeUtil;
+import org.picketlink.identity.federation.core.saml.v2.util.XMLTimeUtil;
import org.picketlink.identity.federation.core.util.StringUtil;
import org.picketlink.identity.federation.newmodel.saml.v2.assertion.AttributeStatementType;
import org.picketlink.identity.federation.newmodel.saml.v2.assertion.AttributeStatementType.ASTChoiceType;
@@ -47,6 +47,7 @@
import org.picketlink.identity.federation.newmodel.saml.v2.assertion.AuthnContextType;
import org.picketlink.identity.federation.newmodel.saml.v2.assertion.AuthnStatementType;
import org.picketlink.identity.federation.newmodel.saml.v2.assertion.NameIDType;
+import org.picketlink.identity.federation.newmodel.saml.v2.assertion.SubjectLocalityType;
/**
* Utility methods for SAML Parser
@@ -61,55 +62,55 @@
* @return
* @throws ParsingException
*/
- public static AttributeStatementType parseAttributeStatement( XMLEventReader xmlEventReader ) throws ParsingException
+ public static AttributeStatementType parseAttributeStatement(XMLEventReader xmlEventReader) throws ParsingException
{
AttributeStatementType attributeStatementType = new AttributeStatementType();
-
+
StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
String ATTRIBSTATEMT = JBossSAMLConstants.ATTRIBUTE_STATEMENT.get();
- StaxParserUtil.validate( startElement, ATTRIBSTATEMT );
-
- while( xmlEventReader.hasNext() )
+ StaxParserUtil.validate(startElement, ATTRIBSTATEMT);
+
+ while (xmlEventReader.hasNext())
{
XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader);
- if( xmlEvent instanceof EndElement )
+ if (xmlEvent instanceof EndElement)
{
EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
- StaxParserUtil.validate(endElement, JBossSAMLConstants.ATTRIBUTE_STATEMENT.get() );
+ StaxParserUtil.validate(endElement, JBossSAMLConstants.ATTRIBUTE_STATEMENT.get());
break;
}
//Get the next start element
- startElement = StaxParserUtil.peekNextStartElement( xmlEventReader );
+ startElement = StaxParserUtil.peekNextStartElement(xmlEventReader);
String tag = startElement.getName().getLocalPart();
- if( JBossSAMLConstants.ATTRIBUTE.get().equals( tag ) )
+ if (JBossSAMLConstants.ATTRIBUTE.get().equals(tag))
{
AttributeType attribute = parseAttribute(xmlEventReader);
- attributeStatementType.addAttribute( new ASTChoiceType( attribute ));
+ attributeStatementType.addAttribute(new ASTChoiceType(attribute));
}
- else throw new RuntimeException( "Unknown tag:" + tag + "::Location=" + startElement.getLocation() );
- }
+ else
+ throw new RuntimeException("Unknown tag:" + tag + "::Location=" + startElement.getLocation());
+ }
return attributeStatementType;
}
-
+
/**
* Parse an {@code AttributeType}
* @param xmlEventReader
* @return
* @throws ParsingException
*/
- public static AttributeType parseAttribute( XMLEventReader xmlEventReader ) throws ParsingException
- {
- StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
- StaxParserUtil.validate( startElement, JBossSAMLConstants.ATTRIBUTE.get() );
+ public static AttributeType parseAttribute(XMLEventReader xmlEventReader) throws ParsingException
+ {
+ StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
+ StaxParserUtil.validate(startElement, JBossSAMLConstants.ATTRIBUTE.get());
AttributeType attributeType = null;
-
- Attribute name = startElement.getAttributeByName( new QName( JBossSAMLConstants.NAME.get() ));
- if( name == null )
- throw new RuntimeException( "Required attribute Name in Attribute" );
- attributeType = new AttributeType( StaxParserUtil.getAttributeValue( name ));
-
+
+ Attribute name = startElement.getAttributeByName(new QName(JBossSAMLConstants.NAME.get()));
+ if (name == null)
+ throw new RuntimeException("Required attribute Name in Attribute");
+ attributeType = new AttributeType(StaxParserUtil.getAttributeValue(name));
+
parseAttributeType(xmlEventReader, startElement, JBossSAMLConstants.ATTRIBUTE.get(), attributeType);
-
/*//Look for X500 Encoding
QName x500EncodingName = new QName( JBossSAMLURIConstants.X500_NSURI.get(),
@@ -154,229 +155,277 @@
}
else throw new RuntimeException( "Unknown tag:" + tag );
}*/
-
- return attributeType;
+
+ return attributeType;
}
-
+
/**
* Parse an {@code AttributeType}
* @param xmlEventReader
* @throws ParsingException
*/
- public static void parseAttributeType( XMLEventReader xmlEventReader,
- StartElement startElement, String rootTag, AttributeType attributeType ) throws ParsingException
- {
+ public static void parseAttributeType(XMLEventReader xmlEventReader, StartElement startElement, String rootTag,
+ AttributeType attributeType) throws ParsingException
+ {
//Look for X500 Encoding
- QName x500EncodingName = new QName( JBossSAMLURIConstants.X500_NSURI.get(),
- JBossSAMLConstants.ENCODING.get(), JBossSAMLURIConstants.X500_PREFIX.get() );
- Attribute x500EncodingAttr = startElement.getAttributeByName( x500EncodingName );
-
- if( x500EncodingAttr != null )
- {
- attributeType.getOtherAttributes().put( x500EncodingAttr.getName(), StaxParserUtil.getAttributeValue( x500EncodingAttr ));
- }
-
- Attribute friendlyName = startElement.getAttributeByName( new QName( JBossSAMLConstants.FRIENDLY_NAME.get() ));
- if( friendlyName != null )
- attributeType.setFriendlyName( StaxParserUtil.getAttributeValue( friendlyName ));
-
- Attribute nameFormat = startElement.getAttributeByName( new QName( JBossSAMLConstants.NAME_FORMAT.get() ));
- if( nameFormat != null )
- attributeType.setNameFormat( StaxParserUtil.getAttributeValue( nameFormat ));
-
- while( xmlEventReader.hasNext() )
+ QName x500EncodingName = new QName(JBossSAMLURIConstants.X500_NSURI.get(), JBossSAMLConstants.ENCODING.get(),
+ JBossSAMLURIConstants.X500_PREFIX.get());
+ Attribute x500EncodingAttr = startElement.getAttributeByName(x500EncodingName);
+
+ if (x500EncodingAttr != null)
{
+ attributeType.getOtherAttributes().put(x500EncodingAttr.getName(),
+ StaxParserUtil.getAttributeValue(x500EncodingAttr));
+ }
+
+ Attribute friendlyName = startElement.getAttributeByName(new QName(JBossSAMLConstants.FRIENDLY_NAME.get()));
+ if (friendlyName != null)
+ attributeType.setFriendlyName(StaxParserUtil.getAttributeValue(friendlyName));
+
+ Attribute nameFormat = startElement.getAttributeByName(new QName(JBossSAMLConstants.NAME_FORMAT.get()));
+ if (nameFormat != null)
+ attributeType.setNameFormat(StaxParserUtil.getAttributeValue(nameFormat));
+
+ while (xmlEventReader.hasNext())
+ {
XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader);
- if( xmlEvent instanceof EndElement )
+ if (xmlEvent instanceof EndElement)
{
EndElement end = StaxParserUtil.getNextEndElement(xmlEventReader);
- if( StaxParserUtil.matches( end, rootTag ))
+ if (StaxParserUtil.matches(end, rootTag))
break;
}
startElement = StaxParserUtil.peekNextStartElement(xmlEventReader);
- if( startElement == null )
+ if (startElement == null)
break;
String tag = StaxParserUtil.getStartElementName(startElement);
-
- if( JBossSAMLConstants.ATTRIBUTE.get().equals( tag ))
+
+ if (JBossSAMLConstants.ATTRIBUTE.get().equals(tag))
break;
-
- if( JBossSAMLConstants.ATTRIBUTE_VALUE.get().equals( tag ) )
+
+ if (JBossSAMLConstants.ATTRIBUTE_VALUE.get().equals(tag))
{
Object attributeValue = parseAttributeValue(xmlEventReader);
- attributeType.addAttributeValue( attributeValue );
+ attributeType.addAttributeValue(attributeValue);
}
- else throw new RuntimeException( "Unknown tag:" + tag + "::Location=" + startElement.getLocation() );
+ else
+ throw new RuntimeException("Unknown tag:" + tag + "::Location=" + startElement.getLocation());
}
}
-
+
/**
* Parse Attribute value
* @param xmlEventReader
* @return
* @throws ParsingException
*/
- public static Object parseAttributeValue( XMLEventReader xmlEventReader ) throws ParsingException
+ public static Object parseAttributeValue(XMLEventReader xmlEventReader) throws ParsingException
{
StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
- StaxParserUtil.validate( startElement, JBossSAMLConstants.ATTRIBUTE_VALUE.get() );
-
- Attribute type = startElement.getAttributeByName( new QName( JBossSAMLURIConstants.XSI_NSURI.get(),
- "type", "xsi"));
- if( type == null )
+ StaxParserUtil.validate(startElement, JBossSAMLConstants.ATTRIBUTE_VALUE.get());
+
+ Attribute type = startElement.getAttributeByName(new QName(JBossSAMLURIConstants.XSI_NSURI.get(), "type", "xsi"));
+ if (type == null)
{
return StaxParserUtil.getElementText(xmlEventReader);
- }
-
- String typeValue = StaxParserUtil.getAttributeValue(type);
- if( typeValue.contains( ":string" ))
+ }
+
+ String typeValue = StaxParserUtil.getAttributeValue(type);
+ if (typeValue.contains(":string"))
{
return StaxParserUtil.getElementText(xmlEventReader);
}
-
- throw new RuntimeException( "Unsupported xsi:type=" + typeValue );
+
+ throw new RuntimeException("Unsupported xsi:type=" + typeValue);
}
-
+
/**
* Parse the AuthnStatement inside the assertion
* @param xmlEventReader
* @return
* @throws ParsingException
*/
- public static AuthnStatementType parseAuthnStatement( XMLEventReader xmlEventReader ) throws ParsingException
+ public static AuthnStatementType parseAuthnStatement(XMLEventReader xmlEventReader) throws ParsingException
{
-
StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
String AUTHNSTATEMENT = JBossSAMLConstants.AUTHN_STATEMENT.get();
- StaxParserUtil.validate( startElement, AUTHNSTATEMENT );
-
- Attribute authnInstant = startElement.getAttributeByName( new QName( "AuthnInstant" ));
- if( authnInstant == null )
- throw new RuntimeException( "Required attribute AuthnInstant in " + AUTHNSTATEMENT );
+ StaxParserUtil.validate(startElement, AUTHNSTATEMENT);
- XMLGregorianCalendar issueInstant = XMLTimeUtil.parse( StaxParserUtil.getAttributeValue( authnInstant ));
- AuthnStatementType authnStatementType = new AuthnStatementType( issueInstant );
-
- Attribute sessionIndex = startElement.getAttributeByName( new QName( "SessionIndex" ));
- if( sessionIndex != null )
- authnStatementType.setSessionIndex( StaxParserUtil.getAttributeValue( sessionIndex ));
-
- //Get the next start element
- startElement = StaxParserUtil.peekNextStartElement( xmlEventReader );
- String tag = startElement.getName().getLocalPart();
- if( JBossSAMLConstants.AUTHN_CONTEXT.get().equals( tag ) )
+ Attribute authnInstant = startElement.getAttributeByName(new QName("AuthnInstant"));
+ if (authnInstant == null)
+ throw new RuntimeException("Required attribute AuthnInstant in " + AUTHNSTATEMENT);
+
+ XMLGregorianCalendar issueInstant = XMLTimeUtil.parse(StaxParserUtil.getAttributeValue(authnInstant));
+ AuthnStatementType authnStatementType = new AuthnStatementType(issueInstant);
+
+ Attribute sessionIndex = startElement.getAttributeByName(new QName("SessionIndex"));
+ if (sessionIndex != null)
+ authnStatementType.setSessionIndex(StaxParserUtil.getAttributeValue(sessionIndex));
+
+ while (xmlEventReader.hasNext())
{
- authnStatementType.setAuthnContext( parseAuthnContextType( xmlEventReader ) );
+ XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader);
+ if (xmlEvent == null)
+ break;
+
+ if (xmlEvent instanceof EndElement)
+ {
+ xmlEvent = StaxParserUtil.getNextEvent(xmlEventReader);
+ EndElement endElement = (EndElement) xmlEvent;
+ String endElementTag = StaxParserUtil.getEndElementName(endElement);
+ if (endElementTag.equals(AUTHNSTATEMENT))
+ break;
+ else
+ throw new RuntimeException("Unknown End Element:" + endElementTag);
+ }
+ startElement = null;
+
+ if (xmlEvent instanceof StartElement)
+ {
+ startElement = (StartElement) xmlEvent;
+ }
+ else
+ {
+ startElement = StaxParserUtil.peekNextStartElement(xmlEventReader);
+ }
+ if (startElement == null)
+ break;
+
+ String tag = StaxParserUtil.getStartElementName(startElement);
+
+ if (JBossSAMLConstants.SUBJECT_LOCALITY.get().equals(tag))
+ {
+ startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
+ SubjectLocalityType subjectLocalityType = new SubjectLocalityType();
+ Attribute address = startElement.getAttributeByName(new QName(JBossSAMLConstants.ADDRESS.get()));
+ if (address != null)
+ {
+ subjectLocalityType.setAddress(StaxParserUtil.getAttributeValue(address));
+ }
+ Attribute dns = startElement.getAttributeByName(new QName(JBossSAMLConstants.DNS_NAME.get()));
+ if (dns != null)
+ {
+ subjectLocalityType.setDNSName(StaxParserUtil.getAttributeValue(dns));
+ }
+ authnStatementType.setSubjectLocality(subjectLocalityType);
+ StaxParserUtil.validate(StaxParserUtil.getNextEndElement(xmlEventReader),
+ JBossSAMLConstants.SUBJECT_LOCALITY.get());
+ }
+ else if (JBossSAMLConstants.AUTHN_CONTEXT.get().equals(tag))
+ {
+ authnStatementType.setAuthnContext(parseAuthnContextType(xmlEventReader));
+ }
+ else
+ throw new RuntimeException("Unknown tag:" + tag + "::Location=" + startElement.getLocation());
+
}
- else throw new RuntimeException( "Unknown tag:" + tag + "::Location=" + startElement.getLocation() );
-
- EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
- StaxParserUtil.validate(endElement, AUTHNSTATEMENT );
-
+
return authnStatementType;
}
-
+
/**
* Parse the AuthnContext Type inside the AuthnStatement
* @param xmlEventReader
* @return
* @throws ParsingException
*/
- public static AuthnContextType parseAuthnContextType( XMLEventReader xmlEventReader ) throws ParsingException
+ public static AuthnContextType parseAuthnContextType(XMLEventReader xmlEventReader) throws ParsingException
{
AuthnContextType authnContextType = new AuthnContextType();
-
+
StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
- StaxParserUtil.validate( startElement, JBossSAMLConstants.AUTHN_CONTEXT.get() );
-
+ StaxParserUtil.validate(startElement, JBossSAMLConstants.AUTHN_CONTEXT.get());
+
//Get the next start element
startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
String tag = startElement.getName().getLocalPart();
-
- if( JBossSAMLConstants.AUTHN_CONTEXT_DECLARATION_REF.get().equals( tag ))
+
+ if (JBossSAMLConstants.AUTHN_CONTEXT_DECLARATION_REF.get().equals(tag))
{
- String text = StaxParserUtil.getElementText( xmlEventReader );
-
- AuthnContextDeclRefType aAuthnContextDeclType = new AuthnContextDeclRefType( URI.create(text));
- authnContextType.addURIType(aAuthnContextDeclType);
+ String text = StaxParserUtil.getElementText(xmlEventReader);
+
+ AuthnContextDeclRefType aAuthnContextDeclType = new AuthnContextDeclRefType(URI.create(text));
+ authnContextType.addURIType(aAuthnContextDeclType);
EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
- StaxParserUtil.validate(endElement, JBossSAMLConstants.AUTHN_CONTEXT.get() );
+ StaxParserUtil.validate(endElement, JBossSAMLConstants.AUTHN_CONTEXT.get());
}
- else if( JBossSAMLConstants.AUTHN_CONTEXT_CLASS_REF.get().equals( tag ))
+ else if (JBossSAMLConstants.AUTHN_CONTEXT_CLASS_REF.get().equals(tag))
{
- String text = StaxParserUtil.getElementText( xmlEventReader );
-
- AuthnContextClassRefType aAuthnContextClassRefType = new AuthnContextClassRefType( URI.create(text));
- authnContextType.addURIType( aAuthnContextClassRefType );
+ String text = StaxParserUtil.getElementText(xmlEventReader);
+
+ AuthnContextClassRefType aAuthnContextClassRefType = new AuthnContextClassRefType(URI.create(text));
+ authnContextType.addURIType(aAuthnContextClassRefType);
EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
- StaxParserUtil.validate(endElement, JBossSAMLConstants.AUTHN_CONTEXT.get() );
+ StaxParserUtil.validate(endElement, JBossSAMLConstants.AUTHN_CONTEXT.get());
}
else
- throw new RuntimeException( "Unknown Tag:" + tag + "::Location=" + startElement.getLocation() );
-
+ throw new RuntimeException("Unknown Tag:" + tag + "::Location=" + startElement.getLocation());
+
return authnContextType;
- }
-
+ }
+
/**
* Parse a {@code NameIDType}
* @param xmlEventReader
* @return
* @throws ParsingException
*/
- public static NameIDType parseNameIDType( XMLEventReader xmlEventReader ) throws ParsingException
+ public static NameIDType parseNameIDType(XMLEventReader xmlEventReader) throws ParsingException
{
- StartElement nameIDElement = StaxParserUtil.getNextStartElement( xmlEventReader );
+ StartElement nameIDElement = StaxParserUtil.getNextStartElement(xmlEventReader);
NameIDType nameID = new NameIDType();
-
- Attribute nameQualifier = nameIDElement.getAttributeByName( new QName( JBossSAMLConstants.NAME_QUALIFIER.get() ));
- if( nameQualifier != null )
+
+ Attribute nameQualifier = nameIDElement.getAttributeByName(new QName(JBossSAMLConstants.NAME_QUALIFIER.get()));
+ if (nameQualifier != null)
{
- nameID.setNameQualifier( StaxParserUtil.getAttributeValue(nameQualifier) );
- }
-
- Attribute format = nameIDElement.getAttributeByName( new QName( JBossSAMLConstants.FORMAT.get() ));
- if( format != null )
+ nameID.setNameQualifier(StaxParserUtil.getAttributeValue(nameQualifier));
+ }
+
+ Attribute format = nameIDElement.getAttributeByName(new QName(JBossSAMLConstants.FORMAT.get()));
+ if (format != null)
{
- nameID.setFormat( URI.create( StaxParserUtil.getAttributeValue( format )) );
+ nameID.setFormat(URI.create(StaxParserUtil.getAttributeValue(format)));
}
-
- Attribute spProvidedID = nameIDElement.getAttributeByName( new QName( JBossSAMLConstants.SP_PROVIDED_ID.get() ));
- if( spProvidedID != null )
+
+ Attribute spProvidedID = nameIDElement.getAttributeByName(new QName(JBossSAMLConstants.SP_PROVIDED_ID.get()));
+ if (spProvidedID != null)
{
- nameID.setSPProvidedID( StaxParserUtil.getAttributeValue( spProvidedID ));
+ nameID.setSPProvidedID(StaxParserUtil.getAttributeValue(spProvidedID));
}
-
- Attribute spNameQualifier = nameIDElement.getAttributeByName( new QName( JBossSAMLConstants.SP_NAME_QUALIFIER.get() ));
- if( spNameQualifier != null )
+
+ Attribute spNameQualifier = nameIDElement
+ .getAttributeByName(new QName(JBossSAMLConstants.SP_NAME_QUALIFIER.get()));
+ if (spNameQualifier != null)
{
- nameID.setSPNameQualifier( StaxParserUtil.getAttributeValue( spNameQualifier ));
+ nameID.setSPNameQualifier(StaxParserUtil.getAttributeValue(spNameQualifier));
}
- String nameIDValue = StaxParserUtil.getElementText( xmlEventReader );
- nameID.setValue( nameIDValue );
-
+ String nameIDValue = StaxParserUtil.getElementText(xmlEventReader);
+ nameID.setValue(nameIDValue);
+
return nameID;
}
-
+
/**
* Parse a space delimited list of strings
* @param startElement
* @return
*/
- public static List<String> parseProtocolEnumeration( StartElement startElement )
+ public static List<String> parseProtocolEnumeration(StartElement startElement)
{
List<String> protocolEnum = new ArrayList<String>();
- Attribute proto = startElement.getAttributeByName( new QName( JBossSAMLConstants.PROTOCOL_SUPPORT_ENUMERATION.get() ) );
+ Attribute proto = startElement
+ .getAttributeByName(new QName(JBossSAMLConstants.PROTOCOL_SUPPORT_ENUMERATION.get()));
String val = StaxParserUtil.getAttributeValue(proto);
- if( StringUtil.isNotNull( val ))
+ if (StringUtil.isNotNull(val))
{
- StringTokenizer st = new StringTokenizer( val );
- while( st.hasMoreTokens() )
+ StringTokenizer st = new StringTokenizer(val);
+ while (st.hasMoreTokens())
{
- protocolEnum.add( st.nextToken() );
+ protocolEnum.add(st.nextToken());
}
-
+
}
- return protocolEnum;
+ return protocolEnum;
}
}
\ No newline at end of file
Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/constants/JBossSAMLConstants.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/constants/JBossSAMLConstants.java 2011-03-01 19:10:15 UTC (rev 786)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/constants/JBossSAMLConstants.java 2011-03-01 19:35:51 UTC (rev 787)
@@ -62,6 +62,7 @@
CONTACT_PERSON( "ContactPerson" ),
CONTACT_TYPE( "contactType" ),
DESTINATION( "Destination" ),
+ DNS_NAME( "DNSName"),
EMAIL_ADDRESS( "EmailAddress" ),
ENCODING( "Encoding" ),
ENCRYPTED_ASSERTION( "EncryptedAssertion" ),
@@ -137,6 +138,7 @@
SUBJECT( "Subject" ),
SUBJECT_CONFIRMATION( "SubjectConfirmation" ),
SUBJECT_CONFIRMATION_DATA( "SubjectConfirmationData" ),
+ SUBJECT_LOCALITY( "SubjectLocality" ),
SURNAME( "SurName" ),
TELEPHONE_NUMBER( "TelephoneNumber" ),
TYPE( "type" ),
Modified: federation/trunk/picketlink-fed-core/src/test/java/org/picketlink/test/identity/federation/core/parser/saml/SAMLResponseParserTestCase.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/test/java/org/picketlink/test/identity/federation/core/parser/saml/SAMLResponseParserTestCase.java 2011-03-01 19:10:15 UTC (rev 786)
+++ federation/trunk/picketlink-fed-core/src/test/java/org/picketlink/test/identity/federation/core/parser/saml/SAMLResponseParserTestCase.java 2011-03-01 19:35:51 UTC (rev 787)
@@ -46,6 +46,7 @@
import org.picketlink.identity.federation.newmodel.saml.v2.assertion.StatementAbstractType;
import org.picketlink.identity.federation.newmodel.saml.v2.assertion.SubjectConfirmationDataType;
import org.picketlink.identity.federation.newmodel.saml.v2.assertion.SubjectConfirmationType;
+import org.picketlink.identity.federation.newmodel.saml.v2.assertion.SubjectLocalityType;
import org.picketlink.identity.federation.newmodel.saml.v2.assertion.SubjectType;
import org.picketlink.identity.federation.newmodel.saml.v2.profiles.xacml.assertion.XACMLAuthzDecisionStatementType;
import org.picketlink.identity.federation.newmodel.saml.v2.protocol.ResponseType;
@@ -63,157 +64,161 @@
public void testSAMLResponseParse() throws Exception
{
ClassLoader tcl = Thread.currentThread().getContextClassLoader();
- InputStream configStream = tcl.getResourceAsStream( "parser/saml2/saml2-response.xml" );
-
+ InputStream configStream = tcl.getResourceAsStream("parser/saml2/saml2-response.xml");
+
SAMLParser parser = new SAMLParser();
- ResponseType response = ( ResponseType ) parser.parse(configStream);
- assertNotNull( "ResponseType is not null", response );
-
- assertEquals( XMLTimeUtil.parse( "2009-05-26T14:06:26.362-05:00" ), response.getIssueInstant() );
- assertEquals( "2.0", response.getVersion() );
- assertEquals( "ID_1164e0fc-576d-4797-b11c-3d049520f566", response.getID() );
-
+ ResponseType response = (ResponseType) parser.parse(configStream);
+ assertNotNull("ResponseType is not null", response);
+
+ assertEquals(XMLTimeUtil.parse("2009-05-26T14:06:26.362-05:00"), response.getIssueInstant());
+ assertEquals("2.0", response.getVersion());
+ assertEquals("ID_1164e0fc-576d-4797-b11c-3d049520f566", response.getID());
+
//Issuer
- assertEquals( "testIssuer", response.getIssuer().getValue() );
-
+ assertEquals("testIssuer", response.getIssuer().getValue());
+
//Status
StatusType status = response.getStatus();
- assertEquals( "urn:oasis:names:tc:SAML:2.0:status:Success", status.getStatusCode().getValue().toString() );
-
+ assertEquals("urn:oasis:names:tc:SAML:2.0:status:Success", status.getStatusCode().getValue().toString());
+
List<RTChoiceType> assertionList = response.getAssertions();
- assertEquals( 2, assertionList.size() );
-
- AssertionType assertion1 = assertionList.get( 0 ).getAssertion();
- assertEquals( "ID_0be488d8-7089-4892-8aeb-83594c800706", assertion1.getID() );
- assertEquals( XMLTimeUtil.parse( "2009-05-26T14:06:26.362-05:00" ), assertion1.getIssueInstant() );
- assertEquals( "2.0", assertion1.getVersion() );
- assertEquals( "testIssuer", assertion1.getIssuer().getValue() ) ;
-
+ assertEquals(2, assertionList.size());
+
+ AssertionType assertion1 = assertionList.get(0).getAssertion();
+ assertEquals("ID_0be488d8-7089-4892-8aeb-83594c800706", assertion1.getID());
+ assertEquals(XMLTimeUtil.parse("2009-05-26T14:06:26.362-05:00"), assertion1.getIssueInstant());
+ assertEquals("2.0", assertion1.getVersion());
+ assertEquals("testIssuer", assertion1.getIssuer().getValue());
+
Iterator<StatementAbstractType> iterator = assertion1.getStatements().iterator();
-
+
AuthnStatementType authnStatement = (AuthnStatementType) iterator.next();
- assertEquals( XMLTimeUtil.parse( "2009-05-26T14:06:26.359-05:00" ), authnStatement.getAuthnInstant() );
-
+ assertEquals(XMLTimeUtil.parse("2009-05-26T14:06:26.359-05:00"), authnStatement.getAuthnInstant());
AuthnContextType authnContext = authnStatement.getAuthnContext();
-
+
AuthnContextDeclRefType refType = (AuthnContextDeclRefType) authnContext.getURIType().iterator().next();
- assertEquals( "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport", refType.getValue().toASCIIString() );
+ assertEquals("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport", refType.getValue()
+ .toASCIIString());
/*
JAXBElement<?> authnContextDeclRefJaxb = (JAXBElement<?>) authnStatement.getAuthnContext().getContent().get(0);
assertEquals( "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport", authnContextDeclRefJaxb.getValue() );*/
-
-
- AssertionType assertion2 = (AssertionType) assertionList.get( 1 ).getAssertion();
- assertEquals( "ID_976d8310-658a-450d-be39-f33c73c8afa6", assertion2.getID() );
- assertEquals( XMLTimeUtil.parse( "2009-05-26T14:06:26.363-05:00" ), assertion2.getIssueInstant() );
- assertEquals( "2.0", assertion2.getVersion() );
- assertEquals( "testIssuer", assertion2.getIssuer().getValue() );
-
+
+ AssertionType assertion2 = assertionList.get(1).getAssertion();
+ assertEquals("ID_976d8310-658a-450d-be39-f33c73c8afa6", assertion2.getID());
+ assertEquals(XMLTimeUtil.parse("2009-05-26T14:06:26.363-05:00"), assertion2.getIssueInstant());
+ assertEquals("2.0", assertion2.getVersion());
+ assertEquals("testIssuer", assertion2.getIssuer().getValue());
+
authnStatement = (AuthnStatementType) assertion2.getStatements().iterator().next();
- assertEquals( XMLTimeUtil.parse( "2009-05-26T14:06:26.359-05:00" ), authnStatement.getAuthnInstant() );
+ assertEquals(XMLTimeUtil.parse("2009-05-26T14:06:26.359-05:00"), authnStatement.getAuthnInstant());
+ SubjectLocalityType subjectLocality = authnStatement.getSubjectLocality();
+ assertNotNull(subjectLocality);
+ assertEquals("127.0.0.1", subjectLocality.getAddress());
authnContext = authnStatement.getAuthnContext();
-
+
refType = (AuthnContextDeclRefType) authnContext.getURIType().iterator().next();
- assertEquals( "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport", refType.getValue().toASCIIString() );
-
+ assertEquals("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport", refType.getValue()
+ .toASCIIString());
+
//Let us do some writing - currently only visual inspection. We will do proper validation later.
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- SAMLResponseWriter writer = new SAMLResponseWriter(StaxUtil.getXMLStreamWriter(baos));
- writer.write(response );
-
- System.out.println( new String( baos.toByteArray() ));
-
- ByteArrayInputStream bis = new ByteArrayInputStream( baos.toByteArray() );
- DocumentUtil.getDocument( bis ); //throws exceptions
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ SAMLResponseWriter writer = new SAMLResponseWriter(StaxUtil.getXMLStreamWriter(baos));
+ writer.write(response);
+
+ System.out.println(new String(baos.toByteArray()));
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
+ DocumentUtil.getDocument(bis); //throws exceptions
}
-
+
@Test
public void testAssertionWithSubjectAndAttributes() throws Exception
{
ClassLoader tcl = Thread.currentThread().getContextClassLoader();
- InputStream configStream = tcl.getResourceAsStream( "parser/saml2/saml2-response-assertion-subject.xml" );
-
+ InputStream configStream = tcl.getResourceAsStream("parser/saml2/saml2-response-assertion-subject.xml");
+
SAMLParser parser = new SAMLParser();
- ResponseType response = ( ResponseType ) parser.parse(configStream);
- assertNotNull( response );
-
- assertEquals( "ID_45df1ea5-81e4-4147-a39a-43a4ef613f4e", response.getID() );
- assertEquals( XMLTimeUtil.parse( "2010-11-04T00:19:16.847-05:00" ), response.getIssueInstant() );
- assertEquals( "2.0", response.getVersion() );
- assertEquals( "http://localhost:8080/employee/", response.getDestination() );
- assertEquals( "ID_04ded476-d73c-48af-b3a9-232a52905ffb", response.getInResponseTo() );
-
+ ResponseType response = (ResponseType) parser.parse(configStream);
+ assertNotNull(response);
+
+ assertEquals("ID_45df1ea5-81e4-4147-a39a-43a4ef613f4e", response.getID());
+ assertEquals(XMLTimeUtil.parse("2010-11-04T00:19:16.847-05:00"), response.getIssueInstant());
+ assertEquals("2.0", response.getVersion());
+ assertEquals("http://localhost:8080/employee/", response.getDestination());
+ assertEquals("ID_04ded476-d73c-48af-b3a9-232a52905ffb", response.getInResponseTo());
+
//Issuer
- assertEquals( "http://localhost:8080/idp/", response.getIssuer().getValue() );
-
+ assertEquals("http://localhost:8080/idp/", response.getIssuer().getValue());
+
//Status
StatusType status = response.getStatus();
- assertEquals( "urn:oasis:names:tc:SAML:2.0:status:Success", status.getStatusCode().getValue().toString() );
-
+ assertEquals("urn:oasis:names:tc:SAML:2.0:status:Success", status.getStatusCode().getValue().toString());
+
//Get the assertion
- AssertionType assertion = (AssertionType) response.getAssertions().get(0).getAssertion();
- assertEquals( "ID_8be1534d-9155-4837-9f26-70ea2c15e327", assertion.getID() );
- assertEquals( XMLTimeUtil.parse( "2010-11-04T00:19:16.842-05:00" ), assertion.getIssueInstant() );
- assertEquals( "2.0", assertion.getVersion() );
-
- assertEquals( "http://localhost:8080/idp/", assertion.getIssuer().getValue() );
-
+ AssertionType assertion = response.getAssertions().get(0).getAssertion();
+ assertEquals("ID_8be1534d-9155-4837-9f26-70ea2c15e327", assertion.getID());
+ assertEquals(XMLTimeUtil.parse("2010-11-04T00:19:16.842-05:00"), assertion.getIssueInstant());
+ assertEquals("2.0", assertion.getVersion());
+
+ assertEquals("http://localhost:8080/idp/", assertion.getIssuer().getValue());
+
//Subject
SubjectType subject = assertion.getSubject();
-
+
NameIDType subjectNameID = (NameIDType) subject.getSubType().getBaseID();
- assertEquals( "anil", subjectNameID.getValue() );
- assertEquals( "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent", subjectNameID.getFormat().toString() );
-
+ assertEquals("anil", subjectNameID.getValue());
+ assertEquals("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent", subjectNameID.getFormat().toString());
+
SubjectConfirmationType subjectConfirmation = subject.getConfirmation().get(0);
- assertEquals( "urn:oasis:names:tc:SAML:2.0:cm:bearer", subjectConfirmation.getMethod() );
-
+ assertEquals("urn:oasis:names:tc:SAML:2.0:cm:bearer", subjectConfirmation.getMethod());
+
SubjectConfirmationDataType subjectConfirmationData = subjectConfirmation.getSubjectConfirmationData();
- assertEquals( "ID_04ded476-d73c-48af-b3a9-232a52905ffb", subjectConfirmationData.getInResponseTo() );
- assertEquals( XMLTimeUtil.parse( "2010-11-04T00:19:16.842-05:00" ), subjectConfirmationData.getNotBefore() );
- assertEquals( XMLTimeUtil.parse( "2010-11-04T00:19:16.842-05:00" ), subjectConfirmationData.getNotOnOrAfter() );
- assertEquals( "http://localhost:8080/employee/", subjectConfirmationData.getRecipient());
-
- AttributeStatementType attributeStatement = (AttributeStatementType) assertion.getStatements().iterator().next();
-
+ assertEquals("ID_04ded476-d73c-48af-b3a9-232a52905ffb", subjectConfirmationData.getInResponseTo());
+ assertEquals(XMLTimeUtil.parse("2010-11-04T00:19:16.842-05:00"), subjectConfirmationData.getNotBefore());
+ assertEquals(XMLTimeUtil.parse("2010-11-04T00:19:16.842-05:00"), subjectConfirmationData.getNotOnOrAfter());
+ assertEquals("http://localhost:8080/employee/", subjectConfirmationData.getRecipient());
+
+ AttributeStatementType attributeStatement = (AttributeStatementType) assertion.getStatements().iterator().next();
+
List<AttributeStatementType.ASTChoiceType> attributes = attributeStatement.getAttributes();
- assertEquals( 2, attributes.size() );
-
- for( AttributeStatementType.ASTChoiceType attr: attributes )
+ assertEquals(2, attributes.size());
+
+ for (AttributeStatementType.ASTChoiceType attr : attributes)
{
AttributeType attribute = attr.getAttribute();
- assertEquals( "role", attribute.getFriendlyName() );
- assertEquals( "role", attribute.getName() );
- assertEquals( "role", attribute.getNameFormat() );
+ assertEquals("role", attribute.getFriendlyName());
+ assertEquals("role", attribute.getName());
+ assertEquals("role", attribute.getNameFormat());
List<Object> attributeValues = attribute.getAttributeValue();
- assertEquals( 1, attributeValues.size() );
-
- String str = (String ) attributeValues.get( 0 );
- if( ! ( str.equals( "employee") || str.equals( "manager" )))
- throw new RuntimeException( "attrib value not found" );
- }
+ assertEquals(1, attributeValues.size());
+
+ String str = (String) attributeValues.get(0);
+ if (!(str.equals("employee") || str.equals("manager")))
+ throw new RuntimeException("attrib value not found");
+ }
}
-
+
@Test
public void testXACMLDecisionStatements() throws Exception
{
ClassLoader tcl = Thread.currentThread().getContextClassLoader();
- InputStream configStream = tcl.getResourceAsStream( "saml-xacml/saml-xacml-response-1.xml" );
-
+ InputStream configStream = tcl.getResourceAsStream("saml-xacml/saml-xacml-response-1.xml");
+
SAMLParser parser = new SAMLParser();
- ResponseType response = ( ResponseType ) parser.parse(configStream);
- assertNotNull( "ResponseType is not null", response );
-
+ ResponseType response = (ResponseType) parser.parse(configStream);
+ assertNotNull("ResponseType is not null", response);
+
//Get the assertion
- AssertionType assertion = (AssertionType) response.getAssertions().get(0).getAssertion();
- assertEquals( "ID_response-id:1", assertion.getID() );
- assertEquals( XMLTimeUtil.parse( "2008-03-19T22:17:13Z" ), assertion.getIssueInstant() );
- assertEquals( "2.0", assertion.getVersion() );
-
- XACMLAuthzDecisionStatementType xacmlStat = (XACMLAuthzDecisionStatementType) assertion.getStatements().iterator().next();
- assertNotNull( xacmlStat.getRequest() );
- assertNotNull( xacmlStat.getResponse() );
+ AssertionType assertion = response.getAssertions().get(0).getAssertion();
+ assertEquals("ID_response-id:1", assertion.getID());
+ assertEquals(XMLTimeUtil.parse("2008-03-19T22:17:13Z"), assertion.getIssueInstant());
+ assertEquals("2.0", assertion.getVersion());
+
+ XACMLAuthzDecisionStatementType xacmlStat = (XACMLAuthzDecisionStatementType) assertion.getStatements()
+ .iterator().next();
+ assertNotNull(xacmlStat.getRequest());
+ assertNotNull(xacmlStat.getResponse());
}
}
\ No newline at end of file
Modified: federation/trunk/picketlink-fed-core/src/test/resources/parser/saml2/saml2-response.xml
===================================================================
--- federation/trunk/picketlink-fed-core/src/test/resources/parser/saml2/saml2-response.xml 2011-03-01 19:10:15 UTC (rev 786)
+++ federation/trunk/picketlink-fed-core/src/test/resources/parser/saml2/saml2-response.xml 2011-03-01 19:35:51 UTC (rev 787)
@@ -22,6 +22,7 @@
ID="ID_976d8310-658a-450d-be39-f33c73c8afa6" Version="2.0">
<Issuer>testIssuer</Issuer>
<AuthnStatement AuthnInstant="2009-05-26T14:06:26.359-05:00">
+ <SubjectLocality Address="127.0.0.1"/>
<AuthnContext>
<AuthnContextDeclRef>
urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
13 years, 10 months
Picketlink SVN: r786 - in federation/trunk: picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings and 13 other directories.
by picketlink-commits@lists.jboss.org
Author: anil.saldhana(a)jboss.com
Date: 2011-03-01 14:10:15 -0500 (Tue, 01 Mar 2011)
New Revision: 786
Added:
federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/authenticators/
federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/authenticators/SPPostFormAuthenticatorUnitTestCase.java
federation/trunk/picketlink-bindings/src/test/resources/config/test-idp-metadata-file-config.xml
federation/trunk/picketlink-bindings/src/test/resources/metadata/
federation/trunk/picketlink-bindings/src/test/resources/metadata/testshib.org.idp-metadata.xml
federation/trunk/picketlink-fed-core/src/test/java/org/picketlink/test/identity/federation/core/config/MetadataToSPTypeUnitTestCase.java
Modified:
federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java
federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java
federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java
federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/mock/MockCatalinaContextClassLoader.java
federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/config/SPType.java
federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/parsers/config/SAMLConfigParser.java
federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/constants/JBossSAMLURIConstants.java
federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/CoreConfigUtil.java
federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/XMLSignatureUtil.java
federation/trunk/picketlink-fed-core/src/main/resources/schema/config/picketlink-fed.xsd
federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants/GeneralConstants.java
federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/util/ConfigurationUtil.java
Log:
PLFED-153: let the sp authenticators pick the identity url and idp x509 from a metadata file
Modified: federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java
===================================================================
--- federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java 2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -24,7 +24,9 @@
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
+import java.security.cert.X509Certificate;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
@@ -40,60 +42,77 @@
import org.apache.catalina.connector.Response;
import org.apache.catalina.deploy.LoginConfig;
import org.apache.log4j.Logger;
+import org.picketlink.identity.federation.api.saml.v2.metadata.MetaDataExtractor;
import org.picketlink.identity.federation.core.config.SPType;
import org.picketlink.identity.federation.core.exceptions.ConfigurationException;
+import org.picketlink.identity.federation.core.exceptions.ParsingException;
import org.picketlink.identity.federation.core.exceptions.ProcessingException;
import org.picketlink.identity.federation.core.handler.config.Handlers;
+import org.picketlink.identity.federation.core.parsers.saml.SAMLParser;
+import org.picketlink.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
import org.picketlink.identity.federation.core.saml.v2.factories.SAML2HandlerChainFactory;
import org.picketlink.identity.federation.core.saml.v2.impl.DefaultSAML2HandlerChainConfig;
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2Handler;
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerChain;
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerChainConfig;
import org.picketlink.identity.federation.core.saml.v2.util.HandlerUtil;
+import org.picketlink.identity.federation.core.util.CoreConfigUtil;
import org.picketlink.identity.federation.core.util.StringUtil;
import org.picketlink.identity.federation.core.util.XMLSignatureUtil;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EndpointType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntitiesDescriptorType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntityDescriptorType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.IDPSSODescriptorType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.KeyDescriptorType;
import org.picketlink.identity.federation.web.constants.GeneralConstants;
import org.picketlink.identity.federation.web.util.ConfigurationUtil;
/**
- * Base Class for Form Authenticators
+ * Base Class for Service Provider Form Authenticators
* @author Anil.Saldhana(a)redhat.com
* @since Jun 9, 2009
*/
-public class BaseFormAuthenticator extends FormAuthenticator
+public abstract class BaseFormAuthenticator extends FormAuthenticator
{
private static Logger log = Logger.getLogger(BaseFormAuthenticator.class);
- private boolean trace = log.isTraceEnabled();
-
+
+ private final boolean trace = log.isTraceEnabled();
+
protected SPType spConfiguration = null;
-
+
protected String serviceURL = null;
+
protected String identityURL = null;
-
+
protected String issuerID = null;
protected String configFile = GeneralConstants.CONFIG_FILE_LOCATION;
-
+
+ /**
+ * If the service provider is configured with an IDP metadata file,
+ * then this certificate can be picked up from the metadata
+ */
+ protected transient X509Certificate idpCertificate = null;
+
protected transient SAML2HandlerChain chain = null;
-
- protected transient String samlHandlerChainClass = null;
-
+
+ protected transient String samlHandlerChainClass = null;
+
protected Map<String, Object> chainConfigOptions = new HashMap<String, Object>();
-
+
//Whether the authenticator has to to save and restore request
protected boolean saveRestoreRequest = true;
-
+
/**
* A Lock for Handler operations in the chain
*/
protected Lock chainLock = new ReentrantLock();
-
protected String canonicalizationMethod = CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS;
-
+
public BaseFormAuthenticator()
{
- super();
+ super();
}
public String getConfigFile()
@@ -105,18 +124,22 @@
{
this.configFile = configFile;
}
-
public void setSamlHandlerChainClass(String samlHandlerChainClass)
{
this.samlHandlerChainClass = samlHandlerChainClass;
- }
-
+ }
+
+ public void setServiceURL(String serviceURL)
+ {
+ this.serviceURL = serviceURL;
+ }
+
public void setSaveRestoreRequest(boolean saveRestoreRequest)
{
this.saveRestoreRequest = saveRestoreRequest;
}
-
+
/**
* Set a separate issuer id
* @param issuerID
@@ -135,9 +158,9 @@
*/
protected boolean validate(Request request) throws IOException, GeneralSecurityException
{
- return request.getParameter("SAMLResponse") != null;
+ return request.getParameter("SAMLResponse") != null;
}
-
+
/**
* Authenticate the request
* @param request
@@ -147,104 +170,244 @@
* @throws IOException
* @throws {@link RuntimeException} when the response is not of type catalina response object
*/
- public boolean authenticate( Request request, HttpServletResponse response, LoginConfig config) throws IOException
+ public boolean authenticate(Request request, HttpServletResponse response, LoginConfig config) throws IOException
{
- if( response instanceof Response )
+ if (response instanceof Response)
{
Response catalinaResponse = (Response) response;
- return authenticate(request, catalinaResponse, config);
+ return authenticate(request, catalinaResponse, config);
}
- throw new RuntimeException( "Response was not of type catalina response" );
+ throw new RuntimeException("Response was not of type catalina response");
}
-
+
@Override
public void start() throws LifecycleException
{
super.start();
processStart();
- }
-
+ }
+
+ /**
+ * Get the Identity URL
+ * @return
+ */
+ public String getIdentityURL()
+ {
+ return identityURL;
+ }
+
+ /**
+ * Get the {@link X509Certificate} of the IDP
+ * if provided via the IDP metadata file
+ * @return {@link X509Certificate} or null
+ */
+ public X509Certificate getIdpCertificate()
+ {
+ return idpCertificate;
+ }
+
//Mock test purpose
public void testStart() throws LifecycleException
- {
+ {
this.saveRestoreRequest = false;
+ if (context == null)
+ throw new RuntimeException("Catalina Context not set up");
processStart();
- }
-
+ }
+
private void processStart() throws LifecycleException
{
Handlers handlers = null;
-
+
+ //Get the chain from config
+ if (StringUtil.isNullOrEmpty(samlHandlerChainClass))
+ {
+ chain = SAML2HandlerChainFactory.createChain();
+ }
+ else
+ {
+ try
+ {
+ chain = SAML2HandlerChainFactory.createChain(this.samlHandlerChainClass);
+ }
+ catch (ProcessingException e1)
+ {
+ throw new LifecycleException(e1);
+ }
+ }
+
ServletContext servletContext = context.getServletContext();
+
+ this.processConfiguration();
+
+ try
+ {
+ //Get the handlers
+ String handlerConfigFileName = GeneralConstants.HANDLER_CONFIG_FILE_LOCATION;
+ handlers = ConfigurationUtil.getHandlers(servletContext.getResourceAsStream(handlerConfigFileName));
+ chain.addAll(HandlerUtil.getHandlers(handlers));
+
+ this.populateChainConfig();
+ this.initializeHandlerChain();
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Return the SAML Binding that this authenticator supports
+ * @see {@link JBossSAMLURIConstants#SAML_HTTP_POST_BINDING}
+ * @see {@link JBossSAMLURIConstants#SAML_HTTP_REDIRECT_BINDING}
+ * @return
+ */
+ protected abstract String getBinding();
+
+ /**
+ * Attempt to process a metadata file available locally
+ */
+ protected void processIDPMetadataFile(String idpMetadataFile)
+ {
+ ServletContext servletContext = context.getServletContext();
+ InputStream is = servletContext.getResourceAsStream(idpMetadataFile);
+ if (is == null)
+ return;
+
+ SAMLParser parser = new SAMLParser();
+ Object metadata = null;
+ try
+ {
+ metadata = parser.parse(is);
+ }
+ catch (ParsingException e)
+ {
+ throw new RuntimeException(e);
+ }
+ IDPSSODescriptorType idpSSO = null;
+ if (metadata instanceof EntitiesDescriptorType)
+ {
+ EntitiesDescriptorType entities = (EntitiesDescriptorType) metadata;
+ idpSSO = handleMetadata(entities);
+ }
+ else
+ {
+ idpSSO = handleMetadata((EntityDescriptorType) metadata);
+ }
+ if (idpSSO == null)
+ {
+ log.error("Unable to obtain the IDP SSO Descriptor from metadata");
+ return;
+ }
+ List<EndpointType> endpoints = idpSSO.getSingleSignOnService();
+ for (EndpointType endpoint : endpoints)
+ {
+ if (getBinding().equals(endpoint.getBinding().toString()))
+ {
+ identityURL = endpoint.getLocation().toString();
+ break;
+ }
+ }
+ List<KeyDescriptorType> keyDescriptors = idpSSO.getKeyDescriptor();
+ if (keyDescriptors.size() > 0)
+ {
+ this.idpCertificate = MetaDataExtractor.getCertificate(keyDescriptors.get(0));
+ }
+ }
+
+ /**
+ * Process the configuration from the configuration file
+ */
+ protected void processConfiguration()
+ {
+ ServletContext servletContext = context.getServletContext();
InputStream is = servletContext.getResourceAsStream(configFile);
- if(is == null)
+ if (is == null)
throw new RuntimeException(configFile + " missing");
-
- //Get the chain from config
- if(StringUtil.isNullOrEmpty(samlHandlerChainClass))
- chain = SAML2HandlerChainFactory.createChain();
- else
- try
- {
- chain = SAML2HandlerChainFactory.createChain(this.samlHandlerChainClass);
- }
- catch (ProcessingException e1)
- {
- throw new LifecycleException(e1);
- }
-
try
{
spConfiguration = ConfigurationUtil.getSPConfiguration(is);
- this.identityURL = spConfiguration.getIdentityURL();
+
+ if (StringUtil.isNotNull(spConfiguration.getIdpMetadataFile()))
+ {
+ processIDPMetadataFile(spConfiguration.getIdpMetadataFile());
+ }
+ else
+ {
+ this.identityURL = spConfiguration.getIdentityURL();
+ }
this.serviceURL = spConfiguration.getServiceURL();
this.canonicalizationMethod = spConfiguration.getCanonicalizationMethod();
- log.info( "BaseFormAuthenticator:: Setting the CanonicalizationMethod on XMLSignatureUtil::" + canonicalizationMethod );
+ log.info("BaseFormAuthenticator:: Setting the CanonicalizationMethod on XMLSignatureUtil::"
+ + canonicalizationMethod);
XMLSignatureUtil.setCanonicalizationMethodType(canonicalizationMethod);
-
- if(trace) log.trace("Identity Provider URL=" + this.identityURL);
+
+ if (trace)
+ log.trace("Identity Provider URL=" + this.identityURL);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
-
- try
+ }
+
+ protected IDPSSODescriptorType handleMetadata(EntitiesDescriptorType entities)
+ {
+ IDPSSODescriptorType idpSSO = null;
+
+ List<Object> entityDescs = entities.getEntityDescriptor();
+ for (Object entityDescriptor : entityDescs)
{
- //Get the handlers
- String handlerConfigFileName = GeneralConstants.HANDLER_CONFIG_FILE_LOCATION;
- handlers = ConfigurationUtil.getHandlers(servletContext.getResourceAsStream(handlerConfigFileName));
- chain.addAll(HandlerUtil.getHandlers(handlers));
-
- this.populateChainConfig();
- this.initializeHandlerChain();
+ if (entityDescriptor instanceof EntitiesDescriptorType)
+ {
+ idpSSO = getIDPSSODescriptor(entities);
+ }
+ else
+ idpSSO = handleMetadata((EntityDescriptorType) entityDescriptor);
+ if (idpSSO != null)
+ break;
}
- catch(Exception e)
+ return idpSSO;
+ }
+
+ protected IDPSSODescriptorType handleMetadata(EntityDescriptorType entityDescriptor)
+ {
+ return CoreConfigUtil.getIDPDescriptor(entityDescriptor);
+ }
+
+ protected IDPSSODescriptorType getIDPSSODescriptor(EntitiesDescriptorType entities)
+ {
+ List<Object> entityDescs = entities.getEntityDescriptor();
+ for (Object entityDescriptor : entityDescs)
{
- throw new RuntimeException(e);
- }
- }
-
- protected void initializeHandlerChain()
- throws ConfigurationException, ProcessingException
+
+ if (entityDescriptor instanceof EntitiesDescriptorType)
+ {
+ return getIDPSSODescriptor((EntitiesDescriptorType) entityDescriptor);
+ }
+ return CoreConfigUtil.getIDPDescriptor((EntityDescriptorType) entityDescriptor);
+ }
+ return null;
+ }
+
+ protected void initializeHandlerChain() throws ConfigurationException, ProcessingException
{
populateChainConfig();
SAML2HandlerChainConfig handlerChainConfig = new DefaultSAML2HandlerChainConfig(chainConfigOptions);
-
+
Set<SAML2Handler> samlHandlers = chain.handlers();
-
- for(SAML2Handler handler: samlHandlers)
+
+ for (SAML2Handler handler : samlHandlers)
{
handler.initChainConfig(handlerChainConfig);
}
}
-
- protected void populateChainConfig()
- throws ConfigurationException, ProcessingException
+
+ protected void populateChainConfig() throws ConfigurationException, ProcessingException
{
chainConfigOptions.put(GeneralConstants.CONFIGURATION, spConfiguration);
- chainConfigOptions.put( GeneralConstants.CANONICALIZATION_METHOD, canonicalizationMethod );
+ chainConfigOptions.put(GeneralConstants.CANONICALIZATION_METHOD, canonicalizationMethod);
chainConfigOptions.put(GeneralConstants.ROLE_VALIDATOR_IGNORE, "false"); //No validator as tomcat realm does validn
}
}
\ No newline at end of file
Modified: federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java
===================================================================
--- federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java 2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -44,11 +44,12 @@
import org.picketlink.identity.federation.core.exceptions.ParsingException;
import org.picketlink.identity.federation.core.exceptions.ProcessingException;
import org.picketlink.identity.federation.core.interfaces.TrustKeyManager;
+import org.picketlink.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
import org.picketlink.identity.federation.core.saml.v2.exceptions.IssuerNotTrustedException;
import org.picketlink.identity.federation.core.saml.v2.holders.DestinationInfoHolder;
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2Handler;
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2HandlerResponse;
-import org.picketlink.identity.federation.core.saml.v2.util.DocumentUtil;
+import org.picketlink.identity.federation.core.saml.v2.util.DocumentUtil;
import org.picketlink.identity.federation.newmodel.saml.v2.protocol.ResponseType;
import org.picketlink.identity.federation.web.constants.GeneralConstants;
import org.picketlink.identity.federation.web.core.HTTPContext;
@@ -67,58 +68,60 @@
* @author Anil.Saldhana(a)redhat.com
* @since Dec 12, 2008
*/
-public class SPPostFormAuthenticator extends BaseFormAuthenticator
-{
+public class SPPostFormAuthenticator extends BaseFormAuthenticator
+{
private static Logger log = Logger.getLogger(SPPostFormAuthenticator.class);
- private boolean trace = log.isTraceEnabled();
+
+ private final boolean trace = log.isTraceEnabled();
+
private boolean jbossEnv = false;
-
- private String logOutPage = GeneralConstants.LOGOUT_PAGE_NAME;
-
+
+ private final String logOutPage = GeneralConstants.LOGOUT_PAGE_NAME;
+
protected boolean supportSignatures = false;
-
- protected TrustKeyManager keyManager;
-
+
+ protected TrustKeyManager keyManager;
+
/**
* A flag to indicate that we are going to validate signature
* for saml responses from IDP
*/
protected boolean validateSignature = false;
-
+
public SPPostFormAuthenticator()
{
- super();
- ServerDetector detector = new ServerDetector();
+ super();
+ ServerDetector detector = new ServerDetector();
jbossEnv = detector.isJboss();
- }
+ }
@Override
public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
{
- SPUtil spUtil = new SPUtil();
-
+ SPUtil spUtil = new SPUtil();
+
//Eagerly look for Global LogOut
String gloStr = request.getParameter(GeneralConstants.GLOBAL_LOGOUT);
boolean logOutRequest = isNotNull(gloStr) && "true".equalsIgnoreCase(gloStr);
-
+
String samlRequest = request.getParameter(GeneralConstants.SAML_REQUEST_KEY);
- String samlResponse = request.getParameter(GeneralConstants.SAML_RESPONSE_KEY);
-
+ String samlResponse = request.getParameter(GeneralConstants.SAML_RESPONSE_KEY);
+
Principal principal = request.getUserPrincipal();
-
+
//If we have already authenticated the user and there is no request from IDP or logout from user
- if(principal != null && !(logOutRequest || isNotNull(samlRequest) || isNotNull(samlResponse) ) )
- return true;
-
+ if (principal != null && !(logOutRequest || isNotNull(samlRequest) || isNotNull(samlResponse)))
+ return true;
+
Session session = request.getSessionInternal(true);
String relayState = request.getParameter(GeneralConstants.RELAY_STATE);
boolean willSendRequest = false;
HTTPContext httpContext = new HTTPContext(request, response, context.getServletContext());
Set<SAML2Handler> handlers = chain.handlers();
-
+
//General User Request
- if(!isNotNull(samlRequest) && !isNotNull(samlResponse))
+ if (!isNotNull(samlRequest) && !isNotNull(samlResponse))
{
//Neither saml request nor response from IDP
//So this is a user request
@@ -126,14 +129,14 @@
try
{
ServiceProviderBaseProcessor baseProcessor = new ServiceProviderBaseProcessor(true, serviceURL);
- if( issuerID != null )
- baseProcessor.setIssuer( issuerID );
-
- baseProcessor.setIdentityURL( identityURL );
-
- saml2HandlerResponse = baseProcessor.process(httpContext, handlers, chainLock);
+ if (issuerID != null)
+ baseProcessor.setIssuer(issuerID);
+
+ baseProcessor.setIdentityURL(identityURL);
+
+ saml2HandlerResponse = baseProcessor.process(httpContext, handlers, chainLock);
}
- catch(ProcessingException pe)
+ catch (ProcessingException pe)
{
log.error("Processing Exception:", pe);
throw new RuntimeException(pe);
@@ -147,39 +150,37 @@
{
log.error("Config Exception:", pe);
throw new RuntimeException(pe);
- }
-
+ }
+
willSendRequest = saml2HandlerResponse.getSendRequest();
-
+
Document samlResponseDocument = saml2HandlerResponse.getResultingDocument();
relayState = saml2HandlerResponse.getRelayState();
String destination = saml2HandlerResponse.getDestination();
- if(destination != null &&
- samlResponseDocument != null)
+ if (destination != null && samlResponseDocument != null)
{
try
- {
- if( saveRestoreRequest )
+ {
+ if (saveRestoreRequest)
{
- this.saveRequest(request, session);
+ this.saveRequest(request, session);
}
- sendRequestToIDP(destination, samlResponseDocument, relayState, response,
- willSendRequest);
+ sendRequestToIDP(destination, samlResponseDocument, relayState, response, willSendRequest);
return false;
}
catch (Exception e)
{
- if(trace)
- log.trace("Exception:",e);
+ if (trace)
+ log.trace("Exception:", e);
throw new IOException("Server Error");
- }
- }
+ }
+ }
}
//Handle a SAML Response from IDP
- if(isNotNull(samlResponse) )
+ if (isNotNull(samlResponse))
{
boolean isValid = false;
try
@@ -188,34 +189,31 @@
}
catch (Exception e)
{
- log.error("Exception:",e);
+ log.error("Exception:", e);
throw new IOException();
}
- if(!isValid)
+ if (!isValid)
throw new IOException("Validity check failed");
-
-
+
//deal with SAML response from IDP
try
{
- ServiceProviderSAMLResponseProcessor responseProcessor =
- new ServiceProviderSAMLResponseProcessor(true, serviceURL);
- responseProcessor.setValidateSignature( validateSignature );
+ ServiceProviderSAMLResponseProcessor responseProcessor = new ServiceProviderSAMLResponseProcessor(true,
+ serviceURL);
+ responseProcessor.setValidateSignature(validateSignature);
responseProcessor.setTrustKeyManager(keyManager);
-
- SAML2HandlerResponse saml2HandlerResponse =
- responseProcessor.process(samlResponse, httpContext, handlers, chainLock);
+ SAML2HandlerResponse saml2HandlerResponse = responseProcessor.process(samlResponse, httpContext, handlers,
+ chainLock);
+
Document samlResponseDocument = saml2HandlerResponse.getResultingDocument();
relayState = saml2HandlerResponse.getRelayState();
String destination = saml2HandlerResponse.getDestination();
willSendRequest = saml2HandlerResponse.getSendRequest();
-
- if(destination != null &&
- samlResponseDocument != null)
+ if (destination != null && samlResponseDocument != null)
{
sendRequestToIDP(destination, samlResponseDocument, relayState, response, willSendRequest);
}
@@ -223,38 +221,38 @@
{
//See if the session has been invalidated
- boolean sessionValidity = session.isValid();
- if(!sessionValidity)
+ boolean sessionValidity = session.isValid();
+ if (!sessionValidity)
{
//we are invalidated.
- RequestDispatcher dispatch = context.getServletContext().getRequestDispatcher(this.logOutPage);
- if(dispatch == null)
+ RequestDispatcher dispatch = context.getServletContext().getRequestDispatcher(this.logOutPage);
+ if (dispatch == null)
log.error("Cannot dispatch to the logout page: no request dispatcher:" + this.logOutPage);
else
dispatch.forward(request, response);
- return false;
- }
+ return false;
+ }
//We got a response with the principal
List<String> roles = saml2HandlerResponse.getRoles();
- if(principal == null)
+ if (principal == null)
principal = (Principal) session.getSession().getAttribute(GeneralConstants.PRINCIPAL_ID);
String username = principal.getName();
String password = ServiceProviderSAMLContext.EMPTY_PASSWORD;
- if( trace )
- log.trace( "Roles determined for username=" + username + "=" + Arrays.toString( roles.toArray() ) );
-
+ if (trace)
+ log.trace("Roles determined for username=" + username + "=" + Arrays.toString(roles.toArray()));
+
//Map to JBoss specific principal
- if((new ServerDetector()).isJboss() || jbossEnv)
+ if ((new ServerDetector()).isJboss() || jbossEnv)
{
//Push a context
ServiceProviderSAMLContext.push(username, roles);
- principal = context.getRealm().authenticate(username, password);
+ principal = context.getRealm().authenticate(username, password);
ServiceProviderSAMLContext.clear();
}
else
- {
+ {
//tomcat env
principal = spUtil.createGenericPrincipal(request, username, roles);
}
@@ -263,49 +261,55 @@
session.setNote(Constants.SESS_PASSWORD_NOTE, password);
request.setUserPrincipal(principal);
//Get the original saved request
- if( saveRestoreRequest )
+ if (saveRestoreRequest)
{
- this.restoreRequest(request, session);
+ this.restoreRequest(request, session);
}
- register(request, response, principal, Constants.FORM_METHOD, username, password);
+ register(request, response, principal, Constants.FORM_METHOD, username, password);
- return true;
- }
+ return true;
+ }
}
catch (Exception e)
{
- if(trace)
+ if (trace)
log.trace("Server Exception:", e);
throw new IOException("Server Exception");
- }
- }
-
+ }
+ }
+
//Handle SAML Requests from IDP
- if(isNotNull(samlRequest))
- {
+ if (isNotNull(samlRequest))
+ {
try
{
- ServiceProviderSAMLRequestProcessor requestProcessor =
- new ServiceProviderSAMLRequestProcessor(true, this.serviceURL);
+ ServiceProviderSAMLRequestProcessor requestProcessor = new ServiceProviderSAMLRequestProcessor(true,
+ this.serviceURL);
requestProcessor.setTrustKeyManager(keyManager);
requestProcessor.setSupportSignatures(supportSignatures);
boolean result = requestProcessor.process(samlRequest, httpContext, handlers, chainLock);
-
- if(result)
+
+ if (result)
return result;
}
catch (Exception e)
{
- if(trace)
+ if (trace)
log.trace("Server Exception:", e);
throw new IOException("Server Exception");
- }
+ }
}//end if
//fallback
- return super.authenticate(request, response, loginConfig);
- }
-
+ return super.authenticate(request, response, loginConfig);
+ }
+
+ @Override
+ protected String getBinding()
+ {
+ return JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.get();
+ }
+
/**
* Send the request to the IDP
* @param destination idp url
@@ -316,18 +320,16 @@
* @throws ProcessingException
* @throws ConfigurationException
* @throws IOException
- */
- protected void sendRequestToIDP(
- String destination, Document samlDocument,String relayState, Response response,
- boolean willSendRequest)
- throws ProcessingException, ConfigurationException, IOException
+ */
+ protected void sendRequestToIDP(String destination, Document samlDocument, String relayState, Response response,
+ boolean willSendRequest) throws ProcessingException, ConfigurationException, IOException
{
- String samlMessage = DocumentUtil.getDocumentAsString(samlDocument);
+ String samlMessage = DocumentUtil.getDocumentAsString(samlDocument);
samlMessage = PostBindingUtil.base64Encode(samlMessage);
- PostBindingUtil.sendPost(new DestinationInfoHolder(destination, samlMessage, relayState),
- response, willSendRequest);
+ PostBindingUtil.sendPost(new DestinationInfoHolder(destination, samlMessage, relayState), response,
+ willSendRequest);
}
-
+
/**
* Trust handling
* @param issuer
@@ -338,20 +340,20 @@
try
{
String issuerDomain = ValveUtil.getDomain(issuer);
- TrustType idpTrust = spConfiguration.getTrust();
- if(idpTrust != null)
+ TrustType idpTrust = spConfiguration.getTrust();
+ if (idpTrust != null)
{
String domainsTrusted = idpTrust.getDomains();
- if(domainsTrusted.indexOf(issuerDomain) < 0)
- throw new IssuerNotTrustedException(issuer);
+ if (domainsTrusted.indexOf(issuerDomain) < 0)
+ throw new IssuerNotTrustedException(issuer);
}
}
catch (Exception e)
{
- throw new IssuerNotTrustedException(e.getLocalizedMessage(),e);
+ throw new IssuerNotTrustedException(e.getLocalizedMessage(), e);
}
}
-
+
/**
* Subclasses should provide the implementation
* @param responseType ResponseType that contains the encrypted assertion
@@ -360,5 +362,5 @@
protected ResponseType decryptAssertion(ResponseType responseType)
{
throw new RuntimeException("This authenticator does not handle encryption");
- }
+ }
}
\ No newline at end of file
Modified: federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java
===================================================================
--- federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java 2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -47,6 +47,7 @@
import org.picketlink.identity.federation.core.exceptions.ConfigurationException;
import org.picketlink.identity.federation.core.exceptions.ParsingException;
import org.picketlink.identity.federation.core.exceptions.ProcessingException;
+import org.picketlink.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
import org.picketlink.identity.federation.core.saml.v2.exceptions.AssertionExpiredException;
import org.picketlink.identity.federation.core.saml.v2.exceptions.IssuerNotTrustedException;
import org.picketlink.identity.federation.core.saml.v2.interfaces.SAML2Handler;
@@ -73,21 +74,22 @@
* @author Anil.Saldhana(a)redhat.com
* @since Dec 12, 2008
*/
-public class SPRedirectFormAuthenticator extends BaseFormAuthenticator
-{
+public class SPRedirectFormAuthenticator extends BaseFormAuthenticator
+{
private static Logger log = Logger.getLogger(SPRedirectFormAuthenticator.class);
- private boolean trace = log.isTraceEnabled();
-
+
+ private final boolean trace = log.isTraceEnabled();
+
private boolean jbossEnv = false;
-
- private String logOutPage = GeneralConstants.LOGOUT_PAGE_NAME;
-
+
+ private final String logOutPage = GeneralConstants.LOGOUT_PAGE_NAME;
+
public SPRedirectFormAuthenticator()
{
super();
- ServerDetector detector = new ServerDetector();
+ ServerDetector detector = new ServerDetector();
jbossEnv = detector.isJboss();
- }
+ }
@Override
public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
@@ -95,38 +97,38 @@
//Eagerly look for Global LogOut
String gloStr = request.getParameter(GeneralConstants.GLOBAL_LOGOUT);
boolean logOutRequest = isNotNull(gloStr) && "true".equalsIgnoreCase(gloStr);
-
+
String samlRequest = request.getParameter(GeneralConstants.SAML_REQUEST_KEY);
- String samlResponse = request.getParameter(GeneralConstants.SAML_RESPONSE_KEY);
-
- Principal principal = request.getUserPrincipal();
+ String samlResponse = request.getParameter(GeneralConstants.SAML_RESPONSE_KEY);
+ Principal principal = request.getUserPrincipal();
+
//If we have already authenticated the user and there is no request from IDP or logout from user
- if(principal != null && !(logOutRequest || isNotNull(samlRequest) || isNotNull(samlResponse) ) )
+ if (principal != null && !(logOutRequest || isNotNull(samlRequest) || isNotNull(samlResponse)))
return true;
Session session = request.getSessionInternal(true);
String relayState = request.getParameter(GeneralConstants.RELAY_STATE);
HTTPContext httpContext = new HTTPContext(request, response, context.getServletContext());
-
+
Set<SAML2Handler> handlers = chain.handlers();
-
+
//General User Request
- if(!isNotNull(samlRequest) && !isNotNull(samlResponse))
+ if (!isNotNull(samlRequest) && !isNotNull(samlResponse))
{
//Neither saml request nor response from IDP
//So this is a user request
SAML2HandlerResponse saml2HandlerResponse = null;
try
{
- ServiceProviderBaseProcessor baseProcessor = new ServiceProviderBaseProcessor(false, serviceURL);
-
+ ServiceProviderBaseProcessor baseProcessor = new ServiceProviderBaseProcessor(false, serviceURL);
+
initializeSAMLProcessor(baseProcessor);
-
+
saml2HandlerResponse = baseProcessor.process(httpContext, handlers, chainLock);
- saml2HandlerResponse.setDestination(identityURL);
+ saml2HandlerResponse.setDestination(identityURL);
}
- catch(ProcessingException pe)
+ catch (ProcessingException pe)
{
log.error("Processing Exception:", pe);
throw new RuntimeException(pe);
@@ -140,57 +142,56 @@
{
log.error("Config Exception:", pe);
throw new RuntimeException(pe);
- }
-
+ }
+
Document samlResponseDocument = saml2HandlerResponse.getResultingDocument();
relayState = saml2HandlerResponse.getRelayState();
String destination = saml2HandlerResponse.getDestination();
- if(destination != null &&
- samlResponseDocument != null)
+ if (destination != null && samlResponseDocument != null)
{
try
{
String samlMsg = DocumentUtil.getDocumentAsString(samlResponseDocument);
- if(trace)
+ if (trace)
log.trace("SAML Document=" + samlMsg);
boolean areWeSendingRequest = saml2HandlerResponse.getSendRequest();
-
+
String base64Request = RedirectBindingUtil.deflateBase64URLEncode(samlMsg.getBytes("UTF-8"));
-
+
String destinationQuery = getDestinationQueryString(base64Request, relayState, areWeSendingRequest);
-
+
RedirectBindingUtilDestHolder holder = new RedirectBindingUtilDestHolder();
holder.setDestination(destination).setDestinationQueryString(destinationQuery);
-
+
String destinationURL = RedirectBindingUtil.getDestinationURL(holder);
-
- if(trace)
+
+ if (trace)
{
log.trace("URL used for sending:" + destinationURL);
}
- if( saveRestoreRequest )
+ if (saveRestoreRequest)
{
- this.saveRequest(request, session);
+ this.saveRequest(request, session);
}
-
- HTTPRedirectUtil.sendRedirectForRequestor(destinationURL, response);
+
+ HTTPRedirectUtil.sendRedirectForRequestor(destinationURL, response);
return false;
}
catch (Exception e)
{
- if(trace)
- log.trace("Exception:",e);
+ if (trace)
+ log.trace("Exception:", e);
throw new IOException("Server Error");
- }
- }
+ }
+ }
}
//See if we got a response from IDP
- if(isNotNull(samlResponse) )
+ if (isNotNull(samlResponse))
{
boolean isValid = false;
try
@@ -199,35 +200,35 @@
}
catch (Exception e)
{
- log.error("Exception:",e);
+ log.error("Exception:", e);
throw new IOException();
}
- if(!isValid)
+ if (!isValid)
throw new IOException("Validity check failed");
-
+
try
{
- ServiceProviderSAMLResponseProcessor responseProcessor =
- new ServiceProviderSAMLResponseProcessor(false, serviceURL);
+ ServiceProviderSAMLResponseProcessor responseProcessor = new ServiceProviderSAMLResponseProcessor(false,
+ serviceURL);
initializeSAMLProcessor(responseProcessor);
-
+
SAML2HandlerResponse saml2HandlerResponse = null;
-
+
try
{
- saml2HandlerResponse = responseProcessor.process(samlResponse, httpContext, handlers, chainLock);
+ saml2HandlerResponse = responseProcessor.process(samlResponse, httpContext, handlers, chainLock);
}
- catch(ProcessingException pe)
+ catch (ProcessingException pe)
{
Throwable te = pe.getCause();
- if(te instanceof AssertionExpiredException)
+ if (te instanceof AssertionExpiredException)
{
//We need to reissue redirect to IDP
ServiceProviderBaseProcessor baseProcessor = new ServiceProviderBaseProcessor(false, serviceURL);
initializeSAMLProcessor(baseProcessor);
-
+
saml2HandlerResponse = baseProcessor.process(httpContext, handlers, chainLock);
- saml2HandlerResponse.setDestination(identityURL);
+ saml2HandlerResponse.setDestination(identityURL);
}
else
throw pe;
@@ -236,20 +237,19 @@
relayState = saml2HandlerResponse.getRelayState();
String destination = saml2HandlerResponse.getDestination();
-
- if(destination != null &&
- samlResponseDocument != null)
+
+ if (destination != null && samlResponseDocument != null)
{
- boolean areWeSendingRequest = saml2HandlerResponse.getSendRequest();
+ boolean areWeSendingRequest = saml2HandlerResponse.getSendRequest();
String samlMsg = DocumentUtil.getDocumentAsString(samlResponseDocument);
- String base64Request = RedirectBindingUtil.deflateBase64URLEncode(samlMsg.getBytes("UTF-8"));
-
+ String base64Request = RedirectBindingUtil.deflateBase64URLEncode(samlMsg.getBytes("UTF-8"));
+
String destinationQuery = getDestinationQueryString(base64Request, relayState, areWeSendingRequest);
-
+
RedirectBindingUtilDestHolder holder = new RedirectBindingUtilDestHolder();
- holder.setDestination(destination).setDestinationQueryString(destinationQuery);
-
+ holder.setDestination(destination).setDestinationQueryString(destinationQuery);
+
String destinationURL = RedirectBindingUtil.getDestinationURL(holder);
HTTPRedirectUtil.sendRedirectForRequestor(destinationURL, response);
@@ -257,32 +257,32 @@
else
{
//See if the session has been invalidated
- boolean sessionValidity = session.isValid();
- if(!sessionValidity)
+ boolean sessionValidity = session.isValid();
+ if (!sessionValidity)
{
//we are invalidated.
- RequestDispatcher dispatch = context.getServletContext().getRequestDispatcher(this.logOutPage);
- if(dispatch == null)
+ RequestDispatcher dispatch = context.getServletContext().getRequestDispatcher(this.logOutPage);
+ if (dispatch == null)
log.error("Cannot dispatch to the logout page: no request dispatcher:" + this.logOutPage);
else
dispatch.forward(request, response);
- return false;
- }
+ return false;
+ }
//We got a response with the principal
List<String> roles = saml2HandlerResponse.getRoles();
- if(principal == null)
+ if (principal == null)
principal = (Principal) session.getSession().getAttribute(GeneralConstants.PRINCIPAL_ID);
String username = principal.getName();
String password = ServiceProviderSAMLContext.EMPTY_PASSWORD;
//Map to JBoss specific principal
- if((new ServerDetector()).isJboss() || jbossEnv)
- {
+ if ((new ServerDetector()).isJboss() || jbossEnv)
+ {
//Push a context
ServiceProviderSAMLContext.push(username, roles);
- principal = context.getRealm().authenticate(username, password);
+ principal = context.getRealm().authenticate(username, password);
ServiceProviderSAMLContext.clear();
}
else
@@ -295,138 +295,144 @@
session.setNote(Constants.SESS_USERNAME_NOTE, username);
session.setNote(Constants.SESS_PASSWORD_NOTE, password);
request.setUserPrincipal(principal);
-
- if( saveRestoreRequest )
+
+ if (saveRestoreRequest)
{
- this.restoreRequest(request, session);
+ this.restoreRequest(request, session);
}
- register(request, response, principal, Constants.FORM_METHOD, username, password);
+ register(request, response, principal, Constants.FORM_METHOD, username, password);
- return true;
+ return true;
}
}
catch (Exception e)
{
e.printStackTrace();
- if(trace)
+ if (trace)
log.trace("Server Exception:", e);
- throw new IOException("Server Exception:"+ e.getLocalizedMessage());
- }
- }
+ throw new IOException("Server Exception:" + e.getLocalizedMessage());
+ }
+ }
//Handle SAML Requests from IDP
- if(isNotNull(samlRequest))
+ if (isNotNull(samlRequest))
{
//we got a logout request
try
{
- ServiceProviderSAMLRequestProcessor requestProcessor =
- new ServiceProviderSAMLRequestProcessor(false, this.serviceURL);
+ ServiceProviderSAMLRequestProcessor requestProcessor = new ServiceProviderSAMLRequestProcessor(false,
+ this.serviceURL);
boolean result = requestProcessor.process(samlRequest, httpContext, handlers, chainLock);
- if(result)
+ if (result)
return result;
}
catch (Exception e)
{
- if(trace)
+ if (trace)
log.trace("Server Exception:", e);
throw new IOException("Server Exception");
- }
+ }
}//end if
//fallback
return super.authenticate(request, response, loginConfig);
- }
+ }
- protected String createSAMLRequestMessage(String relayState, Response response)
- throws ServletException, ConfigurationException, IOException, ProcessingException
+ protected String createSAMLRequestMessage(String relayState, Response response) throws ServletException,
+ ConfigurationException, IOException, ProcessingException
{
//create a saml request
- if(this.serviceURL == null)
+ if (this.serviceURL == null)
throw new ServletException("serviceURL is not configured");
SAML2Request saml2Request = new SAML2Request();
-
+
SPUtil spUtil = new SPUtil();
AuthnRequestType authnRequest = spUtil.createSAMLRequest(serviceURL, identityURL);
-
+
ByteArrayOutputStream baos = new ByteArrayOutputStream();
saml2Request.marshall(authnRequest, baos);
-
+
String base64Request = RedirectBindingUtil.deflateBase64URLEncode(baos.toByteArray());
String destination = authnRequest.getDestination().toASCIIString();
-
+
String destinationQueryString = getDestinationQueryString(base64Request, relayState, true);
-
+
RedirectBindingUtilDestHolder holder = new RedirectBindingUtilDestHolder();
holder.setDestinationQueryString(destinationQueryString).setDestination(destination);
- return RedirectBindingUtil.getDestinationURL(holder);
+ return RedirectBindingUtil.getDestinationURL(holder);
}
-
- protected String getDestinationQueryString(String urlEncodedRequest, String urlEncodedRelayState,
- boolean sendRequest)
+
+ @Override
+ protected String getBinding()
{
- return RedirectBindingUtil.getDestinationQueryString(urlEncodedRequest,
- urlEncodedRelayState, sendRequest);
+ return JBossSAMLURIConstants.SAML_HTTP_REDIRECT_BINDING.get();
}
-
+
+ protected String getDestinationQueryString(String urlEncodedRequest, String urlEncodedRelayState, boolean sendRequest)
+ {
+ return RedirectBindingUtil.getDestinationQueryString(urlEncodedRequest, urlEncodedRelayState, sendRequest);
+ }
+
protected void isTrusted(String issuer) throws IssuerNotTrustedException
{
try
{
String issuerDomain = ValveUtil.getDomain(issuer);
- TrustType spTrust = spConfiguration.getTrust();
- if(spTrust != null)
+ TrustType spTrust = spConfiguration.getTrust();
+ if (spTrust != null)
{
String domainsTrusted = spTrust.getDomains();
- if(trace)
- log.trace("Domains that SP trusts="+domainsTrusted + " and issuer domain="+issuerDomain);
- if(domainsTrusted.indexOf(issuerDomain) < 0)
+ if (trace)
+ log.trace("Domains that SP trusts=" + domainsTrusted + " and issuer domain=" + issuerDomain);
+ if (domainsTrusted.indexOf(issuerDomain) < 0)
{
//Let us do string parts checking
StringTokenizer st = new StringTokenizer(domainsTrusted, ",");
- while(st != null && st.hasMoreTokens())
+ while (st != null && st.hasMoreTokens())
{
String uriBit = st.nextToken();
- if(trace) log.trace("Matching uri bit="+ uriBit);
- if(issuerDomain.indexOf(uriBit) > 0)
+ if (trace)
+ log.trace("Matching uri bit=" + uriBit);
+ if (issuerDomain.indexOf(uriBit) > 0)
{
- if(trace) log.trace("Matched " + uriBit + " trust for " + issuerDomain );
+ if (trace)
+ log.trace("Matched " + uriBit + " trust for " + issuerDomain);
return;
- }
- }
+ }
+ }
throw new IssuerNotTrustedException(issuer);
- }
- }
+ }
+ }
}
catch (Exception e)
{
- throw new IssuerNotTrustedException(e.getLocalizedMessage(),e);
+ throw new IssuerNotTrustedException(e.getLocalizedMessage(), e);
}
}
-
+
/**
* Initialize the {@code ServiceProviderBaseProcessor}
* @param processor
*/
protected void initializeSAMLProcessor(ServiceProviderBaseProcessor processor)
- {
- if( issuerID != null )
- processor.setIssuer( issuerID );
-
+ {
+ if (issuerID != null)
+ processor.setIssuer(issuerID);
+
processor.setConfiguration(spConfiguration);
}
-
+
/**
* Subclasses should provide the implementation
* @param responseType ResponseType that contains the encrypted assertion
* @return response type with the decrypted assertion
*/
- protected ResponseType decryptAssertion(ResponseType responseType)
- throws IOException, GeneralSecurityException, ConfigurationException, ParsingException
+ protected ResponseType decryptAssertion(ResponseType responseType) throws IOException, GeneralSecurityException,
+ ConfigurationException, ParsingException
{
throw new RuntimeException("This authenticator does not handle encryption");
- }
+ }
}
\ No newline at end of file
Added: federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/authenticators/SPPostFormAuthenticatorUnitTestCase.java
===================================================================
--- federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/authenticators/SPPostFormAuthenticatorUnitTestCase.java (rev 0)
+++ federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/authenticators/SPPostFormAuthenticatorUnitTestCase.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -0,0 +1,70 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.picketlink.test.identity.federation.bindings.authenticators;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.net.URL;
+import java.security.cert.X509Certificate;
+
+import org.junit.Test;
+import org.picketlink.identity.federation.bindings.tomcat.sp.SPPostFormAuthenticator;
+import org.picketlink.test.identity.federation.bindings.mock.MockCatalinaContext;
+import org.picketlink.test.identity.federation.bindings.mock.MockCatalinaContextClassLoader;
+
+/**
+ * Unit test the {@link SPPostFormAuthenticator}
+ * @author Anil.Saldhana(a)redhat.com
+ * @since Mar 1, 2011
+ */
+public class SPPostFormAuthenticatorUnitTestCase
+{
+ @Test
+ public void testIDPMetadataFile() throws Exception
+ {
+ MockCatalinaContext ctx = new MockCatalinaContext();
+ SPPostFormAuthenticator auth = new SPPostFormAuthenticator();
+ auth.setContainer(ctx);
+
+ ClassLoader tccl = Thread.currentThread().getContextClassLoader();
+ URL configURL = tccl.getResource("config/test-idp-metadata-file-config.xml");
+ URL[] urls = new URL[]
+ {configURL};
+ MockCatalinaContextClassLoader tcl = new MockCatalinaContextClassLoader(urls);
+ tcl.associate("/WEB-INF/picketlink-idfed.xml", configURL.openStream());
+ tcl.associate("/WEB-INF/picketlink-handlers.xml",
+ tccl.getResourceAsStream("saml2/post/sp/employee/WEB-INF/picketlink-handlers.xml"));
+ tcl.associate("/WEB-INF/testshib.org.idp-metadata.xml",
+ tccl.getResourceAsStream("metadata/testshib.org.idp-metadata.xml"));
+ tcl.setProfile("DUMMY");
+ tcl.setDelegate(tccl);
+
+ Thread.currentThread().setContextClassLoader(tcl);
+ auth.testStart();
+ assertEquals("https://idp.testshib.org/idp/profile/SAML2/POST/SSO", auth.getIdentityURL());
+ X509Certificate idpCert = auth.getIdpCertificate();
+ assertNotNull(idpCert);
+ assertEquals("CN=idp.testshib.org, O=TestShib, L=Pittsburgh, ST=Pennsylvania, C=US", idpCert.getIssuerDN()
+ .getName());
+ }
+}
\ No newline at end of file
Modified: federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/mock/MockCatalinaContextClassLoader.java
===================================================================
--- federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/mock/MockCatalinaContextClassLoader.java 2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-bindings/src/test/java/org/picketlink/test/identity/federation/bindings/mock/MockCatalinaContextClassLoader.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -24,6 +24,8 @@
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
+import java.util.HashMap;
+import java.util.Map;
/**
* Mock TCL
@@ -31,33 +33,43 @@
* @since Oct 7, 2009
*/
public class MockCatalinaContextClassLoader extends URLClassLoader
-{
+{
private String profile;
-
+
private ClassLoader delegate;
+ private final Map<String, InputStream> streams = new HashMap<String, InputStream>();
+
public MockCatalinaContextClassLoader(URL[] urls)
{
- super(urls);
+ super(urls);
}
public void setDelegate(ClassLoader tcl)
{
this.delegate = tcl;
}
-
+
public void setProfile(String profile)
{
this.profile = profile;
}
+ public void associate(String name, InputStream is)
+ {
+ this.streams.put(name, is);
+ }
+
@Override
public InputStream getResourceAsStream(String name)
{
- if(profile == null)
- throw new RuntimeException("null profile");
+ if (streams.containsKey(name))
+ return streams.get(name);
+
+ if (profile == null)
+ throw new RuntimeException("null profile when seeking resource:" + name);
InputStream is = delegate.getResourceAsStream(profile + "/" + name);
- if( is == null )
+ if (is == null)
is = super.getResourceAsStream(name);
return is;
}
Added: federation/trunk/picketlink-bindings/src/test/resources/config/test-idp-metadata-file-config.xml
===================================================================
--- federation/trunk/picketlink-bindings/src/test/resources/config/test-idp-metadata-file-config.xml (rev 0)
+++ federation/trunk/picketlink-bindings/src/test/resources/config/test-idp-metadata-file-config.xml 2011-03-01 19:10:15 UTC (rev 786)
@@ -0,0 +1,6 @@
+<PicketLinkSP xmlns="urn:picketlink:identity-federation:config:2.0"
+ AttributeManager="org.picketlink.identity.federation.core.impl.EmptyAttributeManager">
+<IDPMetadataFile>/WEB-INF/testshib.org.idp-metadata.xml</IDPMetadataFile>
+<ServiceURL>http://localhost:8080/sales/</ServiceURL>
+
+</PicketLinkSP>
\ No newline at end of file
Added: federation/trunk/picketlink-bindings/src/test/resources/metadata/testshib.org.idp-metadata.xml
===================================================================
--- federation/trunk/picketlink-bindings/src/test/resources/metadata/testshib.org.idp-metadata.xml (rev 0)
+++ federation/trunk/picketlink-bindings/src/test/resources/metadata/testshib.org.idp-metadata.xml 2011-03-01 19:10:15 UTC (rev 786)
@@ -0,0 +1,233 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<EntitiesDescriptor Name="urn:mace:shibboleth:testshib:two"
+ xmlns:shibmd="urn:mace:shibboleth:metadata:1.0" xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+ xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <EntityDescriptor entityID="https://idp.testshib.org/idp/shibboleth">
+ <IDPSSODescriptor
+ protocolSupportEnumeration="urn:oasis:names:tc:SAML:1.1:protocol urn:mace:shibboleth:1.0 urn:oasis:names:tc:SAML:2.0:protocol">
+ <Extensions>
+ <shibmd:Scope regexp="false">testshib.org</shibmd:Scope>
+ </Extensions>
+ <KeyDescriptor>
+ <ds:KeyInfo>
+ <ds:X509Data>
+ <ds:X509Certificate>MIIEDjCCAvagAwIBAgIBADANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJVUzEV
+MBMGA1UECBMMUGVubnN5bHZhbmlhMRMwEQYDVQQHEwpQaXR0c2J1cmdoMREwDwYD
+VQQKEwhUZXN0U2hpYjEZMBcGA1UEAxMQaWRwLnRlc3RzaGliLm9yZzAeFw0wNjA4
+MzAyMTEyMjVaFw0xNjA4MjcyMTEyMjVaMGcxCzAJBgNVBAYTAlVTMRUwEwYDVQQI
+EwxQZW5uc3lsdmFuaWExEzARBgNVBAcTClBpdHRzYnVyZ2gxETAPBgNVBAoTCFRl
+c3RTaGliMRkwFwYDVQQDExBpZHAudGVzdHNoaWIub3JnMIIBIjANBgkqhkiG9w0B
+AQEFAAOCAQ8AMIIBCgKCAQEArYkCGuTmJp9eAOSGHwRJo1SNatB5ZOKqDM9ysg7C
+yVTDClcpu93gSP10nH4gkCZOlnESNgttg0r+MqL8tfJC6ybddEFB3YBo8PZajKSe
+3OQ01Ow3yT4I+Wdg1tsTpSge9gEz7SrC07EkYmHuPtd71CHiUaCWDv+xVfUQX0aT
+NPFmDixzUjoYzbGDrtAyCqA8f9CN2txIfJnpHE6q6CmKcoLADS4UrNPlhHSzd614
+kR/JYiks0K4kbRqCQF0Dv0P5Di+rEfefC6glV8ysC8dB5/9nb0yh/ojRuJGmgMWH
+gWk6h0ihjihqiu4jACovUZ7vVOCgSE5Ipn7OIwqd93zp2wIDAQABo4HEMIHBMB0G
+A1UdDgQWBBSsBQ869nh83KqZr5jArr4/7b+QazCBkQYDVR0jBIGJMIGGgBSsBQ86
+9nh83KqZr5jArr4/7b+Qa6FrpGkwZzELMAkGA1UEBhMCVVMxFTATBgNVBAgTDFBl
+bm5zeWx2YW5pYTETMBEGA1UEBxMKUGl0dHNidXJnaDERMA8GA1UEChMIVGVzdFNo
+aWIxGTAXBgNVBAMTEGlkcC50ZXN0c2hpYi5vcmeCAQAwDAYDVR0TBAUwAwEB/zAN
+BgkqhkiG9w0BAQUFAAOCAQEAjR29PhrCbk8qLN5MFfSVk98t3CT9jHZoYxd8QMRL
+I4j7iYQxXiGJTT1FXs1nd4Rha9un+LqTfeMMYqISdDDI6tv8iNpkOAvZZUosVkUo
+93pv1T0RPz35hcHHYq2yee59HJOco2bFlcsH8JBXRSRrJ3Q7Eut+z9uo80JdGNJ4
+/SJy5UorZ8KazGj16lfJhOBXldgrhppQBb0Nq6HKHguqmwRfJ+WkxemZXzhediAj
+Geka8nz8JjwxpUjAiSWYKLtJhGEaTqCYxCCX2Dw+dOTqUzHOZ7WKv4JXPK5G/Uhr
+8K/qhmFT2nIQi538n6rVYLeWj8Bbnl+ev0peYzxFyF5sQA==</ds:X509Certificate>
+ </ds:X509Data>
+ </ds:KeyInfo>
+ </KeyDescriptor>
+ <ArtifactResolutionService
+ Binding="urn:oasis:names:tc:SAML:1.0:bindings:SOAP-binding"
+ Location="https://idp.testshib.org:8443/idp/profile/SAML1/SOAP/ArtifactResolution"
+ index="1" />
+ <ArtifactResolutionService
+ Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP"
+ Location="https://idp.testshib.org:8443/idp/profile/SAML2/SOAP/ArtifactResolution"
+ index="2" />
+ <NameIDFormat>urn:mace:shibboleth:1.0:nameIdentifier</NameIDFormat>
+ <NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient
+ </NameIDFormat>
+ <SingleSignOnService Binding="urn:mace:shibboleth:1.0:profiles:AuthnRequest"
+ Location="https://idp.testshib.org/idp/profile/Shibboleth/SSO" />
+ <SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
+ Location="https://idp.testshib.org/idp/profile/SAML2/POST/SSO" />
+ <SingleSignOnService
+ Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
+ Location="https://idp.testshib.org/idp/profile/SAML2/Redirect/SSO" />
+ </IDPSSODescriptor>
+ <AttributeAuthorityDescriptor
+ protocolSupportEnumeration="urn:oasis:names:tc:SAML:1.1:protocol urn:oasis:names:tc:SAML:2.0:protocol">
+ <KeyDescriptor>
+ <ds:KeyInfo>
+ <ds:X509Data>
+ <ds:X509Certificate>MIIEKjCCAxKgAwIBAgIJAIgUuHL4QvkYMA0GCSqGSIb3DQEBBQUAMGsxCzAJBgNV
+ BAYTAkdCMRIwEAYDVQQIEwlCZXJrc2hpcmUxEDAOBgNVBAcTB05ld2J1cnkxFzAV
+ BgNVBAoTDk15IENvbXBhbnkgTHRkMR0wGwYDVQQDExRpZHAudHdvLnRlc3RzaGli
+ Lm9yZzAeFw0wNzEyMTcxOTE4NDFaFw0xNzEyMTQxOTE4NDFaMGsxCzAJBgNVBAYT
+ AkdCMRIwEAYDVQQIEwlCZXJrc2hpcmUxEDAOBgNVBAcTB05ld2J1cnkxFzAVBgNV
+ BAoTDk15IENvbXBhbnkgTHRkMR0wGwYDVQQDExRpZHAudHdvLnRlc3RzaGliLm9y
+ ZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK2JAhrk5iafXgDkhh8E
+ SaNUjWrQeWTiqgzPcrIOwslUwwpXKbvd4Ej9dJx+IJAmTpZxEjYLbYNK/jKi/LXy
+ Qusm3XRBQd2AaPD2WoykntzkNNTsN8k+CPlnYNbbE6UoHvYBM+0qwtOxJGJh7j7X
+ e9Qh4lGglg7/sVX1EF9GkzTxZg4sc1I6GM2xg67QMgqgPH/QjdrcSHyZ6RxOqugp
+ inKCwA0uFKzT5YR0s3eteJEfyWIpLNCuJG0agkBdA79D+Q4vqxH3nwuoJVfMrAvH
+ Qef/Z29Mof6I0biRpoDFh4FpOodIoY4oaoruIwAqL1Ge71TgoEhOSKZ+ziMKnfd8
+ 6dsCAwEAAaOB0DCBzTAdBgNVHQ4EFgQUrAUPOvZ4fNyqma+YwK6+P+2/kGswgZ0G
+ A1UdIwSBlTCBkoAUrAUPOvZ4fNyqma+YwK6+P+2/kGuhb6RtMGsxCzAJBgNVBAYT
+ AkdCMRIwEAYDVQQIEwlCZXJrc2hpcmUxEDAOBgNVBAcTB05ld2J1cnkxFzAVBgNV
+ BAoTDk15IENvbXBhbnkgTHRkMR0wGwYDVQQDExRpZHAudHdvLnRlc3RzaGliLm9y
+ Z4IJAIgUuHL4QvkYMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAEti
+ KJki8WO2wGhpJc3oIAF7V0CYBR3303S37iqSodabyN/2nxFXTqd+ZSAdfe+14E/G
+ dyC9Dtbq4VL2lF0fbaNarCzfhMD7DExSANFkOPFk/lz54ccFdfIRHRVeLHvEtGAI
+ UTK+qEqaEl1vjZVKmvNSdDet06EQ+MGZf1MnW6jid4AMrSdboDHFW34qet+tr9gf
+ 5k6bZx6oIiOILgXWHk7hK1ZuxK5w0bpbktNIfO35HoQSPBx6u6wuxt4yN/m6QLiq
+ nGEzsHlzsPFv1Iw+ccdALcqR0zor7GEJrKmp4Gcb/zH3oy1rQNZHUlz29emJhS/1
+ q1og9SGCUU2yRL1tC+Y=</ds:X509Certificate>
+ </ds:X509Data>
+ </ds:KeyInfo>
+ </KeyDescriptor>
+ <KeyDescriptor>
+ <ds:KeyInfo>
+ <ds:X509Data>
+ <ds:X509Certificate>MIIEDjCCAvagAwIBAgIBADANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJVUzEV
+ MBMGA1UECBMMUGVubnN5bHZhbmlhMRMwEQYDVQQHEwpQaXR0c2J1cmdoMREwDwYD
+ VQQKEwhUZXN0U2hpYjEZMBcGA1UEAxMQaWRwLnRlc3RzaGliLm9yZzAeFw0wNjA4
+ MzAyMTEyMjVaFw0xNjA4MjcyMTEyMjVaMGcxCzAJBgNVBAYTAlVTMRUwEwYDVQQI
+ EwxQZW5uc3lsdmFuaWExEzARBgNVBAcTClBpdHRzYnVyZ2gxETAPBgNVBAoTCFRl
+ c3RTaGliMRkwFwYDVQQDExBpZHAudGVzdHNoaWIub3JnMIIBIjANBgkqhkiG9w0B
+ AQEFAAOCAQ8AMIIBCgKCAQEArYkCGuTmJp9eAOSGHwRJo1SNatB5ZOKqDM9ysg7C
+ yVTDClcpu93gSP10nH4gkCZOlnESNgttg0r+MqL8tfJC6ybddEFB3YBo8PZajKSe
+ 3OQ01Ow3yT4I+Wdg1tsTpSge9gEz7SrC07EkYmHuPtd71CHiUaCWDv+xVfUQX0aT
+ NPFmDixzUjoYzbGDrtAyCqA8f9CN2txIfJnpHE6q6CmKcoLADS4UrNPlhHSzd614
+ kR/JYiks0K4kbRqCQF0Dv0P5Di+rEfefC6glV8ysC8dB5/9nb0yh/ojRuJGmgMWH
+ gWk6h0ihjihqiu4jACovUZ7vVOCgSE5Ipn7OIwqd93zp2wIDAQABo4HEMIHBMB0G
+ A1UdDgQWBBSsBQ869nh83KqZr5jArr4/7b+QazCBkQYDVR0jBIGJMIGGgBSsBQ86
+ 9nh83KqZr5jArr4/7b+Qa6FrpGkwZzELMAkGA1UEBhMCVVMxFTATBgNVBAgTDFBl
+ bm5zeWx2YW5pYTETMBEGA1UEBxMKUGl0dHNidXJnaDERMA8GA1UEChMIVGVzdFNo
+ aWIxGTAXBgNVBAMTEGlkcC50ZXN0c2hpYi5vcmeCAQAwDAYDVR0TBAUwAwEB/zAN
+ BgkqhkiG9w0BAQUFAAOCAQEAjR29PhrCbk8qLN5MFfSVk98t3CT9jHZoYxd8QMRL
+ I4j7iYQxXiGJTT1FXs1nd4Rha9un+LqTfeMMYqISdDDI6tv8iNpkOAvZZUosVkUo
+ 93pv1T0RPz35hcHHYq2yee59HJOco2bFlcsH8JBXRSRrJ3Q7Eut+z9uo80JdGNJ4
+ /SJy5UorZ8KazGj16lfJhOBXldgrhppQBb0Nq6HKHguqmwRfJ+WkxemZXzhediAj
+ Geka8nz8JjwxpUjAiSWYKLtJhGEaTqCYxCCX2Dw+dOTqUzHOZ7WKv4JXPK5G/Uhr
+ 8K/qhmFT2nIQi538n6rVYLeWj8Bbnl+ev0peYzxFyF5sQA==
+ </ds:X509Certificate>
+ </ds:X509Data>
+ </ds:KeyInfo>
+ </KeyDescriptor>
+ <AttributeService Binding="urn:oasis:names:tc:SAML:1.0:bindings:SOAP-binding"
+ Location="https://idp.testshib.org:8443/idp/profile/SAML1/SOAP/AttributeQuery" />
+ <AttributeService Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP"
+ Location="https://idp.testshib.org:8443/idp/profile/SAML2/SOAP/AttributeQuery" />
+ <NameIDFormat>urn:mace:shibboleth:1.0:nameIdentifier</NameIDFormat>
+ <NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient
+ </NameIDFormat>
+ </AttributeAuthorityDescriptor>
+ <Organization>
+ <OrganizationName xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+ xml:lang="en">TestShib Two Identity Provider</OrganizationName>
+ <OrganizationDisplayName xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+ xml:lang="en">TestShib Two</OrganizationDisplayName>
+ <OrganizationURL xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+ xml:lang="en">http://www.testshib.org/testshib-two/</OrganizationURL>
+ </Organization>
+ <ContactPerson contactType="technical">
+ <GivenName>Nate</GivenName>
+ <SurName>Klingenstein</SurName>
+ <EmailAddress>ndk(a)internet2.edu</EmailAddress>
+ </ContactPerson>
+ </EntityDescriptor>
+ <EntityDescriptor entityID="https://sp.testshib.org/shibboleth-sp">
+ <SPSSODescriptor
+ protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol urn:oasis:names:tc:SAML:1.1:protocol http://schemas.xmlsoap.org/ws/2003/07/secext">
+ <Extensions>
+ <idpdisc:DiscoveryResponse
+ Binding="urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol"
+ Location="https://sp.testshib.org/Shibboleth.sso/DS" index="1"
+ xmlns:idpdisc="urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol" />
+ </Extensions>
+ <KeyDescriptor>
+ <ds:KeyInfo>
+ <ds:X509Data>
+ <ds:X509Certificate>MIIEPjCCAyagAwIBAgIBADANBgkqhkiG9w0BAQUFADB3MQswCQYDVQQGEwJVUzEV
+ MBMGA1UECBMMUGVubnN5bHZhbmlhMRMwEQYDVQQHEwpQaXR0c2J1cmdoMSIwIAYD
+ VQQKExlUZXN0U2hpYiBTZXJ2aWNlIFByb3ZpZGVyMRgwFgYDVQQDEw9zcC50ZXN0
+ c2hpYi5vcmcwHhcNMDYwODMwMjEyNDM5WhcNMTYwODI3MjEyNDM5WjB3MQswCQYD
+ VQQGEwJVUzEVMBMGA1UECBMMUGVubnN5bHZhbmlhMRMwEQYDVQQHEwpQaXR0c2J1
+ cmdoMSIwIAYDVQQKExlUZXN0U2hpYiBTZXJ2aWNlIFByb3ZpZGVyMRgwFgYDVQQD
+ Ew9zcC50ZXN0c2hpYi5vcmcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
+ AQDJyR6ZP6MXkQ9z6RRziT0AuCabDd3x1m7nLO9ZRPbr0v1LsU+nnC363jO8nGEq
+ sqkgiZ/bSsO5lvjEt4ehff57ERio2Qk9cYw8XCgmYccVXKH9M+QVO1MQwErNobWb
+ AjiVkuhWcwLWQwTDBowfKXI87SA7KR7sFUymNx5z1aoRvk3GM++tiPY6u4shy8c7
+ vpWbVfisfTfvef/y+galxjPUQYHmegu7vCbjYP3On0V7/Ivzr+r2aPhp8egxt00Q
+ XpilNai12LBYV3Nv/lMsUzBeB7+CdXRVjZOHGuQ8mGqEbsj8MBXvcxIKbcpeK5Zi
+ JCVXPfarzuriM1G5y5QkKW+LAgMBAAGjgdQwgdEwHQYDVR0OBBYEFKB6wPDxwYrY
+ StNjU5P4b4AjBVQVMIGhBgNVHSMEgZkwgZaAFKB6wPDxwYrYStNjU5P4b4AjBVQV
+ oXukeTB3MQswCQYDVQQGEwJVUzEVMBMGA1UECBMMUGVubnN5bHZhbmlhMRMwEQYD
+ VQQHEwpQaXR0c2J1cmdoMSIwIAYDVQQKExlUZXN0U2hpYiBTZXJ2aWNlIFByb3Zp
+ ZGVyMRgwFgYDVQQDEw9zcC50ZXN0c2hpYi5vcmeCAQAwDAYDVR0TBAUwAwEB/zAN
+ BgkqhkiG9w0BAQUFAAOCAQEAc06Kgt7ZP6g2TIZgMbFxg6vKwvDL0+2dzF11Onpl
+ 5sbtkPaNIcj24lQ4vajCrrGKdzHXo9m54BzrdRJ7xDYtw0dbu37l1IZVmiZr12eE
+ Iay/5YMU+aWP1z70h867ZQ7/7Y4HW345rdiS6EW663oH732wSYNt9kr7/0Uer3KD
+ 9CuPuOidBacospDaFyfsaJruE99Kd6Eu/w5KLAGG+m0iqENCziDGzVA47TngKz2v
+ PVA+aokoOyoz3b53qeti77ijatSEoKjxheBWpO+eoJeGq/e49Um3M2ogIX/JAlMa
+ Inh+vYSYngQB2sx9LGkR9KHaMKNIGCDehk93Xla4pWJx1w==
+ </ds:X509Certificate>
+ </ds:X509Data>
+ </ds:KeyInfo>
+ </KeyDescriptor>
+ <SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP"
+ Location="https://sp.testshib.org/Shibboleth.sso/SLO/SOAP" />
+ <SingleLogoutService
+ Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
+ Location="https://sp.testshib.org/Shibboleth.sso/SLO/Redirect" />
+ <SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
+ Location="https://sp.testshib.org/Shibboleth.sso/SLO/POST" />
+ <SingleLogoutService
+ Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"
+ Location="https://sp.testshib.org/Shibboleth.sso/SLO/Artifact" />
+ <NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient
+ </NameIDFormat>
+ <NameIDFormat>urn:mace:shibboleth:1.0:nameIdentifier</NameIDFormat>
+ <AssertionConsumerService
+ Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://sp.testshib.org/Shibboleth.sso/SAML2/POST"
+ index="1" isDefault="true" />
+ <AssertionConsumerService
+ Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST-SimpleSign"
+ Location="https://sp.testshib.org/Shibboleth.sso/SAML2/POST-SimpleSign"
+ index="2" />
+ <AssertionConsumerService
+ Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"
+ Location="https://sp.testshib.org/Shibboleth.sso/SAML2/Artifact"
+ index="3" />
+ <AssertionConsumerService
+ Binding="urn:oasis:names:tc:SAML:1.0:profiles:browser-post"
+ Location="https://sp.testshib.org/Shibboleth.sso/SAML/POST" index="4" />
+ <AssertionConsumerService
+ Binding="urn:oasis:names:tc:SAML:1.0:profiles:artifact-01" Location="https://sp.testshib.org/Shibboleth.sso/SAML/Artifact"
+ index="5" />
+ <AssertionConsumerService
+ Binding="http://schemas.xmlsoap.org/ws/2003/07/secext" Location="https://sp.testshib.org/Shibboleth.sso/ADFS"
+ index="6" />
+ <AssertionConsumerService
+ Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://www.testshib.org/Shibboleth.sso/SAML2/POST"
+ index="7" />
+ <AssertionConsumerService
+ Binding="urn:oasis:names:tc:SAML:1.0:profiles:browser-post"
+ Location="https://www.testshib.org/Shibboleth.sso/SAML/POST" index="8" />
+ </SPSSODescriptor>
+ <Organization>
+ <OrganizationName xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+ xml:lang="en">TestShib Two Service Provider</OrganizationName>
+ <OrganizationDisplayName xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+ xml:lang="en">TestShib Two</OrganizationDisplayName>
+ <OrganizationURL xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
+ xml:lang="en">http://www.testshib.org/testshib-two/</OrganizationURL>
+ </Organization>
+ <ContactPerson contactType="technical">
+ <GivenName>Nate</GivenName>
+ <SurName>Klingenstein</SurName>
+ <EmailAddress>ndk(a)internet2.edu</EmailAddress>
+ </ContactPerson>
+ </EntityDescriptor>
+</EntitiesDescriptor>
\ No newline at end of file
Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/config/SPType.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/config/SPType.java 2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/config/SPType.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -47,6 +47,8 @@
protected String serviceURL;
+ protected String idpMetadataFile;
+
/**
* Gets the value of the serviceURL property.
*
@@ -73,4 +75,21 @@
this.serviceURL = value;
}
-}
+ /**
+ * Get the IDP metadata file String
+ * @return
+ */
+ public String getIdpMetadataFile()
+ {
+ return idpMetadataFile;
+ }
+
+ /**
+ * Set the IDP Metadata file String
+ * @param idpMetadataFile
+ */
+ public void setIdpMetadataFile(String idpMetadataFile)
+ {
+ this.idpMetadataFile = idpMetadataFile;
+ }
+}
\ No newline at end of file
Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/parsers/config/SAMLConfigParser.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/parsers/config/SAMLConfigParser.java 2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/parsers/config/SAMLConfigParser.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -49,45 +49,58 @@
public class SAMLConfigParser extends AbstractParser
{
public static final String IDP = "PicketLinkIDP";
+
public static final String SP = "PicketLinkSP";
public static final String IDENTITY_URL = "IdentityURL";
+
public static final String SERVICE_URL = "ServiceURL";
+ public static final String IDP_METADATA_FILE = "IDPMetadataFile";
+
public static final String TRUST = "Trust";
public static final String DOMAINS = "Domains";
public static final String KEY_PROVIDER = "KeyProvider";
+
public static final String META_PROVIDER = "MetaDataProvider";
- public static final String CLASS_NAME = "ClassName";
- public static final String CLASS = "class";
+
+ public static final String CLASS_NAME = "ClassName";
+
+ public static final String CLASS = "class";
+
public static final String AUTH = "Auth";
+
public static final String KEY = "Key";
+
public static final String VALUE = "Value";
+
public static final String VALIDATING_ALIAS = "ValidatingAlias";
+
public static final String ASSERTION_VALIDITY = "AssertionValidity";
public static final String ROLE_GENERATOR = "RoleGenerator";
public static final String ENCRYPT = "Encrypt";
+ public static final String ATTRIBUTE_MANAGER = "AttributeManager";
- public static final String ATTRIBUTE_MANAGER = "AttributeManager";
public static final String CANONICALIZATION_METHOD = "CanonicalizationMethod";
public static final String HANDLERS = "Handlers";
+
public static final String HANDLER = "Handler";
+
public static final String OPTION = "Option";
-
public Object parse(XMLEventReader xmlEventReader) throws ParsingException
{
- StartElement startElement = StaxParserUtil.peekNextStartElement( xmlEventReader );
+ StartElement startElement = StaxParserUtil.peekNextStartElement(xmlEventReader);
- if( StaxParserUtil.getStartElementName(startElement).equals( IDP ))
- return parseIDPConfiguration( xmlEventReader );
- if( StaxParserUtil.getStartElementName(startElement).equals( SP ))
+ if (StaxParserUtil.getStartElementName(startElement).equals(IDP))
+ return parseIDPConfiguration(xmlEventReader);
+ if (StaxParserUtil.getStartElementName(startElement).equals(SP))
return parseSPConfiguration(xmlEventReader);
return parseHandlers(xmlEventReader);
@@ -98,13 +111,13 @@
return false;
}
- protected Handlers parseHandlers( XMLEventReader xmlEventReader ) throws ParsingException
+ protected Handlers parseHandlers(XMLEventReader xmlEventReader) throws ParsingException
{
Handlers handlers = new Handlers();
-
- StartElement startElement = StaxParserUtil.getNextStartElement( xmlEventReader );
- StaxParserUtil.validate( startElement, HANDLERS );
+ StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
+ StaxParserUtil.validate(startElement, HANDLERS);
+
while (xmlEventReader.hasNext())
{
XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader);
@@ -114,59 +127,58 @@
{
EndElement endElement = (EndElement) StaxParserUtil.getNextEvent(xmlEventReader);
String endElementName = StaxParserUtil.getEndElementName(endElement);
- if (endElementName.equals( HANDLERS ))
+ if (endElementName.equals(HANDLERS))
break;
else
throw new RuntimeException("Unknown End Element:" + endElementName);
}
startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
- if ( startElement == null)
+ if (startElement == null)
break;
- String elementName = StaxParserUtil.getStartElementName( startElement );
- if( elementName.equals( HANDLER ))
+ String elementName = StaxParserUtil.getStartElementName(startElement);
+ if (elementName.equals(HANDLER))
{
- Handler handler = parseHandler(xmlEventReader, startElement);
+ Handler handler = parseHandler(xmlEventReader, startElement);
handlers.add(handler);
- }
- }
-
+ }
+ }
+
return handlers;
}
- protected IDPType parseIDPConfiguration( XMLEventReader xmlEventReader ) throws ParsingException
+ protected IDPType parseIDPConfiguration(XMLEventReader xmlEventReader) throws ParsingException
{
IDPType idp = new IDPType();
- StartElement startElement = StaxParserUtil.getNextStartElement( xmlEventReader );
- StaxParserUtil.validate( startElement, IDP );
+ StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
+ StaxParserUtil.validate(startElement, IDP);
// parse and set the root element attributes.
QName attributeQName = new QName("", ASSERTION_VALIDITY);
Attribute attribute = startElement.getAttributeByName(attributeQName);
if (attribute != null)
- idp.setAssertionValidity( Long.parseLong( StaxParserUtil.getAttributeValue( attribute )) );
+ idp.setAssertionValidity(Long.parseLong(StaxParserUtil.getAttributeValue(attribute)));
attributeQName = new QName("", ROLE_GENERATOR);
attribute = startElement.getAttributeByName(attributeQName);
if (attribute != null)
- idp.setRoleGenerator( StaxParserUtil.getAttributeValue( attribute )) ;
+ idp.setRoleGenerator(StaxParserUtil.getAttributeValue(attribute));
attributeQName = new QName("", ENCRYPT);
attribute = startElement.getAttributeByName(attributeQName);
if (attribute != null)
- idp.setEncrypt( Boolean.parseBoolean( StaxParserUtil.getAttributeValue( attribute )) ) ;
+ idp.setEncrypt(Boolean.parseBoolean(StaxParserUtil.getAttributeValue(attribute)));
- attributeQName = new QName("", CANONICALIZATION_METHOD );
+ attributeQName = new QName("", CANONICALIZATION_METHOD);
attribute = startElement.getAttributeByName(attributeQName);
if (attribute != null)
- idp.setCanonicalizationMethod( StaxParserUtil.getAttributeValue( attribute ));
+ idp.setCanonicalizationMethod(StaxParserUtil.getAttributeValue(attribute));
- attributeQName = new QName("", ATTRIBUTE_MANAGER );
+ attributeQName = new QName("", ATTRIBUTE_MANAGER);
attribute = startElement.getAttributeByName(attributeQName);
if (attribute != null)
- idp.setAttributeManager( StaxParserUtil.getAttributeValue( attribute ));
+ idp.setAttributeManager(StaxParserUtil.getAttributeValue(attribute));
-
while (xmlEventReader.hasNext())
{
XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader);
@@ -176,57 +188,55 @@
{
EndElement endElement = (EndElement) StaxParserUtil.getNextEvent(xmlEventReader);
String endElementName = StaxParserUtil.getEndElementName(endElement);
- if (endElementName.equals( IDP ))
+ if (endElementName.equals(IDP))
break;
else
throw new RuntimeException("Unknown End Element:" + endElementName);
}
startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
- if ( startElement == null)
+ if (startElement == null)
break;
- String elementName = StaxParserUtil.getStartElementName( startElement );
- if( elementName.equals( IDENTITY_URL ))
+ String elementName = StaxParserUtil.getStartElementName(startElement);
+ if (elementName.equals(IDENTITY_URL))
{
- idp.setIdentityURL( StaxParserUtil.getElementText(xmlEventReader) );
+ idp.setIdentityURL(StaxParserUtil.getElementText(xmlEventReader));
}
- else if( elementName.equals( TRUST ))
+ else if (elementName.equals(TRUST))
{
TrustType trustType = new TrustType();
startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
StaxParserUtil.validate(startElement, DOMAINS);
- trustType.setDomains( StaxParserUtil.getElementText(xmlEventReader) );
+ trustType.setDomains(StaxParserUtil.getElementText(xmlEventReader));
EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
StaxParserUtil.validate(endElement, TRUST);
idp.setTrust(trustType);
}
- else if( elementName.equals( KEY_PROVIDER) )
+ else if (elementName.equals(KEY_PROVIDER))
{
KeyProviderType keyProviderType = this.parseKeyProvider(xmlEventReader, startElement);
idp.setKeyProvider(keyProviderType);
}
- else if( elementName.equals( META_PROVIDER) )
+ else if (elementName.equals(META_PROVIDER))
{
- MetadataProviderType mdProviderType = parseMDProvider( xmlEventReader, startElement);
- idp.setMetaDataProvider( mdProviderType );
+ MetadataProviderType mdProviderType = parseMDProvider(xmlEventReader, startElement);
+ idp.setMetaDataProvider(mdProviderType);
}
}
- return idp;
+ return idp;
}
- protected SPType parseSPConfiguration( XMLEventReader xmlEventReader ) throws ParsingException
+ protected SPType parseSPConfiguration(XMLEventReader xmlEventReader) throws ParsingException
{
SPType sp = new SPType();
- StartElement startElement = StaxParserUtil.getNextStartElement( xmlEventReader );
- StaxParserUtil.validate( startElement, SP );
+ StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
+ StaxParserUtil.validate(startElement, SP);
-
- QName attributeQName = new QName("", CANONICALIZATION_METHOD );
+ QName attributeQName = new QName("", CANONICALIZATION_METHOD);
Attribute attribute = startElement.getAttributeByName(attributeQName);
if (attribute != null)
- sp.setCanonicalizationMethod( StaxParserUtil.getAttributeValue( attribute ));
+ sp.setCanonicalizationMethod(StaxParserUtil.getAttributeValue(attribute));
-
while (xmlEventReader.hasNext())
{
XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader);
@@ -236,186 +246,191 @@
{
EndElement endElement = (EndElement) StaxParserUtil.getNextEvent(xmlEventReader);
String endElementName = StaxParserUtil.getEndElementName(endElement);
- if (endElementName.equals( SP ))
+ if (endElementName.equals(SP))
break;
else
throw new RuntimeException("Unknown End Element:" + endElementName);
}
startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
- if ( startElement == null)
+ if (startElement == null)
break;
- String elementName = StaxParserUtil.getStartElementName( startElement );
- if( elementName.equals( IDENTITY_URL ))
+ String elementName = StaxParserUtil.getStartElementName(startElement);
+ if (elementName.equals(IDENTITY_URL))
{
- sp.setIdentityURL( StaxParserUtil.getElementText(xmlEventReader) );
+ sp.setIdentityURL(StaxParserUtil.getElementText(xmlEventReader));
}
- else if( elementName.equals( SERVICE_URL ))
+ else if (elementName.equals(SERVICE_URL))
{
- sp.setServiceURL( StaxParserUtil.getElementText(xmlEventReader) );
+ sp.setServiceURL(StaxParserUtil.getElementText(xmlEventReader));
}
- else if( elementName.equals( TRUST ))
+ else if (elementName.equals(IDP_METADATA_FILE))
{
+ sp.setIdpMetadataFile(StaxParserUtil.getElementText(xmlEventReader));
+ }
+ else if (elementName.equals(TRUST))
+ {
TrustType trustType = new TrustType();
startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
StaxParserUtil.validate(startElement, DOMAINS);
- trustType.setDomains( StaxParserUtil.getElementText(xmlEventReader) );
+ trustType.setDomains(StaxParserUtil.getElementText(xmlEventReader));
EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
StaxParserUtil.validate(endElement, TRUST);
sp.setTrust(trustType);
}
- else if( elementName.equals( KEY_PROVIDER) )
+ else if (elementName.equals(KEY_PROVIDER))
{
- KeyProviderType keyProviderType = parseKeyProvider(xmlEventReader, startElement);
+ KeyProviderType keyProviderType = parseKeyProvider(xmlEventReader, startElement);
sp.setKeyProvider(keyProviderType);
}
- else if( elementName.equals( META_PROVIDER) )
+ else if (elementName.equals(META_PROVIDER))
{
- MetadataProviderType mdProviderType = parseMDProvider( xmlEventReader, startElement);
- sp.setMetaDataProvider( mdProviderType );
+ MetadataProviderType mdProviderType = parseMDProvider(xmlEventReader, startElement);
+ sp.setMetaDataProvider(mdProviderType);
}
}
return sp;
}
- protected KeyProviderType parseKeyProvider(XMLEventReader xmlEventReader, StartElement startElement ) throws ParsingException
+ protected KeyProviderType parseKeyProvider(XMLEventReader xmlEventReader, StartElement startElement)
+ throws ParsingException
{
XMLEvent xmlEvent = null;
KeyProviderType keyProviderType = new KeyProviderType();
// parse and set the ClassName element attributes.
- QName attributeQName = new QName("", CLASS_NAME );
+ QName attributeQName = new QName("", CLASS_NAME);
Attribute attribute = startElement.getAttributeByName(attributeQName);
if (attribute != null)
- keyProviderType.setClassName( StaxParserUtil.getAttributeValue( attribute ) );
+ keyProviderType.setClassName(StaxParserUtil.getAttributeValue(attribute));
- while( xmlEventReader.hasNext() )
+ while (xmlEventReader.hasNext())
{
xmlEvent = StaxParserUtil.peek(xmlEventReader);
- if( xmlEvent == null )
+ if (xmlEvent == null)
break;
- if( xmlEvent instanceof EndElement )
+ if (xmlEvent instanceof EndElement)
{
EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
- String endElementName = StaxParserUtil.getEndElementName( endElement );
- if( endElementName.equals( KEY_PROVIDER ))
+ String endElementName = StaxParserUtil.getEndElementName(endElement);
+ if (endElementName.equals(KEY_PROVIDER))
break;
else
continue;
}
startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
String startElementName = StaxParserUtil.getStartElementName(startElement);
- if( startElementName.equals( AUTH ))
+ if (startElementName.equals(AUTH))
{
AuthPropertyType auth = new AuthPropertyType();
populateKeyValueType(auth, startElement);
keyProviderType.add(auth);
}
- else if( startElementName.equals( VALIDATING_ALIAS ))
+ else if (startElementName.equals(VALIDATING_ALIAS))
{
KeyValueType auth = new KeyValueType();
populateKeyValueType(auth, startElement);
keyProviderType.add(auth);
}
- }
- return keyProviderType;
+ }
+ return keyProviderType;
}
-
- protected Handler parseHandler(XMLEventReader xmlEventReader, StartElement startElement ) throws ParsingException
+
+ protected Handler parseHandler(XMLEventReader xmlEventReader, StartElement startElement) throws ParsingException
{
XMLEvent xmlEvent = null;
Handler handlerType = new Handler();
// parse and set the ClassName element attributes.
- QName attributeQName = new QName("", CLASS );
+ QName attributeQName = new QName("", CLASS);
Attribute attribute = startElement.getAttributeByName(attributeQName);
if (attribute != null)
- handlerType.setClazz( StaxParserUtil.getAttributeValue( attribute ) );
+ handlerType.setClazz(StaxParserUtil.getAttributeValue(attribute));
- while( xmlEventReader.hasNext() )
+ while (xmlEventReader.hasNext())
{
xmlEvent = StaxParserUtil.peek(xmlEventReader);
- if( xmlEvent == null )
+ if (xmlEvent == null)
break;
- if( xmlEvent instanceof EndElement )
+ if (xmlEvent instanceof EndElement)
{
EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
- String endElementName = StaxParserUtil.getEndElementName( endElement );
- if( endElementName.equals( HANDLER ))
+ String endElementName = StaxParserUtil.getEndElementName(endElement);
+ if (endElementName.equals(HANDLER))
break;
else
continue;
}
startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
String startElementName = StaxParserUtil.getStartElementName(startElement);
-
- if( startElementName.equals( OPTION ))
+
+ if (startElementName.equals(OPTION))
{
KeyValueType auth = new KeyValueType();
populateKeyValueType(auth, startElement);
handlerType.add(auth);
}
- }
- return handlerType;
+ }
+ return handlerType;
}
- protected MetadataProviderType parseMDProvider(XMLEventReader xmlEventReader, StartElement startElement ) throws ParsingException
+ protected MetadataProviderType parseMDProvider(XMLEventReader xmlEventReader, StartElement startElement)
+ throws ParsingException
{
XMLEvent xmlEvent = null;
MetadataProviderType metaProviderType = new MetadataProviderType();
// parse and set the ClassName element attributes.
- QName attributeQName = new QName("", CLASS_NAME );
+ QName attributeQName = new QName("", CLASS_NAME);
Attribute attribute = startElement.getAttributeByName(attributeQName);
if (attribute != null)
- metaProviderType.setClassName( StaxParserUtil.getAttributeValue( attribute ) );
+ metaProviderType.setClassName(StaxParserUtil.getAttributeValue(attribute));
- while( xmlEventReader.hasNext() )
+ while (xmlEventReader.hasNext())
{
xmlEvent = StaxParserUtil.peek(xmlEventReader);
- if( xmlEvent == null )
+ if (xmlEvent == null)
break;
- if( xmlEvent instanceof EndElement )
+ if (xmlEvent instanceof EndElement)
{
EndElement endElement = StaxParserUtil.getNextEndElement(xmlEventReader);
- String endElementName = StaxParserUtil.getEndElementName( endElement );
- if( endElementName.equals( META_PROVIDER ))
+ String endElementName = StaxParserUtil.getEndElementName(endElement);
+ if (endElementName.equals(META_PROVIDER))
break;
else
continue;
}
startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
String startElementName = StaxParserUtil.getStartElementName(startElement);
- if( startElementName.equals( OPTION ))
+ if (startElementName.equals(OPTION))
{
KeyValueType auth = new KeyValueType();
populateKeyValueType(auth, startElement);
metaProviderType.add(auth);
- }
- }
- return metaProviderType;
+ }
+ }
+ return metaProviderType;
}
- protected void populateKeyValueType( KeyValueType kvt, StartElement startElement )
+ protected void populateKeyValueType(KeyValueType kvt, StartElement startElement)
{
- QName attributeQName = new QName("", KEY );
+ QName attributeQName = new QName("", KEY);
Attribute attribute = startElement.getAttributeByName(attributeQName);
if (attribute != null)
- kvt.setKey( StaxParserUtil.getAttributeValue( attribute ) );
+ kvt.setKey(StaxParserUtil.getAttributeValue(attribute));
- attributeQName = new QName("", OPTION );
+ attributeQName = new QName("", OPTION);
attribute = startElement.getAttributeByName(attributeQName);
if (attribute != null)
- kvt.setKey( StaxParserUtil.getAttributeValue( attribute ) );
+ kvt.setKey(StaxParserUtil.getAttributeValue(attribute));
-
- attributeQName = new QName("", VALUE );
+ attributeQName = new QName("", VALUE);
attribute = startElement.getAttributeByName(attributeQName);
if (attribute != null)
- kvt.setValue( StaxParserUtil.getAttributeValue( attribute ) );
+ kvt.setValue(StaxParserUtil.getAttributeValue(attribute));
}
}
\ No newline at end of file
Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/constants/JBossSAMLURIConstants.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/constants/JBossSAMLURIConstants.java 2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/saml/v2/constants/JBossSAMLURIConstants.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -64,6 +64,9 @@
SIGNATURE_DSA_SHA1("http://www.w3.org/2000/09/xmldsig#dsa-sha1"),
SIGNATURE_RSA_SHA1("http://www.w3.org/2000/09/xmldsig#rsa-sha1"),
+ SAML_HTTP_POST_BINDING("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"),
+ SAML_HTTP_REDIRECT_BINDING("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"),
+
SUBJECT_CONFIRMATION_BEARER("urn:oasis:names:tc:SAML:2.0:cm:bearer"),
Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/CoreConfigUtil.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/CoreConfigUtil.java 2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/CoreConfigUtil.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -38,11 +38,17 @@
import org.picketlink.identity.federation.core.config.KeyProviderType;
import org.picketlink.identity.federation.core.config.KeyValueType;
import org.picketlink.identity.federation.core.config.ProviderType;
+import org.picketlink.identity.federation.core.config.SPType;
import org.picketlink.identity.federation.core.config.TokenProviderType;
import org.picketlink.identity.federation.core.constants.PicketLinkFederationConstants;
import org.picketlink.identity.federation.core.exceptions.ConfigurationException;
import org.picketlink.identity.federation.core.exceptions.ProcessingException;
import org.picketlink.identity.federation.core.interfaces.TrustKeyManager;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EndpointType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntityDescriptorType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntityDescriptorType.EDTChoiceType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntityDescriptorType.EDTDescriptorChoiceType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.IDPSSODescriptorType;
/**
* Utility for configuration
@@ -62,9 +68,9 @@
public static TrustKeyManager getTrustKeyManager(ProviderType idpOrSPConfiguration)
{
KeyProviderType keyProvider = idpOrSPConfiguration.getKeyProvider();
- return getTrustKeyManager(keyProvider);
+ return getTrustKeyManager(keyProvider);
}
-
+
/**
* Once the {@code KeyProviderType} is derived, get
* the {@code TrustKeyManager}
@@ -73,24 +79,24 @@
*/
public static TrustKeyManager getTrustKeyManager(KeyProviderType keyProvider)
{
- TrustKeyManager trustKeyManager = null;
+ TrustKeyManager trustKeyManager = null;
try
{
ClassLoader tcl = SecurityActions.getContextClassLoader();
String keyManagerClassName = keyProvider.getClassName();
- if(keyManagerClassName == null)
+ if (keyManagerClassName == null)
throw new RuntimeException("KeyManager class name is null");
Class<?> clazz = tcl.loadClass(keyManagerClassName);
trustKeyManager = (TrustKeyManager) clazz.newInstance();
}
- catch(Exception e)
+ catch (Exception e)
{
- log.error("Exception in getting TrustKeyManager:",e);
- }
- return trustKeyManager;
+ log.error("Exception in getting TrustKeyManager:", e);
+ }
+ return trustKeyManager;
}
-
+
/**
* Get the validating key
* @param idpSpConfiguration
@@ -100,13 +106,13 @@
* @throws ProcessingException
*/
public static PublicKey getValidatingKey(ProviderType idpSpConfiguration, String domain)
- throws ConfigurationException, ProcessingException
+ throws ConfigurationException, ProcessingException
{
- TrustKeyManager trustKeyManager = getTrustKeyManager(idpSpConfiguration);
-
- return getValidatingKey(trustKeyManager, domain);
- }
-
+ TrustKeyManager trustKeyManager = getTrustKeyManager(idpSpConfiguration);
+
+ return getValidatingKey(trustKeyManager, domain);
+ }
+
/**
* Get the validating key given the trust key manager
* @param trustKeyManager
@@ -115,16 +121,15 @@
* @throws ConfigurationException
* @throws ProcessingException
*/
- public static PublicKey getValidatingKey(TrustKeyManager trustKeyManager,
- String domain)
- throws ConfigurationException, ProcessingException
- {
- if(trustKeyManager == null)
+ public static PublicKey getValidatingKey(TrustKeyManager trustKeyManager, String domain)
+ throws ConfigurationException, ProcessingException
+ {
+ if (trustKeyManager == null)
throw new IllegalArgumentException("Trust Key Manager is null");
-
- return trustKeyManager.getValidatingKey(domain);
- }
-
+
+ return trustKeyManager.getValidatingKey(domain);
+ }
+
/**
* Given a {@code KeyProviderType}, return the list of auth properties that have been decrypted for any
* masked password
@@ -133,15 +138,16 @@
* @throws GeneralSecurityException
*/
@SuppressWarnings("unchecked")
- public static List<AuthPropertyType> getKeyProviderProperties( KeyProviderType keyProviderType ) throws GeneralSecurityException
+ public static List<AuthPropertyType> getKeyProviderProperties(KeyProviderType keyProviderType)
+ throws GeneralSecurityException
{
List<AuthPropertyType> authProperties = keyProviderType.getAuth();
- if( decryptionNeeded( authProperties ))
+ if (decryptionNeeded(authProperties))
authProperties = decryptPasswords(authProperties);
-
+
return authProperties;
}
-
+
/**
* Given a {@code TokenProviderType}, return the list of properties that have been decrypted for
* any masked property value
@@ -150,15 +156,15 @@
* @throws GeneralSecurityException
*/
@SuppressWarnings("unchecked")
- public static List<KeyValueType> getProperties( TokenProviderType tokenProviderType ) throws GeneralSecurityException
+ public static List<KeyValueType> getProperties(TokenProviderType tokenProviderType) throws GeneralSecurityException
{
List<KeyValueType> keyValueTypeList = tokenProviderType.getProperty();
- if( decryptionNeeded( keyValueTypeList ))
- keyValueTypeList = decryptPasswords( keyValueTypeList );
-
+ if (decryptionNeeded(keyValueTypeList))
+ keyValueTypeList = decryptPasswords(keyValueTypeList);
+
return keyValueTypeList;
}
-
+
/**
* Given a {@code ClaimsProcessorType}, return the list of properties that have been decrypted for
* any masked property value
@@ -167,37 +173,38 @@
* @throws GeneralSecurityException
*/
@SuppressWarnings("unchecked")
- public static List<KeyValueType> getProperties( ClaimsProcessorType claimsProcessorType ) throws GeneralSecurityException
+ public static List<KeyValueType> getProperties(ClaimsProcessorType claimsProcessorType)
+ throws GeneralSecurityException
{
List<KeyValueType> keyValueTypeList = claimsProcessorType.getProperty();
- if( decryptionNeeded( keyValueTypeList ))
- keyValueTypeList = decryptPasswords( keyValueTypeList );
-
+ if (decryptionNeeded(keyValueTypeList))
+ keyValueTypeList = decryptPasswords(keyValueTypeList);
+
return keyValueTypeList;
}
-
+
/**
* Given a key value list, check if decrypt of any properties is needed.
* Unless one of the keys is "salt", we cannot figure out is decrypt is needed
* @param keyValueList
* @return
*/
- public static boolean decryptionNeeded( List<? extends KeyValueType> keyValueList )
- {
+ public static boolean decryptionNeeded(List<? extends KeyValueType> keyValueList)
+ {
int length = keyValueList.size();
-
+
//Let us run through the list to see if there is any salt
- for( int i = 0 ; i < length; i++ )
+ for (int i = 0; i < length; i++)
{
- KeyValueType kvt = keyValueList.get( i );
-
+ KeyValueType kvt = keyValueList.get(i);
+
String key = kvt.getKey();
- if(PicketLinkFederationConstants.SALT.equalsIgnoreCase( key ) )
- return true;
+ if (PicketLinkFederationConstants.SALT.equalsIgnoreCase(key))
+ return true;
}
- return false;
+ return false;
}
-
+
/**
* Given a key value pair read from PicketLink configuration, ensure
* that we replace the masked passwords with the decoded passwords
@@ -207,75 +214,130 @@
* @return
* @throws GeneralSecurityException
* @throws Exception
- */
+ */
@SuppressWarnings("rawtypes")
- private static List decryptPasswords( List keyValueList ) throws GeneralSecurityException
+ private static List decryptPasswords(List keyValueList) throws GeneralSecurityException
{
String pbeAlgo = PicketLinkFederationConstants.PBE_ALGORITHM;
-
+
String salt = null;
int iterationCount = 0;
-
+
int length = keyValueList.size();
-
+
//Let us run through the list to see if there is any salt
- for( int i = 0 ; i < length; i++ )
+ for (int i = 0; i < length; i++)
{
- KeyValueType kvt = (KeyValueType) keyValueList.get( i );
-
+ KeyValueType kvt = (KeyValueType) keyValueList.get(i);
+
String key = kvt.getKey();
- if(PicketLinkFederationConstants.SALT.equalsIgnoreCase( key ) )
+ if (PicketLinkFederationConstants.SALT.equalsIgnoreCase(key))
salt = kvt.getValue();
- if(PicketLinkFederationConstants.ITERATION_COUNT.equalsIgnoreCase( key ) )
- iterationCount = Integer.parseInt( kvt.getValue() );
+ if (PicketLinkFederationConstants.ITERATION_COUNT.equalsIgnoreCase(key))
+ iterationCount = Integer.parseInt(kvt.getValue());
}
-
- if( salt == null )
+
+ if (salt == null)
return keyValueList;
-
+
//Ok. there is a salt configured. So we have some properties with masked values
- List<KeyValueType> returningList = new ArrayList<KeyValueType>();
-
+ List<KeyValueType> returningList = new ArrayList<KeyValueType>();
+
// Create the PBE secret key
- SecretKeyFactory factory = SecretKeyFactory.getInstance( pbeAlgo );
+ SecretKeyFactory factory = SecretKeyFactory.getInstance(pbeAlgo);
char[] password = "somearbitrarycrazystringthatdoesnotmatter".toCharArray();
- PBEParameterSpec cipherSpec = new PBEParameterSpec( salt.getBytes(), iterationCount );
+ PBEParameterSpec cipherSpec = new PBEParameterSpec(salt.getBytes(), iterationCount);
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKey cipherKey = factory.generateSecret(keySpec);
-
- for( int i = 0 ; i < length; i++ )
+ for (int i = 0; i < length; i++)
{
- KeyValueType kvt = (KeyValueType) keyValueList.get( i );
-
+ KeyValueType kvt = (KeyValueType) keyValueList.get(i);
+
String val = kvt.getValue();
- if( val.startsWith( PicketLinkFederationConstants.PASS_MASK_PREFIX) )
+ if (val.startsWith(PicketLinkFederationConstants.PASS_MASK_PREFIX))
{
- val = val.substring( PicketLinkFederationConstants.PASS_MASK_PREFIX.length() );
+ val = val.substring(PicketLinkFederationConstants.PASS_MASK_PREFIX.length());
String decodedValue;
try
{
- decodedValue = PBEUtils.decode64( val, pbeAlgo , cipherKey, cipherSpec);
+ decodedValue = PBEUtils.decode64(val, pbeAlgo, cipherKey, cipherSpec);
}
catch (UnsupportedEncodingException e)
{
- throw new RuntimeException( e );
- }
-
+ throw new RuntimeException(e);
+ }
+
KeyValueType newKVT = new KeyValueType();
- if( keyValueList.get( 0 ) instanceof AuthPropertyType )
+ if (keyValueList.get(0) instanceof AuthPropertyType)
newKVT = new AuthPropertyType();
- newKVT.setKey( kvt.getKey() );
- newKVT.setValue( new String( decodedValue ) );
- returningList.add( newKVT );
+ newKVT.setKey(kvt.getKey());
+ newKVT.setValue(new String(decodedValue));
+ returningList.add(newKVT);
}
else
{
- returningList.add( kvt );
+ returningList.add(kvt);
}
}
-
- return returningList;
+
+ return returningList;
}
+
+ public static SPType getSPConfiguration(EntityDescriptorType entityDescriptor, String bindingURI)
+ {
+ List<EDTChoiceType> edtChoices = entityDescriptor.getChoiceType();
+ for (EDTChoiceType edt : edtChoices)
+ {
+ List<EDTDescriptorChoiceType> edtDescriptors = edt.getDescriptors();
+ for (EDTDescriptorChoiceType edtDesc : edtDescriptors)
+ {
+ IDPSSODescriptorType idpSSO = edtDesc.getIdpDescriptor();
+ if (idpSSO != null)
+ {
+ return getSPConfiguration(idpSSO, bindingURI);
+ }
+ }
+ }
+ return null;
+ }
+
+ public static IDPSSODescriptorType getIDPDescriptor(EntityDescriptorType entityDescriptor)
+ {
+ List<EDTChoiceType> edtChoices = entityDescriptor.getChoiceType();
+ for (EDTChoiceType edt : edtChoices)
+ {
+ List<EDTDescriptorChoiceType> edtDescriptors = edt.getDescriptors();
+ for (EDTDescriptorChoiceType edtDesc : edtDescriptors)
+ {
+ IDPSSODescriptorType idpSSO = edtDesc.getIdpDescriptor();
+ if (idpSSO != null)
+ {
+ return idpSSO;
+ }
+ }
+ }
+ return null;
+ }
+
+ public static SPType getSPConfiguration(IDPSSODescriptorType idp, String bindingURI)
+ {
+ String identityURL = null;
+
+ SPType sp = new SPType();
+ List<EndpointType> endpoints = idp.getSingleSignOnService();
+ for (EndpointType endpoint : endpoints)
+ {
+ if (endpoint.getBinding().toString().equals(bindingURI))
+ {
+ identityURL = endpoint.getLocation().toString();
+ break;
+ }
+
+ }
+ //get identity url
+ sp.setIdentityURL(identityURL);
+ return sp;
+ }
}
\ No newline at end of file
Modified: federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/XMLSignatureUtil.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/XMLSignatureUtil.java 2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-fed-core/src/main/java/org/picketlink/identity/federation/core/util/XMLSignatureUtil.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -80,29 +80,29 @@
public class XMLSignatureUtil
{
private static Logger log = Logger.getLogger(XMLSignatureUtil.class);
+
private static boolean trace = log.isTraceEnabled();
- private static String canonicalizationMethodType = CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS;
-
- private static XMLSignatureFactory fac = getXMLSignatureFactory();
-
+ private static String canonicalizationMethodType = CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS;
+
+ private static XMLSignatureFactory fac = getXMLSignatureFactory();
+
private static XMLSignatureFactory getXMLSignatureFactory()
{
- XMLSignatureFactory xsf = null;
-
+ XMLSignatureFactory xsf = null;
+
try
{
- xsf = XMLSignatureFactory.getInstance("DOM");
- }
- catch(Exception err)
+ xsf = XMLSignatureFactory.getInstance("DOM");
+ }
+ catch (Exception err)
{
//JDK5
- xsf = XMLSignatureFactory.getInstance("DOM",
- new org.jcp.xml.dsig.internal.dom.XMLDSigRI());
+ xsf = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI());
}
return xsf;
}
-
+
//Set some system properties
static
{
@@ -110,22 +110,22 @@
{
public Object run()
{
- System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true");
+ System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true");
return null;
}
- });
- };
-
+ });
+ };
+
/**
* Set the canonicalization method type
* @param canonical
*/
- public static void setCanonicalizationMethodType( String canonical )
+ public static void setCanonicalizationMethodType(String canonical)
{
- if( canonical != null )
+ if (canonical != null)
canonicalizationMethodType = canonical;
}
-
+
/**
* Precheck whether the document that will be validated
* has the right signedinfo
@@ -137,7 +137,7 @@
NodeList nl = doc.getElementsByTagNameNS(JBossSAMLURIConstants.XMLDSIG_NSURI.get(), "SignedInfo");
return nl != null ? nl.getLength() > 0 : false;
}
-
+
/**
* Sign a node in a document
* @param doc Document
@@ -153,20 +153,14 @@
* @throws GeneralSecurityException
* @throws ParserConfigurationException
*/
- public static Document sign(Document doc,
- Node parentOfNodeToBeSigned,
- PrivateKey signingKey,
- X509Certificate certificate,
- String digestMethod,
- String signatureMethod,
- String referenceURI)
- throws ParserConfigurationException, GeneralSecurityException, MarshalException, XMLSignatureException
+ public static Document sign(Document doc, Node parentOfNodeToBeSigned, PrivateKey signingKey,
+ X509Certificate certificate, String digestMethod, String signatureMethod, String referenceURI)
+ throws ParserConfigurationException, GeneralSecurityException, MarshalException, XMLSignatureException
{
- KeyPair keyPair = new KeyPair(certificate.getPublicKey(),signingKey);
- return sign(doc,parentOfNodeToBeSigned, keyPair,
- digestMethod, signatureMethod, referenceURI);
+ KeyPair keyPair = new KeyPair(certificate.getPublicKey(), signingKey);
+ return sign(doc, parentOfNodeToBeSigned, keyPair, digestMethod, signatureMethod, referenceURI);
}
-
+
/**
* Sign a node in a document
* @param doc
@@ -181,41 +175,37 @@
* @throws XMLSignatureException
* @throws MarshalException
* @throws GeneralSecurityException
- */
- public static Document sign(Document doc,
- Node nodeToBeSigned,
- KeyPair keyPair,
- String digestMethod,
- String signatureMethod,
- String referenceURI) throws ParserConfigurationException, GeneralSecurityException, MarshalException, XMLSignatureException
- {
- if(nodeToBeSigned == null)
+ */
+ public static Document sign(Document doc, Node nodeToBeSigned, KeyPair keyPair, String digestMethod,
+ String signatureMethod, String referenceURI) throws ParserConfigurationException, GeneralSecurityException,
+ MarshalException, XMLSignatureException
+ {
+ if (nodeToBeSigned == null)
throw new IllegalArgumentException("Node to be signed is null");
- if(trace)
+ if (trace)
{
- log.trace("Document to be signed=" + DocumentUtil.asString(doc));
+ log.trace("Document to be signed=" + DocumentUtil.asString(doc));
}
-
+
Node parentNode = nodeToBeSigned.getParentNode();
-
+
//Let us create a new Document
Document newDoc = DocumentUtil.createDocument();
//Import the node
Node signingNode = newDoc.importNode(nodeToBeSigned, true);
newDoc.appendChild(signingNode);
-
+
newDoc = sign(newDoc, keyPair, digestMethod, signatureMethod, referenceURI);
-
+
//Now let us import this signed doc into the original document we got in the method call
Node signedNode = doc.importNode(newDoc.getFirstChild(), true);
-
+
parentNode.replaceChild(signedNode, nodeToBeSigned);
//doc.getDocumentElement().replaceChild(signedNode, nodeToBeSigned);
-
- return doc;
+
+ return doc;
}
-
-
+
/**
* Sign the root element
* @param doc
@@ -229,54 +219,47 @@
* @throws XMLSignatureException
* @throws MarshalException
*/
- public static Document sign(Document doc,
- KeyPair keyPair,
- String digestMethod,
- String signatureMethod,
- String referenceURI) throws GeneralSecurityException, MarshalException, XMLSignatureException
- {
- if(trace)
+ public static Document sign(Document doc, KeyPair keyPair, String digestMethod, String signatureMethod,
+ String referenceURI) throws GeneralSecurityException, MarshalException, XMLSignatureException
+ {
+ if (trace)
{
- log.trace("Document to be signed=" + DocumentUtil.asString(doc));
+ log.trace("Document to be signed=" + DocumentUtil.asString(doc));
}
PrivateKey signingKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
-
- DOMSignContext dsc = new DOMSignContext(signingKey, doc.getDocumentElement());
- dsc.setDefaultNamespacePrefix("dsig");
-
- DigestMethod digestMethodObj = fac.newDigestMethod(digestMethod, null);
- Transform transform1 = fac.newTransform(Transform.ENVELOPED,
- (TransformParameterSpec) null);
- Transform transform2 = fac.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#",
- (TransformParameterSpec) null);
- List<Transform> transformList = new ArrayList<Transform>() ;
- transformList.add(transform1);
- transformList.add(transform2);
+ DOMSignContext dsc = new DOMSignContext(signingKey, doc.getDocumentElement());
+ dsc.setDefaultNamespacePrefix("dsig");
- Reference ref = fac.newReference
- ( referenceURI, digestMethodObj,transformList,null, null);
-
- CanonicalizationMethod canonicalizationMethod
- = fac.newCanonicalizationMethod
- (canonicalizationMethodType, (C14NMethodParameterSpec) null);
-
- List<Reference> referenceList = Collections.singletonList(ref);
- SignatureMethod signatureMethodObj = fac.newSignatureMethod(signatureMethod, null);
- SignedInfo si = fac.newSignedInfo (canonicalizationMethod, signatureMethodObj ,
- referenceList);
-
- KeyInfoFactory kif = fac.getKeyInfoFactory();
- KeyValue kv = kif.newKeyValue(publicKey);
- KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
+ DigestMethod digestMethodObj = fac.newDigestMethod(digestMethod, null);
+ Transform transform1 = fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
+ Transform transform2 = fac.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null);
- XMLSignature signature = fac.newXMLSignature(si, ki);
+ List<Transform> transformList = new ArrayList<Transform>();
+ transformList.add(transform1);
+ transformList.add(transform2);
- signature.sign(dsc);
-
- return doc;
- }
+ Reference ref = fac.newReference(referenceURI, digestMethodObj, transformList, null, null);
+
+ CanonicalizationMethod canonicalizationMethod = fac.newCanonicalizationMethod(canonicalizationMethodType,
+ (C14NMethodParameterSpec) null);
+
+ List<Reference> referenceList = Collections.singletonList(ref);
+ SignatureMethod signatureMethodObj = fac.newSignatureMethod(signatureMethod, null);
+ SignedInfo si = fac.newSignedInfo(canonicalizationMethod, signatureMethodObj, referenceList);
+
+ KeyInfoFactory kif = fac.getKeyInfoFactory();
+ KeyValue kv = kif.newKeyValue(publicKey);
+ KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
+
+ XMLSignature signature = fac.newXMLSignature(si, ki);
+
+ signature.sign(dsc);
+
+ return doc;
+ }
+
/**
* Validate a signed document with the given public key
* @param signedDoc
@@ -286,37 +269,37 @@
* @throws XMLSignatureException
*/
@SuppressWarnings("unchecked")
- public static boolean validate(Document signedDoc, Key publicKey) throws MarshalException, XMLSignatureException
+ public static boolean validate(Document signedDoc, Key publicKey) throws MarshalException, XMLSignatureException
{
- if(signedDoc == null)
+ if (signedDoc == null)
throw new IllegalArgumentException("Signed Document is null");
NodeList nl = signedDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
- if (nl == null || nl.getLength() == 0)
+ if (nl == null || nl.getLength() == 0)
{
- throw new IllegalArgumentException("Cannot find Signature element");
- }
- if(publicKey == null)
+ throw new IllegalArgumentException("Cannot find Signature element");
+ }
+ if (publicKey == null)
throw new IllegalArgumentException("Public Key is null");
-
- DOMValidateContext valContext = new DOMValidateContext(publicKey, nl.item(0));
- XMLSignature signature = fac.unmarshalXMLSignature(valContext);
- boolean coreValidity = signature.validate(valContext);
- if(trace && !coreValidity)
+ DOMValidateContext valContext = new DOMValidateContext(publicKey, nl.item(0));
+ XMLSignature signature = fac.unmarshalXMLSignature(valContext);
+ boolean coreValidity = signature.validate(valContext);
+
+ if (trace && !coreValidity)
{
boolean sv = signature.getSignatureValue().validate(valContext);
- log.trace("Signature validation status: " + sv);
-
+ log.trace("Signature validation status: " + sv);
+
List<Reference> references = signature.getSignedInfo().getReferences();
- for(Reference ref:references)
+ for (Reference ref : references)
{
- log.trace("[Ref id=" + ref.getId() +":uri=" + ref.getURI() +
- "]validity status:" + ref.validate(valContext));
- }
+ log.trace("[Ref id=" + ref.getId() + ":uri=" + ref.getURI() + "]validity status:"
+ + ref.validate(valContext));
+ }
}
return coreValidity;
}
-
+
/**
* Marshall a SignatureType to output stream
* @param signature
@@ -324,57 +307,57 @@
* @throws SAXException
* @throws JAXBException
*/
- public static void marshall(SignatureType signature, OutputStream os) throws JAXBException, SAXException
+ public static void marshall(SignatureType signature, OutputStream os) throws JAXBException, SAXException
{
- throw new RuntimeException( "NYI" );
+ throw new RuntimeException("NYI");
/*JAXBElement<SignatureType> jsig = objectFactory.createSignature(signature);
Marshaller marshaller = JAXBUtil.getValidatingMarshaller(pkgName, schemaLocation);
marshaller.marshal(jsig, os);*/
}
-
+
/**
* Marshall the signed document to an output stream
* @param signedDocument
* @param os
* @throws TransformerException
*/
- public static void marshall(Document signedDocument, OutputStream os)
- throws TransformerException
+ public static void marshall(Document signedDocument, OutputStream os) throws TransformerException
{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
- trans.transform(DocumentUtil.getXMLSource(signedDocument), new StreamResult(os));
+ trans.transform(DocumentUtil.getXMLSource(signedDocument), new StreamResult(os));
}
-
+
/**
* Given the X509Certificate in the keyinfo element, get a {@link X509Certificate}
* @param certificateString
* @return
* @throws ProcessingException
*/
- public static X509Certificate getX509CertificateFromKeyInfoString( String certificateString ) throws ProcessingException
+ public static X509Certificate getX509CertificateFromKeyInfoString(String certificateString)
+ throws ProcessingException
{
X509Certificate cert = null;
StringBuilder builder = new StringBuilder();
- builder.append( "-----BEGIN CERTIFICATE-----\n" ).append( certificateString ).append( "\n-----END CERTIFICATE-----" );
+ builder.append("-----BEGIN CERTIFICATE-----\n").append(certificateString).append("\n-----END CERTIFICATE-----");
String derFormattedString = builder.toString();
try
{
CertificateFactory cf = CertificateFactory.getInstance("X.509");
- ByteArrayInputStream bais = new ByteArrayInputStream( derFormattedString.getBytes());
+ ByteArrayInputStream bais = new ByteArrayInputStream(derFormattedString.getBytes());
- while ( bais.available() > 0)
+ while (bais.available() > 0)
{
cert = (X509Certificate) cf.generateCertificate(bais);
- }
- }
+ }
+ }
catch (java.security.cert.CertificateException e)
- {
- throw new ProcessingException( e );
+ {
+ throw new ProcessingException(e);
}
return cert;
}
-
+
}
\ No newline at end of file
Modified: federation/trunk/picketlink-fed-core/src/main/resources/schema/config/picketlink-fed.xsd
===================================================================
--- federation/trunk/picketlink-fed-core/src/main/resources/schema/config/picketlink-fed.xsd 2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-fed-core/src/main/resources/schema/config/picketlink-fed.xsd 2011-03-01 19:10:15 UTC (rev 786)
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
-<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:picketlink:identity-federation:config:1.0"
- xmlns:tns="urn:picketlink:identity-federation:config:1.0"
- elementFormDefault="qualified" version="1.0">
+<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:picketlink:identity-federation:config:2.0"
+ xmlns:tns="urn:picketlink:identity-federation:config:2.0"
+ elementFormDefault="qualified" version="2.0">
<complexType name="IDPType">
<annotation>
<documentation>
@@ -101,8 +101,7 @@
<documentation>Base Type for IDP and SP</documentation>
</annotation>
<sequence>
- <element name="IdentityURL" type="string" maxOccurs="1"
- minOccurs="1">
+ <element name="IdentityURL" type="string" maxOccurs="1" minOccurs="0">
</element>
<element name="Trust" type="tns:TrustType" maxOccurs="1"
minOccurs="0">
@@ -133,6 +132,7 @@
<extension base="tns:ProviderType">
<sequence>
<element name="ServiceURL" type="string"></element>
+ <element name="IDPMetadataFile" type="string" minOccurs="0" maxOccurs="1"></element>
</sequence>
</extension>
</complexContent>
Added: federation/trunk/picketlink-fed-core/src/test/java/org/picketlink/test/identity/federation/core/config/MetadataToSPTypeUnitTestCase.java
===================================================================
--- federation/trunk/picketlink-fed-core/src/test/java/org/picketlink/test/identity/federation/core/config/MetadataToSPTypeUnitTestCase.java (rev 0)
+++ federation/trunk/picketlink-fed-core/src/test/java/org/picketlink/test/identity/federation/core/config/MetadataToSPTypeUnitTestCase.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -0,0 +1,60 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.picketlink.test.identity.federation.core.config;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.io.InputStream;
+
+import org.junit.Test;
+import org.picketlink.identity.federation.core.config.SPType;
+import org.picketlink.identity.federation.core.parsers.saml.SAMLParser;
+import org.picketlink.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
+import org.picketlink.identity.federation.core.util.CoreConfigUtil;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntitiesDescriptorType;
+import org.picketlink.identity.federation.newmodel.saml.v2.metadata.EntityDescriptorType;
+
+/**
+ * Given an IDP metadata, construct {@link SPType}
+ * @author Anil.Saldhana(a)redhat.com
+ * @since Feb 28, 2011
+ */
+public class MetadataToSPTypeUnitTestCase
+{
+ private final String idpMetadata = "saml2/metadata/testshib.org.idp-metadata.xml";
+
+ @Test
+ public void testMetadataToSP() throws Exception
+ {
+ InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(idpMetadata);
+ assertNotNull(is);
+ SAMLParser parser = new SAMLParser();
+ EntitiesDescriptorType entities = (EntitiesDescriptorType) parser.parse(is);
+ assertNotNull(entities);
+
+ SPType sp = CoreConfigUtil.getSPConfiguration((EntityDescriptorType) entities.getEntityDescriptor().get(0),
+ JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.get());
+ assertNotNull(sp);
+ assertEquals("https://idp.testshib.org/idp/profile/SAML2/POST/SSO", sp.getIdentityURL());
+ }
+}
\ No newline at end of file
Modified: federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants/GeneralConstants.java
===================================================================
--- federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants/GeneralConstants.java 2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/constants/GeneralConstants.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -29,46 +29,64 @@
public interface GeneralConstants
{
String ASSERTIONS_VALIDITY = "ASSERTIONS_VALIDITY";
+
String ASSERTION_ID = "ASSERTION_ID";
+
String ASSERTION = "ASSERTION";
-
+
String ATTRIBUTES = "ATTRIBUTES";
+
String ATTRIBUTE_KEYS = "ATTRIBUTE_KEYS";
- String ATTIBUTE_MANAGER = "ATTRIBUTE_MANAGER";
-
+
+ String ATTIBUTE_MANAGER = "ATTRIBUTE_MANAGER";
+
String CANONICALIZATION_METHOD = "CANONICALIZATION_METHOD";
+
String CONFIGURATION = "CONFIGURATION";
+
String CONFIG_FILE_LOCATION = "/WEB-INF/picketlink-idfed.xml";
-
+
String GLOBAL_LOGOUT = "GLO";
-
+
String HANDLER_CONFIG_FILE_LOCATION = "/WEB-INF/picketlink-handlers.xml";
-
+
String IDENTITY_SERVER = "IDENTITY_SERVER";
+
String IDENTITY_PARTICIPANT_STACK = "IDENTITY_PARTICIPANT_STACK";
+
String IGNORE_SIGNATURES = "IGNORE_SIGNATURES";
-
- String KEYPAIR = "KEYPAIR";
-
+
+ String KEYPAIR = "KEYPAIR";
+
String LOGOUT_PAGE = "LOGOUT_PAGE";
+
String LOGOUT_PAGE_NAME = "/logout.jsp";
-
+
String PRINCIPAL_ID = "jboss_identity.principal";
+
String RELAY_STATE = "RelayState";
+
String ROLES = "ROLES";
+
String ROLES_ID = "jboss_identity.roles";
-
+
String ROLE_GENERATOR = "ROLE_GENERATOR";
+
String ROLE_VALIDATOR = "ROLE_VALIDATOR";
+
String ROLE_VALIDATOR_IGNORE = "ROLE_VALIDATOR_IGNORE";
-
+
String SAML_REQUEST_KEY = "SAMLRequest";
+
String SAML_RESPONSE_KEY = "SAMLResponse";
-
+
String DECRYPTING_KEY = "DECRYPTING_KEY";
+
String SENDER_PUBLIC_KEY = "SENDER_PUBLIC_KEY";
+
String SIGN_OUTGOING_MESSAGES = "SIGN_OUTGOING_MESSAGES";
-
+
String USERNAME_FIELD = "JBID_USERNAME";
+
String PASS_FIELD = "JBID_PASSWORD";
}
\ No newline at end of file
Modified: federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/util/ConfigurationUtil.java
===================================================================
--- federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/util/ConfigurationUtil.java 2011-02-28 21:22:22 UTC (rev 785)
+++ federation/trunk/picketlink-web/src/main/java/org/picketlink/identity/federation/web/util/ConfigurationUtil.java 2011-03-01 19:10:15 UTC (rev 786)
@@ -42,45 +42,30 @@
* @param is
* @return
* @throws ParsingException
- */
- public static IDPType getIDPConfiguration(InputStream is) throws ParsingException
+ */
+ public static IDPType getIDPConfiguration(InputStream is) throws ParsingException
{
- if(is == null)
+ if (is == null)
throw new IllegalArgumentException("inputstream is null");
- /*String schema = PicketLinkFederationConstants.SCHEMA_IDFED;
-
- Unmarshaller un = getUnmarshaller(schema);
-
- JAXBElement<IDPType> jaxbSp = (JAXBElement<IDPType>) un.unmarshal(is);
- return jaxbSp.getValue(); */
-
+
SAMLConfigParser parser = new SAMLConfigParser();
return (IDPType) parser.parse(is);
}
-
/**
* Get the SP Configuration from the
* passed inputstream
* @param is
* @return
* @throws ParsingException
- */
- public static SPType getSPConfiguration(InputStream is) throws ParsingException
+ */
+ public static SPType getSPConfiguration(InputStream is) throws ParsingException
{
- if(is == null)
+ if (is == null)
throw new IllegalArgumentException("inputstream is null");
- /*
- String schema = PicketLinkFederationConstants.SCHEMA_IDFED;
-
- Unmarshaller un = getUnmarshaller(schema);
-
- JAXBElement<SPType> jaxbSp = (JAXBElement<SPType>) un.unmarshal(is);
- return jaxbSp.getValue();
- */
return (SPType) (new SAMLConfigParser()).parse(is);
}
-
+
/**
* Get the Handlers from the configuration
* @param is
@@ -89,14 +74,8 @@
*/
public static Handlers getHandlers(InputStream is) throws ParsingException
{
- if(is == null)
- throw new IllegalArgumentException("inputstream is null");/*
- String[] schemas = new String[] { PicketLinkFederationConstants.SCHEMA_IDFED,
- PicketLinkFederationConstants.SCHEMA_IDFED_HANDLER};
-
- Unmarshaller un = getUnmarshaller(schemas);
- JAXBElement<Handlers> handlers = (JAXBElement<Handlers>) un.unmarshal(is);
- return handlers.getValue(); */
+ if (is == null)
+ throw new IllegalArgumentException("inputstream is null");
return (Handlers) (new SAMLConfigParser()).parse(is);
}
}
\ No newline at end of file
13 years, 10 months