SAMLAssertion getSAMLAssertionFromACSResponse(HttpServletRequest request) {
    String securityTokenResponse = request.getParameter("wresult");
    Utils.logDebug("wsresult in the response from ACS is " + securityTokenResponse, LOG);

    if (securityTokenResponse == null) {
      return null;
    }

    // None of Java XML objects are thread-safe. Better to create instance on demand rather than
    // caching.
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setNamespaceAware(true); // very important, must
    DocumentBuilder docBuilder;
    SAMLAssertion assertion = null;

    try {
      docBuilder = docBuilderFactory.newDocumentBuilder();
      Document respDoc =
          docBuilder.parse(new ByteArrayInputStream(Utils.getUTF8Bytes(securityTokenResponse)));
      // Find the response token
      Element responseToken =
          (Element)
              respDoc
                  .getDocumentElement()
                  .getElementsByTagNameNS(
                      "http://schemas.xmlsoap.org/ws/2005/02/trust", "RequestedSecurityToken")
                  .item(0);
      assertion = SAMLAssertion.getAssertionFromSecurityToken(responseToken);
    } catch (Exception e) {
      Utils.logError("Exception while parsing the security token response from ACS.", e, LOG);
    }
    return assertion;
  }
 void invokeChainWithRemoteUser(
     FilterChain chain,
     HttpServletRequest httpRequest,
     HttpServletResponse httpResponse,
     SAMLAssertion assertion)
     throws IOException, ServletException {
   // set assertion as an attribute in the request
   try {
     httpRequest.setAttribute(
         ACS_SAML, Utils.getXMLStringFromNode(assertion.getAssertionXMLElement()));
   } catch (Exception e) {
     Utils.logError("Invalid Saml Content.", e, LOG);
     throw new ServletException("Invalid SAML Content");
   }
   String remoteUser = getUserFromAssertion(assertion);
   invokeChainWithRemoteUser(chain, httpRequest, httpResponse, remoteUser);
 }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    Utils.logDebug("In the doFilter method..", LOG);

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    this.filterCommand.execute(httpRequest, httpResponse, chain);
  }
 protected void invokeChainWithRemoteUser(
     FilterChain chain,
     HttpServletRequest httpRequest,
     HttpServletResponse httpResponse,
     String remoteUser)
     throws IOException, ServletException {
   Utils.logDebug("Invoking the request with remote user : " + remoteUser, LOG);
   HttpServletRequest httpRequestWithRemoteUser =
       setRemoteUserInServletRequest(httpRequest, remoteUser);
   chain.doFilter(httpRequestWithRemoteUser, httpResponse);
 }
 protected void invokeChainWithRemoteUserAndOldRequest(
     FilterChain chain,
     HttpServletRequest httpRequest,
     HttpServletResponse httpResponse,
     String remoteUser,
     HttpServletRequestDetails requestDetails)
     throws IOException, ServletException {
   Utils.logDebug(
       String.format(
           "Invoking the request with remote user: %s and the details of the request that caused a redirect to ACS",
           remoteUser),
       LOG);
   HttpServletRequest httpRequestWithRemoteUser =
       setRemoteUserAndOldRequestDetailsInServletRequest(httpRequest, remoteUser, requestDetails);
   chain.doFilter(httpRequestWithRemoteUser, httpResponse);
 }
  public void init(FilterConfig filterConfig) throws ServletException {
    Utils.logDebug("Initializing the filter..", LOG);

    passiveRequestorEndPoint = filterConfig.getInitParameter(PASSIVE_REQUESTOR_ENDPOINT);
    Utils.logInfo("Passive Requestor Endpoint is:" + passiveRequestorEndPoint, LOG);
    if (passiveRequestorEndPoint == null) {
      throw new ServletException(
          PASSIVE_REQUESTOR_ENDPOINT + " init parameter not proivded in the filter configuration.");
    }
    // Remove query parameters if any
    passiveRequestorEndPoint =
        (passiveRequestorEndPoint != null && passiveRequestorEndPoint.indexOf('?') > 0)
            ? passiveRequestorEndPoint.substring(0, passiveRequestorEndPoint.indexOf('?'))
            : passiveRequestorEndPoint;

    relyingPartyRealm = filterConfig.getInitParameter(RELYING_PARTY_REALM);
    Utils.logInfo("Relying Party Realm is:" + relyingPartyRealm, LOG);
    if (relyingPartyRealm == null) {
      throw new ServletException(
          RELYING_PARTY_REALM + " init parameter not proivded in the filter configuration.");
    }

    certificatePath = filterConfig.getInitParameter(CERTIFICATE_PATH);
    Utils.logInfo("Certificate path:" + certificatePath, LOG);
    if (certificatePath == null) {
      // 1. check for embedded cert and if exists set certPath to cert/acs_signing.cer
      if (filterConfig.getServletContext().getResourceAsStream(EMBEDDED_CERT_LOC) != null)
        certificatePath = EMBEDDED_CERT_LOC;
      else
        throw new ServletException(
            CERTIFICATE_PATH
                + " init parameter not proivded in the filter configuration"
                + " or Embeddded Cert is not found at /WEB-INF/cert/_acs_signing.cer");
    }

    secretKey = filterConfig.getInitParameter(SECRET_KEY);
    if (secretKey == null) {
      throw new ServletException(
          SECRET_KEY + " init parameter not proivded in the filter configuration.");
    }

    allowHttp = Boolean.parseBoolean(filterConfig.getInitParameter(ALLOW_HTTP));

    // create keystore
    Key publicKey = getPublicKey(certificatePath, filterConfig);
    trustParams =
        new TrustParameters(publicKey, Utils.getSecretKey(secretKey), allowHttp, relyingPartyRealm);

    // Create the command which performs actual filtering
    Utils.logDebug("Creating stateless filter...", LOG);
    filterCommand = new StatelessFilterCommand(this);
  }
  private String getUserFromAssertion(SAMLAssertion assertion) {
    String user = null;
    // Check name claim attribute. If exists set as remote user else use NameID
    SAMLAssertion.Attribute[] attributes = assertion.getAttributes();
    for (SAMLAssertion.Attribute attribute : attributes) {
      if (attribute.getName().endsWith("claims/name")) {
        user = attribute.getValues()[0];
        break;
      }
    }

    if (user == null) {
      Utils.logDebug(
          "No name claim found in the assertion, so assuming subject's name identifier as the remote user.",
          LOG);
      user = assertion.getSubject().getNameIdentifier();
    }
    return user;
  }