Author: anil.saldhana(a)jboss.com
Date: 2011-07-28 17:38:57 -0400 (Thu, 28 Jul 2011)
New Revision: 1143
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
Log:
PLFED-197: refactor the sp methods
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-07-28
18:57:30 UTC (rev 1142)
+++
federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/BaseFormAuthenticator.java 2011-07-28
21:38:57 UTC (rev 1143)
@@ -37,6 +37,7 @@
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.dsig.CanonicalizationMethod;
@@ -46,6 +47,7 @@
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;
@@ -253,54 +255,42 @@
}
}
- //Mock test purpose
- public void testStart() throws LifecycleException
+ /**
+ * Fall back on local authentication at the service provider side
+ * @param request
+ * @param response
+ * @param loginConfig
+ * @return
+ * @throws IOException
+ */
+ protected boolean localAuthentication(Request request, Response response, LoginConfig
loginConfig)
+ throws IOException
{
- 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))
+ if (request.getUserPrincipal() == null)
{
- chain = SAML2HandlerChainFactory.createChain();
- }
- else
- {
+ log.error("Falling back on local Form Authentication if
available");//fallback
try
{
- chain = SAML2HandlerChainFactory.createChain(this.samlHandlerChainClass);
+ return super.authenticate(request, response, loginConfig);
}
- catch (ProcessingException e1)
+ catch (NoSuchMethodError e)
{
- throw new LifecycleException(e1);
+ //Use Reflection
+ try
+ {
+ Method method = super.getClass().getMethod("authenticate", new
Class[]
+ {HttpServletRequest.class, HttpServletResponse.class,
LoginConfig.class});
+ return (Boolean) method.invoke(this, new Object[]
+ {request.getRequest(), response.getResponse(), loginConfig});
+ }
+ catch (Exception ex)
+ {
+ throw new IOException("Unable to fallback on local auth", ex);
+ }
}
}
-
- 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);
- }
+ else
+ return true;
}
/**
@@ -481,6 +471,56 @@
}
}
+ //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);
+ }
+ }
+
private Class<?> getAuthenticatorBaseClass()
{
Class<?> myClass = getClass();
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-07-28
18:57:30 UTC (rev 1142)
+++
federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPPostFormAuthenticator.java 2011-07-28
21:38:57 UTC (rev 1143)
@@ -46,6 +46,7 @@
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.AssertionExpiredException;
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;
@@ -118,8 +119,6 @@
{
Session session = request.getSessionInternal(true);
- SPUtil spUtil = new SPUtil();
-
//Eagerly look for Local LogOut
String lloStr = request.getParameter(GeneralConstants.LOCAL_LOGOUT);
boolean localLogout = isNotNull(lloStr) &&
"true".equalsIgnoreCase(lloStr);
@@ -150,189 +149,256 @@
if (principal != null && !(logOutRequest || isNotNull(samlRequest) ||
isNotNull(samlResponse)))
return true;
+ //General User Request
+ if (!isNotNull(samlRequest) && !isNotNull(samlResponse))
+ {
+ return generalUserRequest(request, response, loginConfig);
+ }
+
+ //Handle a SAML Response from IDP
+ if (isNotNull(samlResponse))
+ {
+ return handleSAMLResponse(request, response, loginConfig);
+ }
+
+ //Handle SAML Requests from IDP
+ if (isNotNull(samlRequest))
+ {
+ return handleSAMLRequest(request, response, loginConfig);
+ }//end if
+
+ return localAuthentication(request, response, loginConfig);
+ }
+
+ /**
+ * Handle the IDP Request
+ * @param request
+ * @param response
+ * @param loginConfig
+ * @return
+ * @throws IOException
+ */
+ protected boolean handleSAMLRequest(Request request, Response response, LoginConfig
loginConfig) throws IOException
+ {
+ String samlRequest = request.getParameter(GeneralConstants.SAML_REQUEST_KEY);
+ HTTPContext httpContext = new HTTPContext(request, response,
context.getServletContext());
+ Set<SAML2Handler> handlers = chain.handlers();
+
+ try
+ {
+ ServiceProviderSAMLRequestProcessor requestProcessor = new
ServiceProviderSAMLRequestProcessor(true,
+ this.serviceURL);
+ requestProcessor.setTrustKeyManager(keyManager);
+ requestProcessor.setSupportSignatures(supportSignatures);
+ boolean result = requestProcessor.process(samlRequest, httpContext, handlers,
chainLock);
+
+ if (result)
+ return result;
+ }
+ catch (Exception e)
+ {
+ if (trace)
+ log.trace("Server Exception:", e);
+ throw new IOException("Server Exception");
+ }
+ return localAuthentication(request, response, loginConfig);
+ }
+
+ /**
+ * Handle IDP Response
+ * @param request
+ * @param response
+ * @param loginConfig
+ * @return
+ * @throws IOException
+ */
+ protected boolean handleSAMLResponse(Request request, Response response, LoginConfig
loginConfig) throws IOException
+ {
+ SPUtil spUtil = new SPUtil();
+ boolean isValid = false;
+ Session session = request.getSessionInternal(true);
+ String samlResponse = request.getParameter(GeneralConstants.SAML_RESPONSE_KEY);
+
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))
+ Principal principal = request.getUserPrincipal();
+ try
{
- //Neither saml request nor response from IDP
- //So this is a user request
- SAML2HandlerResponse saml2HandlerResponse = null;
- try
- {
- ServiceProviderBaseProcessor baseProcessor = new
ServiceProviderBaseProcessor(true, serviceURL);
- if (issuerID != null)
- baseProcessor.setIssuer(issuerID);
+ isValid = this.validate(request);
+ }
+ catch (Exception e)
+ {
+ log.error("Exception:", e);
+ throw new IOException();
+ }
+ if (!isValid)
+ throw new IOException("Validity check failed");
- baseProcessor.setIdentityURL(identityURL);
+ //deal with SAML response from IDP
+ try
+ {
+ ServiceProviderSAMLResponseProcessor responseProcessor = new
ServiceProviderSAMLResponseProcessor(true,
+ serviceURL);
+ responseProcessor.setValidateSignature(validateSignature);
+ responseProcessor.setTrustKeyManager(keyManager);
- saml2HandlerResponse = baseProcessor.process(httpContext, handlers,
chainLock);
- }
- catch (ProcessingException pe)
- {
- log.error("Processing Exception:", pe);
- throw new RuntimeException(pe);
- }
- catch (ParsingException pe)
- {
- log.error("Parsing Exception:", pe);
- throw new RuntimeException(pe);
- }
- catch (ConfigurationException pe)
- {
- log.error("Config Exception:", pe);
- throw new RuntimeException(pe);
- }
+ SAML2HandlerResponse saml2HandlerResponse =
responseProcessor.process(samlResponse, httpContext, handlers,
+ chainLock);
- willSendRequest = saml2HandlerResponse.getSendRequest();
-
Document samlResponseDocument = saml2HandlerResponse.getResultingDocument();
relayState = saml2HandlerResponse.getRelayState();
String destination = saml2HandlerResponse.getDestination();
+ willSendRequest = saml2HandlerResponse.getSendRequest();
+
if (destination != null && samlResponseDocument != null)
{
- try
+ sendRequestToIDP(destination, samlResponseDocument, relayState, response,
willSendRequest);
+ }
+ else
+ {
+ //See if the session has been invalidated
+
+ boolean sessionValidity = session.isValid();
+ if (!sessionValidity)
{
- if (saveRestoreRequest)
- {
- this.saveRequest(request, session);
- }
- sendRequestToIDP(destination, samlResponseDocument, relayState, response,
willSendRequest);
+ sendToLogoutPage(request, response, session);
return false;
}
- catch (Exception e)
+
+ //We got a response with the principal
+ List<String> roles = saml2HandlerResponse.getRoles();
+ 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()));
+
+ //Map to JBoss specific principal
+ if ((new ServerDetector()).isJboss() || jbossEnv)
{
- if (trace)
- log.trace("Exception:", e);
- throw new IOException("Server Error");
+ //Push a context
+ ServiceProviderSAMLContext.push(username, roles);
+ principal = context.getRealm().authenticate(username, password);
+ ServiceProviderSAMLContext.clear();
}
+ else
+ {
+ //tomcat env
+ principal = spUtil.createGenericPrincipal(request, username, roles);
+ }
+
+ session.setNote(Constants.SESS_USERNAME_NOTE, username);
+ session.setNote(Constants.SESS_PASSWORD_NOTE, password);
+ request.setUserPrincipal(principal);
+ //Get the original saved request
+ if (saveRestoreRequest)
+ {
+ this.restoreRequest(request, session);
+ }
+ register(request, response, principal, Constants.FORM_METHOD, username,
password);
+
+ return true;
}
}
-
- //Handle a SAML Response from IDP
- if (isNotNull(samlResponse))
+ catch (ProcessingException pe)
{
- boolean isValid = false;
- try
+ Throwable t = pe.getCause();
+ if (t != null && t instanceof AssertionExpiredException)
{
- isValid = this.validate(request);
+ log.error("Assertion has expired. Asking IDP for reissue");
+ //Just issue a fresh request back to IDP
+ return generalUserRequest(request, response, loginConfig);
}
- catch (Exception e)
- {
- log.error("Exception:", e);
- throw new IOException();
- }
- if (!isValid)
- throw new IOException("Validity check failed");
+ throw new IOException("Server Exception:" +
pe.getLocalizedMessage());
+ }
+ catch (Exception e)
+ {
+ log.error("Server Exception:", e);
+ throw new IOException("Server Exception");
+ }
+ return localAuthentication(request, response, loginConfig);
+ }
- //deal with SAML response from IDP
- try
- {
- ServiceProviderSAMLResponseProcessor responseProcessor = new
ServiceProviderSAMLResponseProcessor(true,
- serviceURL);
- responseProcessor.setValidateSignature(validateSignature);
- responseProcessor.setTrustKeyManager(keyManager);
+ /**
+ * Handle the user invocation for the first time
+ * @param request
+ * @param response
+ * @param loginConfig
+ * @return
+ * @throws IOException
+ */
+ protected boolean generalUserRequest(Request request, Response response, LoginConfig
loginConfig) throws IOException
+ {
+ Session session = request.getSessionInternal(true);
+ boolean willSendRequest = false;
+ HTTPContext httpContext = new HTTPContext(request, response,
context.getServletContext());
+ Set<SAML2Handler> handlers = chain.handlers();
- SAML2HandlerResponse saml2HandlerResponse =
responseProcessor.process(samlResponse, httpContext, handlers,
- chainLock);
+ String relayState = request.getParameter(GeneralConstants.RELAY_STATE);
- Document samlResponseDocument = saml2HandlerResponse.getResultingDocument();
- relayState = saml2HandlerResponse.getRelayState();
+ //Neither saml request nor response from IDP
+ //So this is a user request
+ SAML2HandlerResponse saml2HandlerResponse = null;
+ try
+ {
+ ServiceProviderBaseProcessor baseProcessor = new
ServiceProviderBaseProcessor(true, serviceURL);
+ if (issuerID != null)
+ baseProcessor.setIssuer(issuerID);
- String destination = saml2HandlerResponse.getDestination();
+ baseProcessor.setIdentityURL(identityURL);
- willSendRequest = saml2HandlerResponse.getSendRequest();
+ saml2HandlerResponse = baseProcessor.process(httpContext, handlers, chainLock);
+ }
+ catch (ProcessingException pe)
+ {
+ log.error("Processing Exception:", pe);
+ throw new RuntimeException(pe);
+ }
+ catch (ParsingException pe)
+ {
+ log.error("Parsing Exception:", pe);
+ throw new RuntimeException(pe);
+ }
+ catch (ConfigurationException pe)
+ {
+ log.error("Config Exception:", pe);
+ throw new RuntimeException(pe);
+ }
- if (destination != null && samlResponseDocument != null)
- {
- sendRequestToIDP(destination, samlResponseDocument, relayState, response,
willSendRequest);
- }
- else
- {
- //See if the session has been invalidated
+ willSendRequest = saml2HandlerResponse.getSendRequest();
- boolean sessionValidity = session.isValid();
- if (!sessionValidity)
- {
- sendToLogoutPage(request, response, session);
- return false;
- }
+ Document samlResponseDocument = saml2HandlerResponse.getResultingDocument();
+ relayState = saml2HandlerResponse.getRelayState();
- //We got a response with the principal
- List<String> roles = saml2HandlerResponse.getRoles();
- if (principal == null)
- principal = (Principal)
session.getSession().getAttribute(GeneralConstants.PRINCIPAL_ID);
+ String destination = saml2HandlerResponse.getDestination();
- String username = principal.getName();
- String password = ServiceProviderSAMLContext.EMPTY_PASSWORD;
- if (trace)
- log.trace("Roles determined for username=" + username +
"=" + Arrays.toString(roles.toArray()));
-
- //Map to JBoss specific principal
- if ((new ServerDetector()).isJboss() || jbossEnv)
- {
- //Push a context
- ServiceProviderSAMLContext.push(username, roles);
- principal = context.getRealm().authenticate(username, password);
- ServiceProviderSAMLContext.clear();
- }
- else
- {
- //tomcat env
- principal = spUtil.createGenericPrincipal(request, username, roles);
- }
-
- session.setNote(Constants.SESS_USERNAME_NOTE, username);
- session.setNote(Constants.SESS_PASSWORD_NOTE, password);
- request.setUserPrincipal(principal);
- //Get the original saved request
- if (saveRestoreRequest)
- {
- this.restoreRequest(request, session);
- }
- register(request, response, principal, Constants.FORM_METHOD, username,
password);
-
- return true;
- }
- }
- catch (Exception e)
- {
- log.error("Server Exception:", e);
- throw new IOException("Server Exception");
- }
- }
-
- //Handle SAML Requests from IDP
- if (isNotNull(samlRequest))
+ if (destination != null && samlResponseDocument != null)
{
try
{
- ServiceProviderSAMLRequestProcessor requestProcessor = new
ServiceProviderSAMLRequestProcessor(true,
- this.serviceURL);
- requestProcessor.setTrustKeyManager(keyManager);
- requestProcessor.setSupportSignatures(supportSignatures);
- boolean result = requestProcessor.process(samlRequest, httpContext, handlers,
chainLock);
-
- if (result)
- return result;
+ if (saveRestoreRequest)
+ {
+ this.saveRequest(request, session);
+ }
+ sendRequestToIDP(destination, samlResponseDocument, relayState, response,
willSendRequest);
+ return false;
}
catch (Exception e)
{
if (trace)
- log.trace("Server Exception:", e);
- throw new IOException("Server Exception");
+ log.trace("Exception:", e);
+ throw new IOException("Server Error");
}
- }//end if
+ }
- log.error("Did not find any SAML Request/Response. Falling back on local Form
Authentication if available");
- //fallback
- return super.authenticate(request, response, loginConfig);
+ return localAuthentication(request, response, loginConfig);
}
@Override
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-07-28
18:57:30 UTC (rev 1142)
+++
federation/trunk/picketlink-bindings/src/main/java/org/picketlink/identity/federation/bindings/tomcat/sp/SPRedirectFormAuthenticator.java 2011-07-28
21:38:57 UTC (rev 1143)
@@ -141,42 +141,120 @@
if (principal != null && !(logOutRequest || isNotNull(samlRequest) ||
isNotNull(samlResponse)))
return true;
+ //General User Request
+ if (!isNotNull(samlRequest) && !isNotNull(samlResponse))
+ {
+ return generalUserRequest(request, response, loginConfig);
+ }
+
+ //See if we got a response from IDP
+ if (isNotNull(samlResponse))
+ {
+ return handleSAMLResponse(request, response, loginConfig);
+ }
+
+ //Handle SAML Requests from IDP
+ if (isNotNull(samlRequest))
+ {
+ return handleSAMLRequest(request, response, loginConfig);
+ }//end if
+
+ return localAuthentication(request, response, loginConfig);
+ }
+
+ /**
+ * Handle the SAML Request message from IDP
+ * @param request
+ * @param response
+ * @param loginConfig
+ * @return
+ * @throws IOException
+ */
+ protected boolean handleSAMLRequest(Request request, Response response, LoginConfig
loginConfig) throws IOException
+ {
+ String samlRequest = request.getParameter(GeneralConstants.SAML_REQUEST_KEY);
+ HTTPContext httpContext = new HTTPContext(request, response,
context.getServletContext());
+
+ Set<SAML2Handler> handlers = chain.handlers();
+
+ //we got a logout request
+ try
+ {
+ ServiceProviderSAMLRequestProcessor requestProcessor = new
ServiceProviderSAMLRequestProcessor(false,
+ this.serviceURL);
+ boolean result = requestProcessor.process(samlRequest, httpContext, handlers,
chainLock);
+
+ if (result)
+ return result;
+ }
+ catch (Exception e)
+ {
+ log.error("Server Exception:", e);
+ throw new IOException("Server Exception");
+ }
+ return localAuthentication(request, response, loginConfig);
+ }
+
+ /**
+ * Handle the IDP Response
+ * @param request
+ * @param response
+ * @param loginConfig
+ * @return
+ * @throws IOException
+ */
+ protected boolean handleSAMLResponse(Request request, Response response, LoginConfig
loginConfig) throws IOException
+ {
+ Session session = request.getSessionInternal(true);
+
+ String samlResponse = request.getParameter(GeneralConstants.SAML_RESPONSE_KEY);
+
+ Principal principal = request.getUserPrincipal();
+
String relayState = request.getParameter(GeneralConstants.RELAY_STATE);
HTTPContext httpContext = new HTTPContext(request, response,
context.getServletContext());
Set<SAML2Handler> handlers = chain.handlers();
+ boolean isValid = false;
+ try
+ {
+ isValid = this.validate(request);
+ }
+ catch (Exception e)
+ {
+ log.error("Exception:", e);
+ throw new IOException();
+ }
+ if (!isValid)
+ throw new IOException("Validity check failed");
- //General User Request
- if (!isNotNull(samlRequest) && !isNotNull(samlResponse))
+ try
{
- //Neither saml request nor response from IDP
- //So this is a user request
+ ServiceProviderSAMLResponseProcessor responseProcessor = new
ServiceProviderSAMLResponseProcessor(false,
+ serviceURL);
+ initializeSAMLProcessor(responseProcessor);
+
SAML2HandlerResponse saml2HandlerResponse = null;
+
try
{
- ServiceProviderBaseProcessor baseProcessor = new
ServiceProviderBaseProcessor(false, serviceURL);
-
- initializeSAMLProcessor(baseProcessor);
-
- saml2HandlerResponse = baseProcessor.process(httpContext, handlers,
chainLock);
- saml2HandlerResponse.setDestination(identityURL);
+ saml2HandlerResponse = responseProcessor.process(samlResponse, httpContext,
handlers, chainLock);
}
catch (ProcessingException pe)
{
- log.error("Processing Exception:", pe);
- throw new RuntimeException(pe);
+ Throwable te = pe.getCause();
+ 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);
+ }
+ else
+ throw pe;
}
- catch (ParsingException pe)
- {
- log.error("Parsing Exception:", pe);
- throw new RuntimeException(pe);
- }
- catch (ConfigurationException pe)
- {
- log.error("Config Exception:", pe);
- throw new RuntimeException(pe);
- }
-
Document samlResponseDocument = saml2HandlerResponse.getResultingDocument();
relayState = saml2HandlerResponse.getRelayState();
@@ -184,188 +262,175 @@
if (destination != null && samlResponseDocument != null)
{
- try
- {
- String samlMsg = DocumentUtil.getDocumentAsString(samlResponseDocument);
- if (trace)
- log.trace("SAML Document=" + samlMsg);
+ boolean areWeSendingRequest = saml2HandlerResponse.getSendRequest();
+ String samlMsg = DocumentUtil.getDocumentAsString(samlResponseDocument);
- boolean areWeSendingRequest = saml2HandlerResponse.getSendRequest();
+ String base64Request =
RedirectBindingUtil.deflateBase64URLEncode(samlMsg.getBytes("UTF-8"));
- String base64Request =
RedirectBindingUtil.deflateBase64URLEncode(samlMsg.getBytes("UTF-8"));
+ String destinationQuery = getDestinationQueryString(base64Request,
relayState, areWeSendingRequest);
- String destinationQuery = getDestinationQueryString(base64Request,
relayState, areWeSendingRequest);
+ RedirectBindingUtilDestHolder holder = new RedirectBindingUtilDestHolder();
+
holder.setDestination(destination).setDestinationQueryString(destinationQuery);
- RedirectBindingUtilDestHolder holder = new
RedirectBindingUtilDestHolder();
-
holder.setDestination(destination).setDestinationQueryString(destinationQuery);
+ String destinationURL = RedirectBindingUtil.getDestinationURL(holder);
- String destinationURL = RedirectBindingUtil.getDestinationURL(holder);
+ HTTPRedirectUtil.sendRedirectForRequestor(destinationURL, response);
+ }
+ else
+ {
+ //See if the session has been invalidated
+ boolean sessionValidity = session.isValid();
+ if (!sessionValidity)
+ {
+ sendToLogoutPage(request, response, session);
+ return false;
+ }
- if (trace)
- {
- log.trace("URL used for sending:" + destinationURL);
- }
+ //We got a response with the principal
+ List<String> roles = saml2HandlerResponse.getRoles();
+ if (principal == null)
+ principal = (Principal)
session.getSession().getAttribute(GeneralConstants.PRINCIPAL_ID);
- if (saveRestoreRequest)
- {
- this.saveRequest(request, session);
- }
+ String username = principal.getName();
+ String password = ServiceProviderSAMLContext.EMPTY_PASSWORD;
- HTTPRedirectUtil.sendRedirectForRequestor(destinationURL, response);
- return false;
+ //Map to JBoss specific principal
+ if ((new ServerDetector()).isJboss() || jbossEnv)
+ {
+ //Push a context
+ ServiceProviderSAMLContext.push(username, roles);
+ principal = context.getRealm().authenticate(username, password);
+ ServiceProviderSAMLContext.clear();
}
- catch (Exception e)
+ else
{
- if (trace)
- log.trace("Exception:", e);
- throw new IOException("Server Error");
+ //tomcat env
+ SPUtil spUtil = new SPUtil();
+ principal = spUtil.createGenericPrincipal(request, principal.getName(),
roles);
}
+
+ session.setNote(Constants.SESS_USERNAME_NOTE, username);
+ session.setNote(Constants.SESS_PASSWORD_NOTE, password);
+ request.setUserPrincipal(principal);
+
+ if (saveRestoreRequest)
+ {
+ this.restoreRequest(request, session);
+ }
+ register(request, response, principal, Constants.FORM_METHOD, username,
password);
+
+ return true;
}
}
-
- //See if we got a response from IDP
- if (isNotNull(samlResponse))
+ catch (ProcessingException pe)
{
- boolean isValid = false;
- try
+ Throwable t = pe.getCause();
+ if (t != null && t instanceof AssertionExpiredException)
{
- isValid = this.validate(request);
+ log.error("Assertion has expired. Asking IDP for reissue");
+ //Just issue a fresh request back to IDP
+ return generalUserRequest(request, response, loginConfig);
}
- catch (Exception e)
- {
- log.error("Exception:", e);
- throw new IOException();
- }
- if (!isValid)
- throw new IOException("Validity check failed");
+ throw new IOException("Server Exception:" +
pe.getLocalizedMessage());
+ }
+ catch (Exception e)
+ {
+ if (trace)
+ log.trace("Server Exception:", e);
+ throw new IOException("Server Exception:" + e.getLocalizedMessage());
+ }
+ return localAuthentication(request, response, loginConfig);
+ }
- try
- {
- ServiceProviderSAMLResponseProcessor responseProcessor = new
ServiceProviderSAMLResponseProcessor(false,
- serviceURL);
- initializeSAMLProcessor(responseProcessor);
+ /**
+ * Handle the user invocation for the first time
+ * @param request
+ * @param response
+ * @param loginConfig
+ * @return
+ * @throws IOException
+ */
+ protected boolean generalUserRequest(Request request, Response response, LoginConfig
loginConfig) throws IOException
+ {
+ Session session = request.getSessionInternal(true);
+ HTTPContext httpContext = new HTTPContext(request, response,
context.getServletContext());
+ Set<SAML2Handler> handlers = chain.handlers();
- SAML2HandlerResponse saml2HandlerResponse = null;
+ String relayState = request.getParameter(GeneralConstants.RELAY_STATE);
- try
- {
- saml2HandlerResponse = responseProcessor.process(samlResponse,
httpContext, handlers, chainLock);
- }
- catch (ProcessingException pe)
- {
- Throwable te = pe.getCause();
- if (te instanceof AssertionExpiredException)
- {
- //We need to reissue redirect to IDP
- ServiceProviderBaseProcessor baseProcessor = new
ServiceProviderBaseProcessor(false, serviceURL);
- initializeSAMLProcessor(baseProcessor);
+ //Neither saml request nor response from IDP
+ //So this is a user request
+ SAML2HandlerResponse saml2HandlerResponse = null;
+ try
+ {
+ ServiceProviderBaseProcessor baseProcessor = new
ServiceProviderBaseProcessor(false, serviceURL);
- saml2HandlerResponse = baseProcessor.process(httpContext, handlers,
chainLock);
- saml2HandlerResponse.setDestination(identityURL);
- }
- else
- throw pe;
- }
- Document samlResponseDocument = saml2HandlerResponse.getResultingDocument();
- relayState = saml2HandlerResponse.getRelayState();
+ initializeSAMLProcessor(baseProcessor);
- String destination = saml2HandlerResponse.getDestination();
+ saml2HandlerResponse = baseProcessor.process(httpContext, handlers, chainLock);
+ saml2HandlerResponse.setDestination(identityURL);
+ }
+ catch (ProcessingException pe)
+ {
+ log.error("Processing Exception:", pe);
+ throw new RuntimeException(pe);
+ }
+ catch (ParsingException pe)
+ {
+ log.error("Parsing Exception:", pe);
+ throw new RuntimeException(pe);
+ }
+ catch (ConfigurationException pe)
+ {
+ log.error("Config Exception:", pe);
+ throw new RuntimeException(pe);
+ }
- if (destination != null && samlResponseDocument != null)
- {
- boolean areWeSendingRequest = saml2HandlerResponse.getSendRequest();
- String samlMsg = DocumentUtil.getDocumentAsString(samlResponseDocument);
+ Document samlResponseDocument = saml2HandlerResponse.getResultingDocument();
+ relayState = saml2HandlerResponse.getRelayState();
- String base64Request =
RedirectBindingUtil.deflateBase64URLEncode(samlMsg.getBytes("UTF-8"));
+ String destination = saml2HandlerResponse.getDestination();
- String destinationQuery = getDestinationQueryString(base64Request,
relayState, areWeSendingRequest);
+ if (destination != null && samlResponseDocument != null)
+ {
+ try
+ {
+ String samlMsg = DocumentUtil.getDocumentAsString(samlResponseDocument);
+ if (trace)
+ log.trace("SAML Document=" + samlMsg);
- RedirectBindingUtilDestHolder holder = new
RedirectBindingUtilDestHolder();
-
holder.setDestination(destination).setDestinationQueryString(destinationQuery);
+ boolean areWeSendingRequest = saml2HandlerResponse.getSendRequest();
- String destinationURL = RedirectBindingUtil.getDestinationURL(holder);
+ String base64Request =
RedirectBindingUtil.deflateBase64URLEncode(samlMsg.getBytes("UTF-8"));
- HTTPRedirectUtil.sendRedirectForRequestor(destinationURL, response);
- }
- else
- {
- //See if the session has been invalidated
- boolean sessionValidity = session.isValid();
- if (!sessionValidity)
- {
- sendToLogoutPage(request, response, session);
- return false;
- }
+ String destinationQuery = getDestinationQueryString(base64Request,
relayState, areWeSendingRequest);
- //We got a response with the principal
- List<String> roles = saml2HandlerResponse.getRoles();
- if (principal == null)
- principal = (Principal)
session.getSession().getAttribute(GeneralConstants.PRINCIPAL_ID);
+ RedirectBindingUtilDestHolder holder = new RedirectBindingUtilDestHolder();
+
holder.setDestination(destination).setDestinationQueryString(destinationQuery);
- String username = principal.getName();
- String password = ServiceProviderSAMLContext.EMPTY_PASSWORD;
+ String destinationURL = RedirectBindingUtil.getDestinationURL(holder);
- //Map to JBoss specific principal
- if ((new ServerDetector()).isJboss() || jbossEnv)
- {
- //Push a context
- ServiceProviderSAMLContext.push(username, roles);
- principal = context.getRealm().authenticate(username, password);
- ServiceProviderSAMLContext.clear();
- }
- else
- {
- //tomcat env
- SPUtil spUtil = new SPUtil();
- principal = spUtil.createGenericPrincipal(request, principal.getName(),
roles);
- }
+ if (trace)
+ {
+ log.trace("URL used for sending:" + destinationURL);
+ }
- session.setNote(Constants.SESS_USERNAME_NOTE, username);
- session.setNote(Constants.SESS_PASSWORD_NOTE, password);
- request.setUserPrincipal(principal);
+ if (saveRestoreRequest)
+ {
+ this.saveRequest(request, session);
+ }
- if (saveRestoreRequest)
- {
- this.restoreRequest(request, session);
- }
- register(request, response, principal, Constants.FORM_METHOD, username,
password);
-
- return true;
- }
+ HTTPRedirectUtil.sendRedirectForRequestor(destinationURL, response);
+ return false;
}
catch (Exception e)
{
- e.printStackTrace();
if (trace)
- log.trace("Server Exception:", e);
- throw new IOException("Server Exception:" +
e.getLocalizedMessage());
+ log.trace("Exception:", e);
+ throw new IOException("Server Error");
}
}
-
- //Handle SAML Requests from IDP
- if (isNotNull(samlRequest))
- {
- //we got a logout request
- try
- {
- ServiceProviderSAMLRequestProcessor requestProcessor = new
ServiceProviderSAMLRequestProcessor(false,
- this.serviceURL);
- boolean result = requestProcessor.process(samlRequest, httpContext, handlers,
chainLock);
-
- if (result)
- return result;
- }
- catch (Exception e)
- {
- log.error("Server Exception:", e);
- throw new IOException("Server Exception");
- }
-
- }//end if
-
- log.error("Did not find any SAML Request/Response. Falling back on local Form
Authentication if available");
- //fallback
- return super.authenticate(request, response, loginConfig);
+ return localAuthentication(request, response, loginConfig);
}
protected String createSAMLRequestMessage(String relayState, Response response) throws
ServletException,