Package org.jboss.identity.federation.bindings.tomcat.sp

Source Code of org.jboss.identity.federation.bindings.tomcat.sp.SPRedirectFormAuthenticator

/*
* 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.jboss.identity.federation.bindings.tomcat.sp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.Principal;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.xml.bind.JAXBException;

import org.apache.catalina.Session;
import org.apache.catalina.authenticator.Constants;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.deploy.LoginConfig;
import org.apache.catalina.realm.GenericPrincipal;
import org.apache.log4j.Logger;
import org.jboss.identity.federation.api.saml.v2.request.SAML2Request;
import org.jboss.identity.federation.api.saml.v2.response.SAML2Response;
import org.jboss.identity.federation.api.util.Base64;
import org.jboss.identity.federation.api.util.DeflateUtil;
import org.jboss.identity.federation.bindings.config.TrustType;
import org.jboss.identity.federation.bindings.tomcat.sp.holder.ServiceProviderSAMLContext;
import org.jboss.identity.federation.bindings.util.HTTPRedirectUtil;
import org.jboss.identity.federation.bindings.util.RedirectBindingUtil;
import org.jboss.identity.federation.bindings.util.ValveUtil;
import org.jboss.identity.federation.core.exceptions.ConfigurationException;
import org.jboss.identity.federation.core.exceptions.ParsingException;
import org.jboss.identity.federation.core.saml.v2.exceptions.AssertionExpiredException;
import org.jboss.identity.federation.core.saml.v2.exceptions.IssuerNotTrustedException;
import org.jboss.identity.federation.saml.v2.assertion.EncryptedElementType;
import org.jboss.identity.federation.saml.v2.protocol.AuthnRequestType;
import org.jboss.identity.federation.saml.v2.protocol.ResponseType;
import org.xml.sax.SAXException;

/**
* Authenticator at the Service Provider
* that handles HTTP/Redirect binding of SAML 2
* but falls back on Form Authentication
*
* @author Anil.Saldhana@redhat.com
* @since Dec 12, 2008
*/
public class SPRedirectFormAuthenticator extends BaseFormAuthenticator
{
   private static Logger log = Logger.getLogger(SPRedirectFormAuthenticator.class);
  
   public SPRedirectFormAuthenticator()
   {
      super();
   }

   @Override
   public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
   {
      Principal principal = request.getUserPrincipal();
      if (principal != null)
      {
         log.debug("Already authenticated '" + principal.getName() + "'");
         return true;
      }

      Session session = request.getSessionInternal(true);
      String relayState = request.getParameter("RelayState");

      //Try to get the username
      try
      {
         principal = (GenericPrincipal) process(request,response);
        
         if(principal == null)
         {
            String destination = createSAMLRequestMessage( relayState, response)
            HTTPRedirectUtil.sendRedirectForRequestor(destination, response);
           
            return false;
         }
        
         String username = principal.getName();
         String password = ServiceProviderSAMLContext.EMPTY_PASSWORD;
        
         //Map to JBoss specific principal
         if(spConfiguration.getServerEnvironment().equalsIgnoreCase("JBOSS"))
         {
            GenericPrincipal gp = (GenericPrincipal) principal;
            //Push a context
            ServiceProviderSAMLContext.push(username, Arrays.asList(gp.getRoles()));
            principal = context.getRealm().authenticate(username, password);
            ServiceProviderSAMLContext.clear();
        
        
         session.setNote(Constants.SESS_USERNAME_NOTE, username);
         session.setNote(Constants.SESS_PASSWORD_NOTE, password);
         request.setUserPrincipal(principal);
         register(request, response, principal, Constants.FORM_METHOD, username, password);
        
         return true;
      }
      catch(AssertionExpiredException aie)
      {
         log.debug("Assertion has expired. Issuing a new saml2 request to the IDP");
         try
         {
            String destination = createSAMLRequestMessage( relayState, response)
            HTTPRedirectUtil.sendRedirectForRequestor(destination, response);
         }
         catch (Exception e)
         {
            log.trace("Exception:",e);
         }
         return false;
      }
      catch(Exception e)
      {
         log.debug("Exception :",e);
      }

      //fallback
      return super.authenticate(request, response, loginConfig);
   }

   protected String createSAMLRequestMessage(String relayState, Response response)
   throws ServletException, ConfigurationException, SAXException, JAXBException, IOException
   {
      //create a saml request
      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() + getDestination(base64Request, relayState);
      log.debug("Sending to destination="+destination);
        
      return destination;
   }
  
   protected String getDestination(String urlEncodedRequest, String urlEncodedRelayState)
   {
      StringBuilder sb = new StringBuilder();
      sb.append("?SAMLRequest=").append(urlEncodedRequest);
      if(urlEncodedRelayState != null && urlEncodedRelayState.length() > 0)
         sb.append("&RelayState=").append(urlEncodedRelayState);
      return sb.toString();
   }
  
   protected void isTrusted(String issuer) throws IssuerNotTrustedException
   {
      try
      {
         String issuerDomain = ValveUtil.getDomain(issuer);
         TrustType spTrust =  spConfiguration.getTrust();
         if(spTrust != null)
         {
            String domainsTrusted = spTrust.getDomains();
            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())
               {
                  String uriBit = st.nextToken();
                  log.trace("Matching uri bit="+ uriBit);
                  if(issuerDomain.indexOf(uriBit) > 0)
                  {
                     log.trace("Matched " + uriBit + " trust for " + issuerDomain );
                     return;
                  }
               }
               throw new IssuerNotTrustedException(issuer);
            }
         }
      }
      catch (Exception e)
      {
         throw new IssuerNotTrustedException(e.getLocalizedMessage(),e);
      }
   }
  
   /**
    * 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
   {
      throw new RuntimeException("This authenticator does not handle encryption");
   }
   private Principal process(Request request, Response response)
   throws IOException, GeneralSecurityException,
   ConfigurationException, ParsingException
   {
      Principal userPrincipal = null;

      String samlResponse = request.getParameter("SAMLResponse");
      if(samlResponse != null && samlResponse.length() > 0 )
      {
         boolean isValid = this.validate(request);
        
         if(!isValid)
            throw new GeneralSecurityException("Validity Checks failed");
        
         //deal with SAML response from IDP
         byte[] base64DecodedResponse = Base64.decode(samlResponse);
         InputStream is = DeflateUtil.decode(base64DecodedResponse);

         SAML2Response saml2Response = new SAML2Response();
        
         ResponseType responseType;
         try
         {
            responseType = saml2Response.getResponseType(is);
         }
         catch (JAXBException e)
         {
            throw new ParsingException(e);
         }
         catch (SAXException e)
         {
            throw new ParsingException(e);
         }
                 
         this.isTrusted(responseType.getIssuer().getValue());
        
         List<Object> assertions = responseType.getAssertionOrEncryptedAssertion();
         if(assertions.size() == 0)
            throw new IllegalStateException("No assertions in reply from IDP");
        
         Object assertion = assertions.get(0);
         if(assertion instanceof EncryptedElementType)
         {
            responseType = this.decryptAssertion(responseType);
         }
        
         SPUtil spUtil = new SPUtil();
         return spUtil.handleSAMLResponse(request, responseType);
      }
      return userPrincipal;
   }
}
TOP

Related Classes of org.jboss.identity.federation.bindings.tomcat.sp.SPRedirectFormAuthenticator

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.