use of com.sun.identity.saml2.plugins.SAML2IdentityProviderAdapter in project OpenAM by OpenRock.
the class IDPSSOUtil method sendResponseToACS.
/**
* Sends <code>Response</code> containing an <code>Assertion</code>
* back to the requesting service provider
*
* @param request the <code>HttpServletRequest</code> object
* @param response the <code>HttpServletResponse</code> object
* @param out the print writer for writing out presentation
* @param session user session
* @param authnReq the <code>AuthnRequest</code> object
* @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
* @param nameIDFormat the <code>NameIDFormat</code>
* @param relayState the relay state
* @param matchingAuthnContext the <code>AuthnContext</code> used to find
* authentication type and scheme.
*/
public static void sendResponseToACS(HttpServletRequest request, HttpServletResponse response, PrintWriter out, Object session, AuthnRequest authnReq, String spEntityID, String idpEntityID, String idpMetaAlias, String realm, String nameIDFormat, String relayState, AuthnContext matchingAuthnContext) throws SAML2Exception {
StringBuffer returnedBinding = new StringBuffer();
String acsURL = IDPSSOUtil.getACSurl(spEntityID, realm, authnReq, request, returnedBinding);
String acsBinding = returnedBinding.toString();
if ((acsURL == null) || (acsURL.trim().length() == 0)) {
SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " no ACS URL found.");
String[] data = { idpMetaAlias };
LogUtil.error(Level.INFO, LogUtil.NO_ACS_URL, data, session);
throw new SAML2Exception(SAML2Utils.bundle.getString("UnableTofindACSURL"));
}
if ((acsBinding == null) || (acsBinding.trim().length() == 0)) {
SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " no return binding found.");
String[] data = { idpMetaAlias };
LogUtil.error(Level.INFO, LogUtil.NO_RETURN_BINDING, data, session);
throw new SAML2Exception(SAML2Utils.bundle.getString("UnableTofindBinding"));
}
String affiliationID = request.getParameter(SAML2Constants.AFFILIATION_ID);
//check first if there is already an existing sessionindex associated with this SSOToken, if there is, then
//we need to redirect the request internally to the holder of the idpsession.
//The remoteServiceURL will be null if there is no sessionindex for this SSOToken, or there is, but it's
//local. If the remoteServiceURL is not null, we can start to send the request to the original server.
String remoteServiceURL = SAML2Utils.getRemoteServiceURL(getSessionIndex(session));
if (remoteServiceURL != null) {
remoteServiceURL += SAML2Utils.removeDeployUri(request.getRequestURI()) + "?" + request.getQueryString();
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SessionIndex for this SSOToken is not local, forwarding the request to: " + remoteServiceURL);
}
String redirectUrl = null;
String outputData = null;
String responseCode = null;
HashMap<String, String> remoteRequestData = SAML2Utils.sendRequestToOrigServer(request, response, remoteServiceURL);
if (remoteRequestData != null && !remoteRequestData.isEmpty()) {
redirectUrl = remoteRequestData.get(SAML2Constants.AM_REDIRECT_URL);
outputData = remoteRequestData.get(SAML2Constants.OUTPUT_DATA);
responseCode = remoteRequestData.get(SAML2Constants.RESPONSE_CODE);
}
try {
if (redirectUrl != null && !redirectUrl.isEmpty()) {
response.sendRedirect(redirectUrl);
} else {
if (responseCode != null) {
response.setStatus(Integer.valueOf(responseCode));
}
// no redirect, perhaps an error page, return the content
if (outputData != null && !outputData.isEmpty()) {
SAML2Utils.debug.message("Printing the forwarded response");
response.setContentType("text/html; charset=UTF-8");
out.println(outputData);
return;
}
}
} catch (IOException ioe) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS() error in Request Routing", ioe);
}
}
return;
}
//end of request proxy
// generate a response for the authn request
Response res = getResponse(request, session, authnReq, spEntityID, idpEntityID, idpMetaAlias, realm, nameIDFormat, acsURL, affiliationID, matchingAuthnContext);
if (res == null) {
SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " response is null");
String errorMsg = SAML2Utils.bundle.getString("UnableToCreateAssertion");
if (authnReq == null) {
//idp initiated case, will not send error response to sp
throw new SAML2Exception(errorMsg);
}
res = SAML2Utils.getErrorResponse(authnReq, SAML2Constants.RESPONDER, null, errorMsg, idpEntityID);
} else {
try {
String[] values = { idpMetaAlias };
sessionProvider.setProperty(session, SAML2Constants.IDP_META_ALIAS, values);
} catch (SessionException e) {
SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " error setting idpMetaAlias into the session: ", e);
}
}
if (res != null) {
// call multi-federation protocol to set the protocol
MultiProtocolUtils.addFederationProtocol(session, SingleLogoutManager.SAML2);
// check if the COT cookie needs to be set
if (setCOTCookie(request, response, acsBinding, spEntityID, idpEntityID, idpMetaAlias, realm, relayState, acsURL, res, session)) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS:" + " Redirected to set COT cookie.");
}
return;
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS:" + " Doesn't set COT cookie.");
SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS:" + " Response is: " + res.toXMLString());
}
try {
SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS: Invoking the IDP Adapter");
SAML2IdentityProviderAdapter idpAdapter = IDPSSOUtil.getIDPAdapterClass(realm, idpEntityID);
if (idpAdapter != null) {
idpAdapter.preSignResponse(authnReq, res, idpEntityID, realm, request, session, relayState);
}
} catch (SAML2Exception se) {
SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS: There was a problem when invoking the " + "preSendResponse of the IDP Adapter: ", se);
}
sendResponse(request, response, out, acsBinding, spEntityID, idpEntityID, idpMetaAlias, realm, relayState, acsURL, res, session);
} else {
SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " error response is null");
throw new SAML2Exception(SAML2Utils.bundle.getString("UnableToCreateErrorResponse"));
}
}
use of com.sun.identity.saml2.plugins.SAML2IdentityProviderAdapter in project OpenAM by OpenRock.
the class IDPSSOUtil method doSSOFederate.
/**
* Does SSO with existing federation or new federation
*
* @param request the <code>HttpServletRequest</code> object
* @param response the <code>HttpServletResponse</code> object
* @param out the print writer for writing out presentation
* @param authnReq the <code>AuthnRequest</code> object
* @param spEntityID the entity id of the service provider
* @param idpMetaAlias the meta alias of the identity provider
* @param nameIDFormat the <code>NameIDFormat</code>
* @param relayState the relay state
* @param newSession Session used in IDP Proxy Case
* @param auditor the auditor for logging SAML2 Events - may be null
* @throws SAML2Exception if the operation is not successful
*/
public static void doSSOFederate(HttpServletRequest request, HttpServletResponse response, PrintWriter out, AuthnRequest authnReq, String spEntityID, String idpMetaAlias, String nameIDFormat, String relayState, Object newSession, SAML2EventLogger auditor) throws SAML2Exception {
String classMethod = "IDPSSOUtil.doSSOFederate: ";
Object session = null;
if (newSession != null) {
session = newSession;
auditor.setSSOTokenId(session);
} else {
try {
session = sessionProvider.getSession(request);
if (null != auditor) {
auditor.setAuthTokenId(session);
}
} catch (SessionException se) {
if (SAML2Utils.debug.warningEnabled()) {
SAML2Utils.debug.warning(classMethod + "No session yet.");
}
}
}
// log the authnRequest
String authnRequestStr = null;
if (authnReq != null) {
authnRequestStr = authnReq.toXMLString();
auditor.setRequestId(authnReq.getID());
}
String[] logdata = { spEntityID, idpMetaAlias, authnRequestStr };
LogUtil.access(Level.INFO, LogUtil.RECEIVED_AUTHN_REQUEST, logdata, session);
// retrieve IDP entity id from meta alias
String idpEntityID = null;
String realm = null;
try {
if (metaManager == null) {
SAML2Utils.debug.error(classMethod + "Unable to get meta manager.");
throw new SAML2Exception(SAML2Utils.bundle.getString("errorMetaManager"));
}
idpEntityID = metaManager.getEntityByMetaAlias(idpMetaAlias);
if ((idpEntityID == null) || (idpEntityID.trim().length() == 0)) {
SAML2Utils.debug.error(classMethod + "Unable to get IDP Entity ID from meta.");
String[] data = { idpEntityID };
LogUtil.error(Level.INFO, LogUtil.INVALID_IDP, data, session);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
realm = SAML2MetaUtils.getRealmByMetaAlias(idpMetaAlias);
} catch (SAML2MetaException sme) {
SAML2Utils.debug.error(classMethod + "Unable to get IDP Entity ID from meta.");
String[] data = { idpMetaAlias };
LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, session);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
// check if the remote provider is valid
if (authnReq == null) {
Issuer issuer = AssertionFactory.getInstance().createIssuer();
issuer.setValue(spEntityID);
if (!SAML2Utils.isSourceSiteValid(issuer, realm, idpEntityID)) {
if (SAML2Utils.debug.warningEnabled()) {
SAML2Utils.debug.warning(classMethod + "The remote provider is not valid.");
}
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidReceiver"));
}
}
// Validate the RelayState URL.
SAML2Utils.validateRelayStateURL(realm, idpEntityID, relayState, SAML2Constants.IDP_ROLE);
if (authnReq == null && (session == null || !isValidSessionInRealm(realm, session))) {
// idp initiated and not logged in yet, need to authenticate
try {
if (Boolean.parseBoolean(request.getParameter(REDIRECTED))) {
if (session == null) {
String[] data = { idpEntityID };
SAML2Utils.debug.error(classMethod + "The IdP was not able to create a session");
LogUtil.error(Level.INFO, LogUtil.SSO_NOT_FOUND, data, session, null);
} else {
try {
String ipAddress = ClientUtils.getClientIPAddress(request);
String sessionRealm = SAML2Utils.getSingleValuedSessionProperty(session, SAML2Constants.ORGANIZATION);
String[] data = { sessionRealm, realm, spEntityID, ipAddress, null };
SAML2Utils.debug.error(classMethod + "The realm of the session (" + sessionRealm + ") does not correspond to that of the IdP (" + realm + ")");
LogUtil.error(Level.INFO, LogUtil.INVALID_REALM_FOR_SESSION, data, session, null);
} catch (SessionException se) {
SAML2Utils.debug.error(classMethod + "Failed to retrieve realm from session", se);
}
}
String rbKey = "UnableToDOSSOOrFederation";
SAMLUtils.sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rbKey, SAML2Utils.bundle.getString(rbKey));
} else {
redirectAuthentication(request, response, authnReq, null, realm, idpEntityID, spEntityID);
}
} catch (IOException ioe) {
SAML2Utils.debug.error(classMethod + "Unable to redirect to authentication.", ioe);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "UnableToRedirectToAuth", SAML2Utils.bundle.getString("UnableToRedirectToAuth"));
}
return;
}
// Invoke the IDP Adapter
try {
SAML2Utils.debug.message(classMethod + " Invoking the " + "IDP Adapter");
SAML2IdentityProviderAdapter idpAdapter = IDPSSOUtil.getIDPAdapterClass(realm, idpEntityID);
if (idpAdapter != null) {
// If the preSendResponse returns true we end here
if (idpAdapter.preSendResponse(authnReq, idpEntityID, realm, request, response, session, null, relayState)) {
return;
}
// else we continue with the logic. Beware of loops
}
} catch (SAML2Exception se2) {
SAML2Utils.debug.error(classMethod + " There was a problem when invoking" + "the preSendResponse of the IDP Adapter: ", se2);
}
// End of invocation
sendResponseToACS(request, response, out, session, authnReq, spEntityID, idpEntityID, idpMetaAlias, realm, nameIDFormat, relayState, null);
}
use of com.sun.identity.saml2.plugins.SAML2IdentityProviderAdapter in project OpenAM by OpenRock.
the class SAML2Utils method getIDPAdapterClass.
/**
* Returns a <code>SAML2IdentityProviderAdapter</code>
*
* @param realm the realm name
* @param idpEntityID the entity id of the identity provider
* @return the <code>SAML2IdentityProviderAdapter</code>
* @throws SAML2Exception if the operation is not successful
*/
public static SAML2IdentityProviderAdapter getIDPAdapterClass(String realm, String idpEntityID) throws SAML2Exception {
String classMethod = "SAML2Utils.getIDPAdapterClass: ";
String idpAdapterName = null;
SAML2IdentityProviderAdapter idpAdapter = null;
try {
idpAdapterName = IDPSSOUtil.getAttributeValueFromIDPSSOConfig(realm, idpEntityID, SAML2Constants.IDP_ADAPTER_CLASS);
if (idpAdapterName == null || idpAdapterName.trim().isEmpty()) {
idpAdapterName = SAML2Constants.DEFAULT_IDP_ADAPTER;
if (debug.messageEnabled()) {
debug.message(classMethod + " uses " + SAML2Constants.DEFAULT_IDP_ADAPTER);
}
}
// Attempt to retrieve the adapter from the cache
idpAdapter = (SAML2IdentityProviderAdapter) IDPCache.idpAdapterCache.get(realm + "$" + idpEntityID + "$" + idpAdapterName);
if (idpAdapter == null) {
// NB: multiple threads may cause several adapter objects to be created
idpAdapter = (SAML2IdentityProviderAdapter) Class.forName(idpAdapterName).newInstance();
idpAdapter.initialize(idpEntityID, realm);
// Add the adapter to the cache after initialization
IDPCache.idpAdapterCache.put(realm + "$" + idpEntityID + "$" + idpAdapterName, idpAdapter);
} else {
if (debug.messageEnabled()) {
debug.message(classMethod + " got the IDPAdapter from cache");
}
}
} catch (Exception ex) {
debug.error(classMethod + " unable to get IDP Adapter.", ex);
throw new SAML2Exception(ex);
}
return idpAdapter;
}
use of com.sun.identity.saml2.plugins.SAML2IdentityProviderAdapter in project OpenAM by OpenRock.
the class IDPSSOFederate method process.
@VisibleForTesting
void process(final HttpServletRequest request, final HttpServletResponse response, final PrintWriter out, final String reqBinding) throws FederatedSSOException, IOException, SessionException {
if (cookieRedirector.needSetLBCookieAndRedirect(request, response, true)) {
return;
}
final IDPRequestValidator validator = saml2ActorFactory.getIDPRequestValidator(reqBinding, isFromECP);
//IDP Proxy with introduction cookie case.
//After reading the introduction cookie, it redirects to here.
String requestID = request.getParameter("requestID");
if (idpProxyCase(requestID, request, response)) {
return;
}
// Fetch a number of properties about the request.
String idpMetaAlias = validator.getMetaAlias(request);
String realm = validator.getRealmByMetaAlias(idpMetaAlias);
String idpEntityID = validator.getIDPEntity(idpMetaAlias, realm);
SAML2IdentityProviderAdapter idpAdapter = validator.getIDPAdapter(realm, idpEntityID);
String reqID = request.getParameter(REQ_ID);
if (null != auditor && StringUtils.isNotEmpty(reqID)) {
auditor.setRequestId(reqID);
}
IDPSSOFederateRequest reqData = new IDPSSOFederateRequest(reqID, realm, idpAdapter, idpMetaAlias, idpEntityID);
reqData.setEventAuditor(auditor);
// id should be there.
if (StringUtils.isEmpty(reqData.getRequestID())) {
SAMLAuthenticator samlAuthenticator = saml2ActorFactory.getSAMLAuthenticator(reqData, request, response, out, isFromECP);
samlAuthenticator.authenticate();
} else {
SAMLAuthenticatorLookup samlLookup = saml2ActorFactory.getSAMLAuthenticatorLookup(reqData, request, response, out);
samlLookup.retrieveAuthenticationFromCache();
}
}
use of com.sun.identity.saml2.plugins.SAML2IdentityProviderAdapter in project OpenAM by OpenRock.
the class UtilProxyIDPRequestValidator method getIDPAdapter.
/**
* Loads the {@link SAML2IdentityProviderAdapter} IDP adapter which will be called as part
* of IDP processing.
*
* @param realm Possibly null realm.
* @param idpEntityID Non null idpEntityID.
*
* @return The loaded {@link SAML2IdentityProviderAdapter} if it could be loaded otherwise
* the default implementation {@link DefaultIDPAdapter}.
*/
public SAML2IdentityProviderAdapter getIDPAdapter(String realm, String idpEntityID) {
SAML2IdentityProviderAdapter r;
if (idpEntityID == null) {
if (debug.errorEnabled())
debug.error("No IDP Entity ID provided");
r = new DefaultIDPAdapter();
} else {
try {
r = IDPSSOUtil.getIDPAdapterClass(realm, idpEntityID);
} catch (SAML2Exception se2) {
debug.error("Unexpected error instantiating IDP Adapter: {0}", se2.getMessage(), se2);
r = new DefaultIDPAdapter();
}
}
debug.message("Using IDP Adapter class: {0}", r.getClass().getSimpleName());
return r;
}
Aggregations