Example #1
0
  /**
   * Parse the AuthnStatement inside the assertion
   *
   * @param xmlEventReader
   * @return
   * @throws ParsingException
   */
  public static AuthnStatementType parseAuthnStatement(XMLEventReader xmlEventReader)
      throws ParsingException {
    StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
    String AUTHNSTATEMENT = JBossSAMLConstants.AUTHN_STATEMENT.get();
    StaxParserUtil.validate(startElement, AUTHNSTATEMENT);

    Attribute authnInstant = startElement.getAttributeByName(new QName("AuthnInstant"));
    if (authnInstant == null) throw logger.parserRequiredAttribute("AuthnInstant");

    XMLGregorianCalendar issueInstant =
        XMLTimeUtil.parse(StaxParserUtil.getAttributeValue(authnInstant));
    AuthnStatementType authnStatementType = new AuthnStatementType(issueInstant);

    Attribute sessionIndex = startElement.getAttributeByName(new QName("SessionIndex"));
    if (sessionIndex != null)
      authnStatementType.setSessionIndex(StaxParserUtil.getAttributeValue(sessionIndex));

    while (xmlEventReader.hasNext()) {
      XMLEvent xmlEvent = StaxParserUtil.peek(xmlEventReader);
      if (xmlEvent == null) break;

      if (xmlEvent instanceof EndElement) {
        xmlEvent = StaxParserUtil.getNextEvent(xmlEventReader);
        EndElement endElement = (EndElement) xmlEvent;
        String endElementTag = StaxParserUtil.getEndElementName(endElement);
        if (endElementTag.equals(AUTHNSTATEMENT)) break;
        else throw logger.parserUnknownEndElement(endElementTag);
      }
      startElement = null;

      if (xmlEvent instanceof StartElement) {
        startElement = (StartElement) xmlEvent;
      } else {
        startElement = StaxParserUtil.peekNextStartElement(xmlEventReader);
      }
      if (startElement == null) break;

      String tag = StaxParserUtil.getStartElementName(startElement);

      if (JBossSAMLConstants.SUBJECT_LOCALITY.get().equals(tag)) {
        startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
        SubjectLocalityType subjectLocalityType = new SubjectLocalityType();
        Attribute address =
            startElement.getAttributeByName(new QName(JBossSAMLConstants.ADDRESS.get()));
        if (address != null) {
          subjectLocalityType.setAddress(StaxParserUtil.getAttributeValue(address));
        }
        Attribute dns =
            startElement.getAttributeByName(new QName(JBossSAMLConstants.DNS_NAME.get()));
        if (dns != null) {
          subjectLocalityType.setDNSName(StaxParserUtil.getAttributeValue(dns));
        }
        authnStatementType.setSubjectLocality(subjectLocalityType);
        StaxParserUtil.validate(
            StaxParserUtil.getNextEndElement(xmlEventReader),
            JBossSAMLConstants.SUBJECT_LOCALITY.get());
      } else if (JBossSAMLConstants.AUTHN_CONTEXT.get().equals(tag)) {
        authnStatementType.setAuthnContext(parseAuthnContextType(xmlEventReader));
      } else throw logger.parserUnknownTag(tag, startElement.getLocation());
    }

    return authnStatementType;
  }
  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;
  }