use of com.sun.identity.saml2.protocol.Response in project OpenAM by OpenRock.
the class IDPSSOUtil method getSubject.
/**
* Returns a <code>SAML Subject</code> object
*
* @param session the user's session
* @param authnReq the <code>AuthnRequest</code> object
* @param acsURL the <code>ACS</code> service <code>url</code>
* @param nameIDFormat the <code>NameIDFormat</code>
* @param realm The realm name
* @param idpEntityID the entity id of the identity provider
* @param recipientEntityID the entity id of the response recipient
* @param effectiveTime the effective time of the assertion
* @param affiliationID affiliationID for IDP initiated SSO
* @return the <code>SAML Subject</code> object
* @throws SAML2Exception if the operation is not successful
*/
private static Subject getSubject(Object session, AuthnRequest authnReq, String acsURL, String nameIDFormat, String realm, String idpEntityID, String recipientEntityID, int effectiveTime, String affiliationID) throws SAML2Exception {
String classMethod = "IDPSSOUtil.getSubject: ";
Subject subject = AssertionFactory.getInstance().createSubject();
boolean ignoreProfile = false;
String userName = null;
try {
userName = sessionProvider.getPrincipalName(session);
ignoreProfile = SAML2Utils.isIgnoreProfileSet(session);
} catch (SessionException se) {
SAML2Utils.debug.error(classMethod + "There was a problem with the session.", se);
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
}
// allow create is the default
boolean allowCreate = true;
String remoteEntityID = null;
String spNameQualifier = null;
boolean isAffiliation = false;
if (authnReq != null) {
remoteEntityID = authnReq.getIssuer().getValue();
NameIDPolicy nameIDPolicy = authnReq.getNameIDPolicy();
if (nameIDPolicy != null) {
// this will take care of affiliation
allowCreate = nameIDPolicy.isAllowCreate();
spNameQualifier = nameIDPolicy.getSPNameQualifier();
if (spNameQualifier != null && !spNameQualifier.isEmpty()) {
AffiliationDescriptorType affiDesc = metaManager.getAffiliationDescriptor(realm, spNameQualifier);
if (affiDesc != null) {
if (affiDesc.getAffiliateMember().contains(remoteEntityID)) {
isAffiliation = true;
remoteEntityID = spNameQualifier;
} else {
throw new SAML2Exception(SAML2Utils.bundle.getString("spNotAffiliationMember"));
}
}
} else {
spNameQualifier = recipientEntityID;
}
}
} else {
// IDP initialted SSO
if (affiliationID != null) {
AffiliationDescriptorType affiDesc = metaManager.getAffiliationDescriptor(realm, affiliationID);
if (affiDesc == null) {
throw new SAML2Exception(SAML2Utils.bundle.getString("affiliationNotFound"));
}
if (affiDesc.getAffiliateMember().contains(recipientEntityID)) {
isAffiliation = true;
remoteEntityID = affiliationID;
spNameQualifier = affiliationID;
} else {
throw new SAML2Exception(SAML2Utils.bundle.getString("spNotAffiliationMember"));
}
} else {
remoteEntityID = recipientEntityID;
spNameQualifier = recipientEntityID;
}
}
SPSSODescriptorElement spsso = getSPSSODescriptor(realm, recipientEntityID, classMethod);
if (spsso == null) {
String[] data = { recipientEntityID };
LogUtil.error(Level.INFO, LogUtil.SP_METADATA_ERROR, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
IDPSSODescriptorElement idpsso = metaManager.getIDPSSODescriptor(realm, idpEntityID);
if (idpsso == null) {
String[] data = { idpEntityID };
LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
nameIDFormat = SAML2Utils.verifyNameIDFormat(nameIDFormat, spsso, idpsso);
boolean isTransient = SAML2Constants.NAMEID_TRANSIENT_FORMAT.equals(nameIDFormat);
boolean isPersistent = SAML2Constants.PERSISTENT.equals(nameIDFormat);
NameIDInfo nameIDInfo;
NameID nameID = null;
IDPAccountMapper idpAccountMapper = SAML2Utils.getIDPAccountMapper(realm, idpEntityID);
//Use-cases for NameID persistence:
//* persistent NameID -> The NameID MUST be stored
//* transient NameID -> The NameID MUST NOT be stored
//* ignored user profile mode -> The NameID CANNOT be stored
//* for any other cases -> The NameID MAY be stored based on customizable logic
boolean shouldPersistNameID = isPersistent || (!isTransient && !ignoreProfile && idpAccountMapper.shouldPersistNameIDFormat(realm, idpEntityID, remoteEntityID, nameIDFormat));
if (!isTransient) {
String userID;
try {
userID = sessionProvider.getPrincipalName(session);
} catch (SessionException se) {
SAML2Utils.debug.error(classMethod + "Unable to get principal name from the session.", se);
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
}
if (isPersistent || shouldPersistNameID) {
nameIDInfo = AccountUtils.getAccountFederation(userID, idpEntityID, remoteEntityID);
if (nameIDInfo != null) {
nameID = nameIDInfo.getNameID();
if (!nameIDFormat.equals(nameID.getFormat())) {
AccountUtils.removeAccountFederation(nameIDInfo, userID);
DoManageNameID.removeIDPFedSession(remoteEntityID, nameID.getValue());
nameID = null;
}
}
}
}
if (nameID == null) {
if (!allowCreate && isPersistent) {
throw new SAML2InvalidNameIDPolicyException(SAML2Utils.bundle.getString("cannotCreateNameID"));
}
nameID = idpAccountMapper.getNameID(session, idpEntityID, spNameQualifier, realm, nameIDFormat);
SAML2Utils.debug.message(classMethod + " shouldPersistNameID = " + shouldPersistNameID);
if (shouldPersistNameID && allowCreate) {
// write federation info into the persistent datastore
if (SAML2Utils.isDualRole(idpEntityID, realm)) {
nameIDInfo = new NameIDInfo(idpEntityID, remoteEntityID, nameID, SAML2Constants.DUAL_ROLE, false);
} else {
nameIDInfo = new NameIDInfo(idpEntityID, remoteEntityID, nameID, SAML2Constants.IDP_ROLE, isAffiliation);
}
AccountUtils.setAccountFederation(nameIDInfo, userName);
}
}
subject.setNameID(nameID);
if (isTransient) {
IDPCache.userIDByTransientNameIDValue.put(nameID.getValue(), userName);
}
String inResponseTo = null;
if (authnReq != null) {
inResponseTo = authnReq.getID();
}
SubjectConfirmation sc = getSubjectConfirmation(inResponseTo, acsURL, effectiveTime);
if (sc == null) {
SAML2Utils.debug.error(classMethod + "Unable to get subject confirmation");
throw new SAML2Exception(SAML2Utils.bundle.getString("noSubjectConfirmation"));
}
List list = new ArrayList();
list.add(sc);
subject.setSubjectConfirmation(list);
return subject;
}
use of com.sun.identity.saml2.protocol.Response in project OpenAM by OpenRock.
the class IDPSSOUtil method sendResponse.
/**
* Sends a response to service provider
*
* @param response the <code>HttpServletResponse</code> object
* @param acsBinding the assertion consumer service binding
* @param spEntityID the entity id of the service provider
* @param idpEntityID the entity id of the identity provider
* @param idpMetaAlias the meta alias of the identity provider
* @param realm the realm name
* @param relayState the relay state
* @param acsURL the assertion consumer service <code>url</code>
* @param res the <code>SAML Response</code> object
* @throws SAML2Exception if the operation is not successful
*/
public static void sendResponse(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String acsBinding, String spEntityID, String idpEntityID, String idpMetaAlias, String realm, String relayState, String acsURL, Response res, Object session) throws SAML2Exception {
String classMethod = "IDPSSOUtil.sendResponse: ";
String nameIDString = SAML2Utils.getNameIDStringFromResponse(res);
Map props = new HashMap();
props.put(LogUtil.NAME_ID, nameIDString);
// send the response back through HTTP POST or Artifact
if (acsBinding.equals(SAML2Constants.HTTP_POST)) {
// 4.1.4.5 POST-Specific Processing Rules (sstc-saml-profiles-errata-2.0-wd-06-diff.pdf)
//If response is not signed and POST binding is used, the assertion(s) MUST be signed.
// encryption is optional based on SP config settings.
boolean signAssertion = true;
// check if response needs to be signed.
boolean signResponse = SAML2Utils.wantPOSTResponseSigned(realm, spEntityID, SAML2Constants.SP_ROLE);
// so will base on wantAssertionsSigned flag
if (signResponse) {
signAssertion = wantAssertionsSigned(spEntityID, realm);
}
signAndEncryptResponseComponents(realm, spEntityID, idpEntityID, res, signAssertion);
if (signResponse) {
signResponse(realm, idpEntityID, res);
}
String resMsg = res.toXMLString(true, true);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "SAML Response content :\n" + resMsg);
}
String encodedResMsg = SAML2Utils.encodeForPOST(resMsg);
String[] logdata1 = { spEntityID, idpMetaAlias, resMsg };
LogUtil.access(Level.INFO, LogUtil.POST_RESPONSE, logdata1, session, props);
try {
SAML2Utils.postToTarget(request, response, "SAMLResponse", encodedResMsg, "RelayState", relayState, acsURL);
} catch (SAML2Exception saml2E) {
String[] data = { acsURL };
LogUtil.error(Level.INFO, LogUtil.POST_TO_TARGET_FAILED, data, session, props);
throw saml2E;
}
} else if (acsBinding.equals(SAML2Constants.HTTP_ARTIFACT)) {
IDPSSOUtil.sendResponseArtifact(request, response, idpEntityID, spEntityID, realm, acsURL, relayState, res, session, props);
} else if (acsBinding.equals(SAML2Constants.PAOS)) {
// signing assertion is a must for ECP profile.
// encryption is optional based on SP config settings.
signAndEncryptResponseComponents(realm, spEntityID, idpEntityID, res, true);
IDPSSOUtil.sendResponseECP(request, response, out, idpEntityID, realm, acsURL, res);
} else {
SAML2Utils.debug.error(classMethod + "unsupported return binding.");
throw new SAML2Exception(SAML2Utils.bundle.getString("UnSupportedReturnBinding"));
}
}
use of com.sun.identity.saml2.protocol.Response in project OpenAM by OpenRock.
the class IDPSSOUtil method getACSurlFromMetaByIndex.
/**
* Returns the assertion consumer service <code>URL</code> from
* meta data by binding
*
* @param spEntityID the entity id of the service provider
* @param realm the realm name of the identity provider
* @param acsIndex the <code>ACS</code> index
* @param returnedBinding the binding used to send back
* <code>Response</code>
* @return the assertion consumer service <code>URL</code>
* @throws SAML2Exception if the operation is not successful
*/
public static String getACSurlFromMetaByIndex(String spEntityID, String realm, int acsIndex, StringBuffer returnedBinding) throws SAML2Exception {
String classMethod = "IDPSSOUtil.getACSurlFromMetaByIndex: ";
SPSSODescriptorElement spSSODescriptorElement = getSPSSODescriptor(realm, spEntityID, classMethod);
List acsList = spSSODescriptorElement.getAssertionConsumerService();
int index;
String acsURL = null;
String binding = null;
String defaultAcsURL = null;
String defaultBinding = null;
String firstAcsURL = null;
String firstBinding = null;
AssertionConsumerServiceElement acs = null;
for (int i = 0; i < acsList.size(); i++) {
acs = (AssertionConsumerServiceElement) acsList.get(i);
index = acs.getIndex();
binding = acs.getBinding();
if (index == acsIndex) {
acsURL = acs.getLocation();
binding = acs.getBinding();
break;
}
if (acs.isIsDefault()) {
defaultAcsURL = acs.getLocation();
defaultBinding = acs.getBinding();
}
if (i == 0) {
firstAcsURL = acs.getLocation();
firstBinding = acs.getBinding();
}
}
if (acsURL == null || acsURL.length() == 0) {
acsURL = defaultAcsURL;
if (acsURL == null || acsURL.length() == 0) {
acsURL = firstAcsURL;
if (acsURL == null || acsURL.length() == 0) {
acsURL = null;
SAML2Utils.debug.error(classMethod + "Unable to get valid Assertion " + "Consumer Service URL");
return null;
}
returnedBinding.append(firstBinding);
} else {
returnedBinding.append(defaultBinding);
}
} else {
returnedBinding.append(binding);
}
return acsURL;
}
use of com.sun.identity.saml2.protocol.Response in project OpenAM by OpenRock.
the class IDPSSOUtil method sendNoPassiveResponse.
/**
* A convenience method to construct NoPassive SAML error responses for SAML passive authentication requests.
*
* @param request The servlet request.
* @param response The servlet response.
* @param out The print writer for writing out presentation.
* @param idpMetaAlias The IdP's metaAlias.
* @param idpEntityID The IdP's entity ID.
* @param realm The realm where the IdP belongs to.
* @param authnReq The SAML AuthnRequest sent by the SP.
* @param relayState The RelayState value.
* @param spEntityID The SP's entity ID.
* @throws SAML2Exception If there was an error while creating or sending the response back to the SP.
*/
public static void sendNoPassiveResponse(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String idpMetaAlias, String idpEntityID, String realm, AuthnRequest authnReq, String relayState, String spEntityID) throws SAML2Exception {
Response res = SAML2Utils.getErrorResponse(authnReq, SAML2Constants.RESPONDER, SAML2Constants.NOPASSIVE, null, idpEntityID);
StringBuffer returnedBinding = new StringBuffer();
String acsURL = IDPSSOUtil.getACSurl(spEntityID, realm, authnReq, request, returnedBinding);
String acsBinding = returnedBinding.toString();
sendResponse(request, response, out, acsBinding, spEntityID, idpEntityID, idpMetaAlias, realm, relayState, acsURL, res, null);
}
use of com.sun.identity.saml2.protocol.Response in project OpenAM by OpenRock.
the class IDPSSOUtil method getAssertion.
/**
* Returns a <code>SAML Assertion</code> object
*
* @throws SAML2Exception if the operation is not successful
* @param request The HTTP request.
* @param session The user's session object.
* @param authnReq The <code>AuthnRequest</code> object.
* @param recipientEntityID The entity ID of the response recipient.
* @param idpEntityID The entity ID of the identity provider.
* @param realm The realm name.
* @param nameIDFormat The <code>NameIDFormat</code>.
* @param acsURL The <code>ACS</code> service <code>url</code>.
* @param affiliationID AffiliationID for IDP initiated SSO.
* @param matchingAuthnContext the <code>AuthnContext</code> used to find authentication type and scheme.
* @return the <code>SAML Assertion</code> object.
* @throws SAML2Exception if the operation is not successful.
*/
private static Assertion getAssertion(HttpServletRequest request, Object session, AuthnRequest authnReq, String recipientEntityID, String idpEntityID, String idpMetaAlias, String realm, String nameIDFormat, String acsURL, String affiliationID, AuthnContext matchingAuthnContext) throws SAML2Exception {
String classMethod = "IDPSSOUtil.getAssertion: ";
Assertion assertion = AssertionFactory.getInstance().createAssertion();
String assertionID = SAML2Utils.generateID();
assertion.setID(assertionID);
assertion.setVersion(SAML2Constants.VERSION_2_0);
assertion.setIssueInstant(new Date());
Issuer issuer = AssertionFactory.getInstance().createIssuer();
issuer.setValue(idpEntityID);
assertion.setIssuer(issuer);
List statementList = new ArrayList();
NewBoolean isNewSessionIndex = new NewBoolean();
AuthnStatement authnStatement = null;
IDPSession idpSession = null;
String sessionIndex = null;
String sessionID = sessionProvider.getSessionID(session);
synchronized (sessionID) {
authnStatement = getAuthnStatement(request, session, isNewSessionIndex, authnReq, idpEntityID, realm, matchingAuthnContext);
if (authnStatement == null) {
return null;
}
sessionIndex = authnStatement.getSessionIndex();
if (isNewSessionIndex.getValue()) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "This is a new IDP session with sessionIndex=" + sessionIndex + ", and sessionID=" + sessionID);
}
idpSession = (IDPSession) IDPCache.idpSessionsBySessionID.get(sessionProvider.getSessionID(session));
if (idpSession == null) {
idpSession = new IDPSession(session);
}
// Set the metaAlias in the IDP session object
idpSession.setMetaAlias(idpMetaAlias);
IDPCache.idpSessionsByIndices.put(sessionIndex, idpSession);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsByIndices.size());
}
} else {
idpSession = (IDPSession) IDPCache.idpSessionsByIndices.get(sessionIndex);
}
}
if (isNewSessionIndex.getValue()) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "a new IDP session has been saved in cache, " + "with sessionIndex=" + sessionIndex);
}
try {
sessionProvider.addListener(session, sessionListener);
} catch (SessionException e) {
SAML2Utils.debug.error(classMethod + "Unable to add session listener.");
}
} else {
if (idpSession == null && SAML2FailoverUtils.isSAML2FailoverEnabled()) {
// Read from SAML2 Token Repository
IDPSessionCopy idpSessionCopy = null;
try {
idpSessionCopy = (IDPSessionCopy) SAML2FailoverUtils.retrieveSAML2Token(sessionIndex);
} catch (SAML2TokenRepositoryException se) {
SAML2Utils.debug.error(classMethod + "Unable to obtain IDPSessionCopy from the SAML2 Token Repository for sessionIndex:" + sessionIndex, se);
}
// Copy back to IDPSession
if (idpSessionCopy != null) {
idpSession = new IDPSession(idpSessionCopy);
} else {
SAML2Utils.debug.error("IDPSessionCopy is null");
throw new SAML2Exception(SAML2Utils.bundle.getString("IDPSessionIsNULL"));
}
} else if ((idpSession == null) && (!SAML2FailoverUtils.isSAML2FailoverEnabled())) {
SAML2Utils.debug.error("IDPSession is null; SAML2 failover" + "is disabled");
throw new SAML2Exception(SAML2Utils.bundle.getString("IDPSessionIsNULL"));
} else {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "This is an existing IDP session with sessionIndex=" + sessionIndex + ", and sessionID=" + sessionProvider.getSessionID(idpSession.getSession()));
}
}
}
statementList.add(authnStatement);
AttributeStatement attrStatement = getAttributeStatement(session, idpEntityID, recipientEntityID, realm);
if (attrStatement != null) {
List attrStatementList = new ArrayList();
attrStatementList.add(attrStatement);
assertion.setAttributeStatements(attrStatementList);
}
// get the assertion effective time (in seconds)
int effectiveTime = getEffectiveTime(realm, idpEntityID);
// get the NotBefore skew (in seconds)
int notBeforeSkewTime = getNotBeforeSkewTime(realm, idpEntityID);
// get the subject element
Subject subject = getSubject(session, authnReq, acsURL, nameIDFormat, realm, idpEntityID, recipientEntityID, effectiveTime, affiliationID);
// register (spEntityID, nameID) with the sso token
// for later logout use
String spEntityID = null;
if (authnReq != null) {
spEntityID = authnReq.getIssuer().getValue();
} else {
spEntityID = recipientEntityID;
}
NameIDandSPpair pair = new NameIDandSPpair(subject.getNameID(), spEntityID);
synchronized (IDPCache.idpSessionsByIndices) {
List<NameIDandSPpair> list = idpSession.getNameIDandSPpairs();
String id;
if (authnReq != null) {
id = authnReq.getIssuer().getValue();
} else {
id = spEntityID;
}
boolean found = false;
for (NameIDandSPpair nameIDandSPpair : list) {
if (nameIDandSPpair.getSPEntityID().equals(id)) {
found = true;
break;
}
}
if (!found) {
list.add(pair);
}
}
assertion.setAuthnStatements(statementList);
assertion.setSubject(subject);
Conditions conditions = getConditions(recipientEntityID, notBeforeSkewTime, effectiveTime);
assertion.setConditions(conditions);
String discoBootstrapEnabled = getAttributeValueFromIDPSSOConfig(realm, idpEntityID, SAML2Constants.DISCO_BOOTSTRAPPING_ENABLED);
if ((discoBootstrapEnabled != null) && discoBootstrapEnabled.equalsIgnoreCase("true")) {
List attrStatementList = assertion.getAttributeStatements();
if (attrStatementList == null) {
attrStatementList = new ArrayList();
assertion.setAttributeStatements(attrStatementList);
}
DiscoveryBootstrap bootstrap = new DiscoveryBootstrap(session, subject, authnStatement.getAuthnContext().getAuthnContextClassRef(), spEntityID, realm);
attrStatementList.add(bootstrap.getBootstrapStatement());
assertion.setAdvice(bootstrap.getCredentials());
}
if (assertionCacheEnabled(realm, idpEntityID)) {
String userName = null;
try {
userName = sessionProvider.getPrincipalName(session);
} catch (SessionException se) {
SAML2Utils.debug.error(classMethod + "Unable to get principal name from the session.", se);
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
}
String cacheKey = userName.toLowerCase();
List assertions = (List) IDPCache.assertionCache.get(cacheKey);
if (assertions == null) {
synchronized (IDPCache.assertionCache) {
assertions = (List) IDPCache.assertionCache.get(cacheKey);
if (assertions == null) {
assertions = new ArrayList();
IDPCache.assertionCache.put(cacheKey, assertions);
}
}
}
synchronized (assertions) {
assertions.add(assertion);
}
IDPCache.assertionByIDCache.put(assertionID, assertion);
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
try {
SAML2FailoverUtils.saveSAML2Token(assertionID, cacheKey, assertion.toXMLString(true, true), conditions.getNotOnOrAfter().getTime() / 1000);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "Saving Assertion to SAML2 Token Repository. ID = " + assertionID);
}
} catch (SAML2TokenRepositoryException se) {
SAML2Utils.debug.error(classMethod + "Unable to save Assertion to the SAML2 Token Repository", se);
}
}
}
// Save to SAML2 Token Repository
try {
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
long sessionExpireTime = System.currentTimeMillis() / 1000 + (sessionProvider.getTimeLeft(session));
SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(sessionIndex, new IDPSessionCopy(idpSession), sessionExpireTime);
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "SAVE IDPSession!");
}
} catch (SessionException se) {
SAML2Utils.debug.error(classMethod + "Unable to get left-time from the session.", se);
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
} catch (SAML2TokenRepositoryException se) {
SAML2Utils.debug.error(classMethod + "Unable to save IDPSession to the SAML2 Token Repository", se);
}
return assertion;
}
Aggregations