private void validateSamlSignature(
     SAMLDocumentHolder holder, boolean postBinding, String paramKey)
     throws VerificationException {
   if (postBinding) {
     verifyPostBindingSignature(
         holder.getSamlDocument(), deployment.getIDP().getSignatureValidationKey());
   } else {
     verifyRedirectBindingSignature(deployment.getIDP().getSignatureValidationKey(), paramKey);
   }
 }
 protected boolean verifySSL() {
   if (!facade.getRequest().isSecure()
       && deployment.getSslRequired().isRequired(facade.getRequest().getRemoteAddr())) {
     log.warn("SSL is required to authenticate");
     return true;
   }
   return false;
 }
  protected void forwardToLogoutPage(
      Request request, HttpServletResponse response, SamlDeployment deployment) {
    RequestDispatcher disp = request.getRequestDispatcher(deployment.getLogoutPage());
    // make sure the login page is never cached
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "0");

    try {
      disp.forward(request, response);
    } catch (ServletException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  protected AuthOutcome handleSamlRequest(String samlRequest, String relayState) {
    SAMLDocumentHolder holder = null;
    boolean postBinding = false;
    String requestUri = facade.getRequest().getURI();
    if (facade.getRequest().getMethod().equalsIgnoreCase("GET")) {
      // strip out query params
      int index = requestUri.indexOf('?');
      if (index > -1) {
        requestUri = requestUri.substring(0, index);
      }
      holder = SAMLRequestParser.parseRequestRedirectBinding(samlRequest);
    } else {
      postBinding = true;
      holder = SAMLRequestParser.parseRequestPostBinding(samlRequest);
    }
    RequestAbstractType requestAbstractType = (RequestAbstractType) holder.getSamlObject();
    if (!requestUri.equals(requestAbstractType.getDestination().toString())) {
      log.error(
          "expected destination '"
              + requestUri
              + "' got '"
              + requestAbstractType.getDestination()
              + "'");
      return AuthOutcome.FAILED;
    }

    if (requestAbstractType instanceof LogoutRequestType) {
      if (deployment.getIDP().getSingleLogoutService().validateRequestSignature()) {
        try {
          validateSamlSignature(holder, postBinding, GeneralConstants.SAML_REQUEST_KEY);
        } catch (VerificationException e) {
          log.error("Failed to verify saml request signature", e);
          return AuthOutcome.FAILED;
        }
      }
      LogoutRequestType logout = (LogoutRequestType) requestAbstractType;
      return logoutRequest(logout, relayState);

    } else {
      log.error("unknown SAML request type");
      return AuthOutcome.FAILED;
    }
  }
  @Override
  public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory)
      throws ServerAuthException {
    if (log.isTraceEnabled()) {
      log.trace("*** authenticate");
    }
    Request request = resolveRequest(req);
    JettyHttpFacade facade = new JettyHttpFacade(request, (HttpServletResponse) res);
    SamlDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (deployment == null || !deployment.isConfigured()) {
      log.debug("*** deployment isn't configured return false");
      return Authentication.UNAUTHENTICATED;
    }
    boolean isEndpoint =
        request.getRequestURI().substring(request.getContextPath().length()).endsWith("/saml");
    if (!mandatory && !isEndpoint) return new DeferredAuthentication(this);
    JettySamlSessionStore tokenStore = getTokenStore(request, facade, deployment);

    SamlAuthenticator authenticator = null;
    if (isEndpoint) {
      authenticator =
          new SamlAuthenticator(facade, deployment, tokenStore) {
            @Override
            protected void completeAuthentication(SamlSession account) {}

            @Override
            protected SamlAuthenticationHandler createBrowserHandler(
                HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) {
              return new SamlEndpoint(facade, deployment, sessionStore);
            }
          };

    } else {
      authenticator =
          new SamlAuthenticator(facade, deployment, tokenStore) {
            @Override
            protected void completeAuthentication(SamlSession account) {}

            @Override
            protected SamlAuthenticationHandler createBrowserHandler(
                HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) {
              return new BrowserHandler(facade, deployment, sessionStore);
            }
          };
    }
    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
      if (facade.isEnded()) {
        return Authentication.SEND_SUCCESS;
      }
      SamlSession samlSession = tokenStore.getAccount();
      Authentication authentication = register(request, samlSession);
      return authentication;
    }
    if (outcome == AuthOutcome.LOGGED_OUT) {
      logoutCurrent(request);
      if (deployment.getLogoutPage() != null) {
        forwardToLogoutPage(request, (HttpServletResponse) res, deployment);
      }
      return Authentication.SEND_CONTINUE;
    }

    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
      challenge.challenge(facade);
    }
    return Authentication.SEND_CONTINUE;
  }
 protected boolean isRole(AttributeType attribute) {
   return (attribute.getName() != null
           && deployment.getRoleAttributeNames().contains(attribute.getName()))
       || (attribute.getFriendlyName() != null
           && deployment.getRoleAttributeNames().contains(attribute.getFriendlyName()));
 }
  protected AuthOutcome handleLoginResponse(
      ResponseType responseType, OnSessionCreated onCreateSession) {

    AssertionType assertion = null;
    try {
      assertion = AssertionUtil.getAssertion(responseType, deployment.getDecryptionKey());
      if (AssertionUtil.hasExpired(assertion)) {
        return initiateLogin();
      }
    } catch (Exception e) {
      log.error("Error extracting SAML assertion: " + e.getMessage());
      challenge =
          new AuthChallenge() {
            @Override
            public boolean challenge(HttpFacade exchange) {
              SamlAuthenticationError error =
                  new SamlAuthenticationError(SamlAuthenticationError.Reason.EXTRACTION_FAILURE);
              exchange.getRequest().setError(error);
              exchange.getResponse().sendError(403);
              return true;
            }

            @Override
            public int getResponseCode() {
              return 403;
            }
          };
    }

    SubjectType subject = assertion.getSubject();
    SubjectType.STSubType subType = subject.getSubType();
    NameIDType subjectNameID = (NameIDType) subType.getBaseID();
    String principalName = subjectNameID.getValue();

    final Set<String> roles = new HashSet<>();
    MultivaluedHashMap<String, String> attributes = new MultivaluedHashMap<>();
    MultivaluedHashMap<String, String> friendlyAttributes = new MultivaluedHashMap<>();

    Set<StatementAbstractType> statements = assertion.getStatements();
    for (StatementAbstractType statement : statements) {
      if (statement instanceof AttributeStatementType) {
        AttributeStatementType attributeStatement = (AttributeStatementType) statement;
        List<AttributeStatementType.ASTChoiceType> attList = attributeStatement.getAttributes();
        for (AttributeStatementType.ASTChoiceType obj : attList) {
          AttributeType attr = obj.getAttribute();
          if (isRole(attr)) {
            List<Object> attributeValues = attr.getAttributeValue();
            if (attributeValues != null) {
              for (Object attrValue : attributeValues) {
                String role = getAttributeValue(attrValue);
                log.debugv("Add role: {0}", role);
                roles.add(role);
              }
            }
          } else {
            List<Object> attributeValues = attr.getAttributeValue();
            if (attributeValues != null) {
              for (Object attrValue : attributeValues) {
                String value = getAttributeValue(attrValue);
                if (attr.getName() != null) {
                  attributes.add(attr.getName(), value);
                }
                if (attr.getFriendlyName() != null) {
                  friendlyAttributes.add(attr.getFriendlyName(), value);
                }
              }
            }
          }
        }
      }
    }
    if (deployment.getPrincipalNamePolicy() == SamlDeployment.PrincipalNamePolicy.FROM_ATTRIBUTE) {
      if (deployment.getPrincipalAttributeName() != null) {
        String attribute = attributes.getFirst(deployment.getPrincipalAttributeName());
        if (attribute != null) principalName = attribute;
        else {
          attribute = friendlyAttributes.getFirst(deployment.getPrincipalAttributeName());
          if (attribute != null) principalName = attribute;
        }
      }
    }

    AuthnStatementType authn = null;
    for (Object statement : assertion.getStatements()) {
      if (statement instanceof AuthnStatementType) {
        authn = (AuthnStatementType) statement;
        break;
      }
    }

    URI nameFormat = subjectNameID.getFormat();
    String nameFormatString =
        nameFormat == null
            ? JBossSAMLURIConstants.NAMEID_FORMAT_UNSPECIFIED.get()
            : nameFormat.toString();
    final SamlPrincipal principal =
        new SamlPrincipal(
            assertion,
            principalName,
            principalName,
            nameFormatString,
            attributes,
            friendlyAttributes);
    String index = authn == null ? null : authn.getSessionIndex();
    final String sessionIndex = index;
    SamlSession account = new SamlSession(principal, roles, sessionIndex);
    sessionStore.saveAccount(account);
    onCreateSession.onSessionCreated(account);

    // redirect to original request, it will be restored
    String redirectUri = sessionStore.getRedirectUri();
    if (redirectUri != null) {
      facade.getResponse().setHeader("Location", redirectUri);
      facade.getResponse().setStatus(302);
      facade.getResponse().end();
    } else {
      log.debug("IDP initiated invocation");
    }
    log.debug("AUTHENTICATED authn");

    return AuthOutcome.AUTHENTICATED;
  }
  protected AuthOutcome handleSamlResponse(
      String samlResponse, String relayState, OnSessionCreated onCreateSession) {
    SAMLDocumentHolder holder = null;
    boolean postBinding = false;
    String requestUri = facade.getRequest().getURI();
    if (facade.getRequest().getMethod().equalsIgnoreCase("GET")) {
      int index = requestUri.indexOf('?');
      if (index > -1) {
        requestUri = requestUri.substring(0, index);
      }
      holder = extractRedirectBindingResponse(samlResponse);
    } else {
      postBinding = true;
      holder = extractPostBindingResponse(samlResponse);
    }
    final StatusResponseType statusResponse = (StatusResponseType) holder.getSamlObject();
    // validate destination
    if (!requestUri.equals(statusResponse.getDestination())) {
      log.error("Request URI does not match SAML request destination");
      return AuthOutcome.FAILED;
    }

    if (statusResponse instanceof ResponseType) {
      try {
        if (deployment.getIDP().getSingleSignOnService().validateResponseSignature()) {
          try {
            validateSamlSignature(holder, postBinding, GeneralConstants.SAML_RESPONSE_KEY);
          } catch (VerificationException e) {
            log.error("Failed to verify saml response signature", e);

            challenge =
                new AuthChallenge() {
                  @Override
                  public boolean challenge(HttpFacade exchange) {
                    SamlAuthenticationError error =
                        new SamlAuthenticationError(
                            SamlAuthenticationError.Reason.INVALID_SIGNATURE);
                    exchange.getRequest().setError(error);
                    exchange.getResponse().sendError(403);
                    return true;
                  }

                  @Override
                  public int getResponseCode() {
                    return 403;
                  }
                };
            return AuthOutcome.FAILED;
          }
        }
        return handleLoginResponse((ResponseType) statusResponse, onCreateSession);
      } finally {
        sessionStore.setCurrentAction(SamlSessionStore.CurrentAction.NONE);
      }

    } else {
      if (sessionStore.isLoggingOut()) {
        try {
          if (deployment.getIDP().getSingleLogoutService().validateResponseSignature()) {
            try {
              validateSamlSignature(holder, postBinding, GeneralConstants.SAML_RESPONSE_KEY);
            } catch (VerificationException e) {
              log.error("Failed to verify saml response signature", e);
              return AuthOutcome.FAILED;
            }
          }
          return handleLogoutResponse(holder, statusResponse, relayState);
        } finally {
          sessionStore.setCurrentAction(SamlSessionStore.CurrentAction.NONE);
        }

      } else if (sessionStore.isLoggingIn()) {

        try {
          // KEYCLOAK-2107 - handle user not authenticated due passive mode. Return special outcome
          // so different authentication mechanisms can behave accordingly.
          StatusType status = statusResponse.getStatus();
          if (checkStatusCodeValue(
                  status.getStatusCode(), JBossSAMLURIConstants.STATUS_RESPONDER.get())
              && checkStatusCodeValue(
                  status.getStatusCode().getStatusCode(),
                  JBossSAMLURIConstants.STATUS_NO_PASSIVE.get())) {
            log.debug(
                "Not authenticated due passive mode Status found in SAML response: "
                    + status.toString());
            return AuthOutcome.NOT_AUTHENTICATED;
          }

          challenge =
              new AuthChallenge() {
                @Override
                public boolean challenge(HttpFacade exchange) {
                  SamlAuthenticationError error =
                      new SamlAuthenticationError(
                          SamlAuthenticationError.Reason.ERROR_STATUS, statusResponse);
                  exchange.getRequest().setError(error);
                  exchange.getResponse().sendError(403);
                  return true;
                }

                @Override
                public int getResponseCode() {
                  return 403;
                }
              };
          return AuthOutcome.FAILED;
        } finally {
          sessionStore.setCurrentAction(SamlSessionStore.CurrentAction.NONE);
        }
      }
      return AuthOutcome.NOT_ATTEMPTED;
    }
  }