org.opensaml.saml2.core.Assertion类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(17.4k)|赞(0)|评价(0)|浏览(164)

本文整理了Java中org.opensaml.saml2.core.Assertion类的一些代码示例,展示了Assertion类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Assertion类的具体详情如下:
包路径:org.opensaml.saml2.core.Assertion
类名称:Assertion

Assertion介绍

[英]SAML 2.0 Core Assertion.
[中]SAML2.0核心断言。

代码示例

代码示例来源:origin: cloudfoundry/uaa

assertion.getAttributeStatements().add(attributeStatement);

代码示例来源:origin: cloudfoundry/uaa

Assertion assertion = response.getAssertions().get(0);
DateTime until = new DateTime().plusHours(1);
assertion.getSubject().getSubjectConfirmations().get(0).getSubjectConfirmationData().setRecipient(spEndpoint);
assertion.getConditions().getAudienceRestrictions().get(0).getAudiences().get(0).setAudienceURI(audienceEntityID);
assertion.getIssuer().setValue(issuerEntityId);
assertion.getSubject().getNameID().setValue(username);
assertion.getSubject().getNameID().setFormat(format);
assertion.getSubject().getSubjectConfirmations().get(0).getSubjectConfirmationData().setInResponseTo(null);
assertion.getSubject().getSubjectConfirmations().get(0).getSubjectConfirmationData().setNotOnOrAfter(until);
assertion.getConditions().setNotOnOrAfter(until);
SamlConfig config = new SamlConfig();
config.addAndActivateKey("active-key", new SamlKey(privateKey, keyPassword, certificate));
signature.setSigningCredential(defaultCredential);
SecurityHelper.prepareSignatureParams(signature, defaultCredential, null, null);
assertion.setSignature(signature);
Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
marshaller.marshall(assertion);

代码示例来源:origin: cloudfoundry/uaa

public MultiValueMap<String, String> retrieveUserAttributes(SamlIdentityProviderDefinition definition, SAMLCredential credential) {
  logger.debug(String.format("Retrieving SAML user attributes [zone:%s, origin:%s]", definition.getZoneId(), definition.getIdpEntityAlias()));
  MultiValueMap<String, String> userAttributes = new LinkedMultiValueMap<>();
  if (definition != null && definition.getAttributeMappings() != null) {
    for (Entry<String, Object> attributeMapping : definition.getAttributeMappings().entrySet()) {
      if (attributeMapping.getValue() instanceof  String) {
        if (credential.getAttribute((String)attributeMapping.getValue()) != null) {
          String key = attributeMapping.getKey();
          for (XMLObject xmlObject : credential.getAttribute((String) attributeMapping.getValue()).getAttributeValues()) {
            String value = getStringValue(key, definition, xmlObject);
            if (value!=null) {
              userAttributes.add(key, value);
            }
          }
        }
      }
    }
  }
  if (credential.getAuthenticationAssertion() != null && credential.getAuthenticationAssertion().getAuthnStatements() != null) {
    for (AuthnStatement statement : credential.getAuthenticationAssertion().getAuthnStatements()) {
      if (statement.getAuthnContext() != null && statement.getAuthnContext().getAuthnContextClassRef() != null) {
        userAttributes.add(AUTHENTICATION_CONTEXT_CLASS_REFERENCE, statement.getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef());
      }
    }
  }
  return userAttributes;
}

代码示例来源:origin: cloudfoundry/uaa

private Assertion buildAssertion(Authentication authentication, AuthnRequest authnRequest,
    IdpWebSSOProfileOptions options, String audienceURI, String issuerEntityId) throws SAMLException{
  @SuppressWarnings("unchecked")
  SAMLObjectBuilder<Assertion> assertionBuilder = (SAMLObjectBuilder<Assertion>) builderFactory
      .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
  Assertion assertion = assertionBuilder.buildObject();
  assertion.setID(generateID());
  assertion.setIssueInstant(new DateTime());
  assertion.setVersion(SAMLVersion.VERSION_20);
  assertion.setIssuer(getIssuer(issuerEntityId));
  buildAssertionAuthnStatement(assertion);
  buildAssertionConditions(assertion, options.getAssertionTimeToLiveSeconds(), audienceURI);
  buildAssertionSubject(assertion, authnRequest, options.getAssertionTimeToLiveSeconds(),
      (UaaPrincipal) authentication.getPrincipal());
  buildAttributeStatement(assertion, authentication, audienceURI);
  return assertion;
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testBuildResponseWithSignedAssertion() throws MessageEncodingException, SAMLException,
    MetadataProviderException, SecurityException, MarshallingException, SignatureException {
  String authenticationId = UUID.randomUUID().toString();
  Authentication authentication = samlTestUtils.mockUaaAuthentication(authenticationId);
  SAMLMessageContext context = samlTestUtils.mockSamlMessageContext();
  IdpWebSSOProfileOptions options = new IdpWebSSOProfileOptions();
  options.setAssertionsSigned(true);
  profile.buildResponse(authentication, context, options);
  AuthnRequest request = (AuthnRequest) context.getInboundSAMLMessage();
  Response response = (Response) context.getOutboundSAMLMessage();
  Assertion assertion = response.getAssertions().get(0);
  Subject subject = assertion.getSubject();
  assertEquals("marissa", subject.getNameID().getValue());
  SubjectConfirmation subjectConfirmation = subject.getSubjectConfirmations().get(0);
  SubjectConfirmationData subjectConfirmationData = subjectConfirmation.getSubjectConfirmationData();
  assertEquals(request.getID(), subjectConfirmationData.getInResponseTo());
  verifyAssertionAttributes(authenticationId, assertion);
  assertNotNull(assertion.getSignature());
}

代码示例来源:origin: se.skltp.adapterservices.se.apotekensservice/TicketMachine

@Override
public Assertion build() {
  AssertionBuilder assertionBuilder = (AssertionBuilder) xmlObjectBuilderFactory.getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
  Assertion assertion = assertionBuilder.buildObject();        
  assertion.setID(id);
  assertion.setIssueInstant(issueInstant);
  assertion.setVersion(SAMLVersion.VERSION_20);
  assertion.setIssuer(issuer);
  assertion.setSubject(subject);
  assertion.setConditions(conditions);
  if(signature !=null){
    assertion.setSignature(signature);
  }
  if(authnStatements.size() > 0){
    for (AuthnStatement authnStatement : authnStatements) {
      assertion.getAuthnStatements().add(authnStatement);
    }
  }
  if(attributeStatements.size() > 0){
    for (AttributeStatement attributeStatement : attributeStatements) {
      assertion.getAttributeStatements().add(attributeStatement);
    }
  }
  
  return assertion;
}

代码示例来源:origin: usnistgov/iheos-toolkit2

params.getAuthenStateBean()
  );
saml2.getAuthnStatements().addAll(authnStatements);
    params.getAttrBean()
  );
saml2.getAttributeStatements().addAll(attributeStatements);
      params.getAuthzBean()
    );
saml2.getAuthzDecisionStatements().addAll(authDecisionStatements);
saml2.setIssuer(samlIssuer);
  saml2.setSubject(subject);
} catch (org.opensaml.xml.security.SecurityException ex) {
  throw new Exception(

代码示例来源:origin: usnistgov/iheos-toolkit2

private void verifyAssertion(Assertion assertion, AuthnRequest request, BasicSAMLMessageContext context) throws  SAMLException, org.opensaml.xml.security.SecurityException, ValidationException, Exception {
  // Verify assertion time skew
  if (!isDateTimeSkewValid(MAX_ASSERTION_TIME, assertion.getIssueInstant())) {
    System.out.println("Authentication statement is too old to be used"+assertion.getIssueInstant());
    throw new Exception("Users authentication credential is too old to be used");
  }
  // Verify validity of assertion
  // Advice is ignored, core 574
  verifyIssuer(assertion.getIssuer(), context);
  verifyAssertionSignature(assertion.getSignature(), context);
  verifySubject(assertion.getSubject(), request, context);
  // Assertion with authentication statement must contain audience restriction
  if (assertion.getAuthnStatements().size() > 0) {
    verifyAssertionConditions(assertion.getConditions(), context, true);
    for (AuthnStatement statement : assertion.getAuthnStatements()) {
      verifyAuthenticationStatement(statement, context);
    }
  } else {
    verifyAssertionConditions(assertion.getConditions(), context, false);
  }
}
/**

代码示例来源:origin: org.opensaml/opensaml

/** {@inheritDoc} */
  protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {
    Assertion assertion = (Assertion) samlObject;

    if (attribute.getLocalName().equals(Assertion.VERSION_ATTRIB_NAME)) {
      assertion.setVersion(SAMLVersion.valueOf(attribute.getValue()));
    } else if (attribute.getLocalName().equals(Assertion.ISSUE_INSTANT_ATTRIB_NAME)
        && !DatatypeHelper.isEmpty(attribute.getValue())) {
      assertion.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()));
    } else if (attribute.getLocalName().equals(Assertion.ID_ATTRIB_NAME)) {
      assertion.setID(attribute.getValue());
      attribute.getOwnerElement().setIdAttributeNode(attribute, true);
    } else {
      super.processAttribute(samlObject, attribute);
    }
  }
}

代码示例来源:origin: org.wso2.carbon.identity.framework/org.wso2.carbon.identity.entitlement

DateTime currentTime = new DateTime();
Assertion assertion = assertionBuilder.buildObject();
assertion.setVersion(org.opensaml.common.SAMLVersion.VERSION_20);
assertion.setIssuer(createIssuer());
assertion.setIssueInstant(currentTime);
assertion.getStatements().add(xacmlAuthzDecisionStatement);
ResponseBuilder builder = (ResponseBuilder) org.opensaml.xml.Configuration.getBuilderFactory()
    .getBuilder(Response.DEFAULT_ELEMENT_NAME);

代码示例来源:origin: org.opensaml/opensaml

/**
   * Checks that the Subject element is present when required.
   * 
   * @param assertion
   * @throws ValidationException
   */
  protected void validateSubject(Assertion assertion) throws ValidationException {
    if ((assertion.getStatements() == null || assertion.getStatements().size() == 0)
        && (assertion.getAuthnStatements() == null || assertion.getAuthnStatements().size() == 0)
        && (assertion.getAttributeStatements() == null || assertion.getAttributeStatements().size() == 0)
        && (assertion.getAuthzDecisionStatements() == null || assertion.getAuthzDecisionStatements().size() == 0)
        && assertion.getSubject() == null) {
      throw new ValidationException("Subject is required when Statements are absent");
    }

    if (assertion.getAuthnStatements().size() > 0 && assertion.getSubject() == null) {
      throw new ValidationException("Assertions containing AuthnStatements require a Subject");
    }
    if (assertion.getAuthzDecisionStatements().size() > 0 && assertion.getSubject() == null) {
      throw new ValidationException("Assertions containing AuthzDecisionStatements require a Subject");
    }
    if (assertion.getAttributeStatements().size() > 0 && assertion.getSubject() == null) {
      throw new ValidationException("Assertions containing AttributeStatements require a Subject");
    }
  }
}

代码示例来源:origin: org.wso2.carbon.appmgt/org.wso2.carbon.appmgt.gateway

private Map<String, Object> getUserAttributes(ResponseImpl samlResponse) {
  Map<String, Object> userAttributes = new HashMap<>();
  // Add 'Subject'
  Assertion assertion = samlResponse.getAssertions().get(0);
  userAttributes.put(SAMLConstants.SAML2_ASSERTION_SUBJECT, assertion.getSubject().getNameID().getValue());
  // Add other user attributes.
  List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
  if (attributeStatements != null) {
    for (AttributeStatement attributeStatement : attributeStatements) {
      List<Attribute> attributes = attributeStatement.getAttributes();
      for (Attribute attribute : attributes) {
        if (attribute.getAttributeValues().size() > 1) {
          List<XMLObject> attributeValues = attribute.getAttributeValues();
          List<String> attributeValuesList = new ArrayList<String>();
          for (XMLObject attributeValue : attributeValues) {
            attributeValuesList.add(attributeValue.getDOM().getTextContent());
          }
          userAttributes.put(attribute.getName(), attributeValuesList);
        } else {
          userAttributes.put(attribute.getName(), attribute.getAttributeValues().get(0).getDOM().getTextContent());
        }
      }
    }
  }
  return userAttributes;
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testBuildResponseForSamlRequestWithEmailAddressNameID() throws MessageEncodingException, SAMLException,
    MetadataProviderException, SecurityException, MarshallingException, SignatureException {
  String authenticationId = UUID.randomUUID().toString();
  Authentication authentication = samlTestUtils.mockUaaAuthentication(authenticationId);
  SAMLMessageContext context = samlTestUtils.mockSamlMessageContext(
      samlTestUtils.mockAuthnRequest(NameIDType.EMAIL));
  IdpWebSSOProfileOptions options = new IdpWebSSOProfileOptions();
  options.setAssertionsSigned(false);
  profile.buildResponse(authentication, context, options);
  AuthnRequest request = (AuthnRequest) context.getInboundSAMLMessage();
  Response response = (Response) context.getOutboundSAMLMessage();
  Assertion assertion = response.getAssertions().get(0);
  Subject subject = assertion.getSubject();
  assertEquals("marissa@testing.org", subject.getNameID().getValue());
  assertEquals(NameIDType.EMAIL, subject.getNameID().getFormat());
  SubjectConfirmation subjectConfirmation = subject.getSubjectConfirmations().get(0);
  SubjectConfirmationData subjectConfirmationData = subjectConfirmation.getSubjectConfirmationData();
  assertEquals(request.getID(), subjectConfirmationData.getInResponseTo());
  verifyAssertionAttributes(authenticationId, assertion);
}

代码示例来源:origin: apache/cloudstack

if (assertion!= null && assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
  session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue());
  break;
      continue;
    Signature encSig = assertion.getSignature();
    if (idpMetadata.getSigningCertificate() != null && encSig != null) {
      BasicX509Credential sigCredential = new BasicX509Credential();
    if (assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
      session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue());
      username = SAMLUtils.getValueFromAttributeStatements(assertion.getAttributeStatements(), SAML2AuthManager.SAMLUserAttributeName.value());

代码示例来源:origin: usnistgov/iheos-toolkit2

assertionBean.getAttrBean()
  );
assertion.setIssuer(samlIssuer);
org.opensaml.saml2.core.Conditions conditions = 
  SAMLAssertionBuilder.createConditions(assertionBean.getConditionsBean());
assertion.setConditions(conditions);
assertion.getAttributeStatements().addAll(attributeStatements);
evidenceElement.getAssertions().add(assertion);

代码示例来源:origin: org.opensaml/opensaml

/** {@inheritDoc} */
protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException {
  Assertion assertion = (Assertion) parentObject;
  if (childObject instanceof Issuer) {
    assertion.setIssuer((Issuer) childObject);
  } else if (childObject instanceof Signature) {
    assertion.setSignature((Signature) childObject);
  } else if (childObject instanceof Subject) {
    assertion.setSubject((Subject) childObject);
  } else if (childObject instanceof Conditions) {
    assertion.setConditions((Conditions) childObject);
  } else if (childObject instanceof Advice) {
    assertion.setAdvice((Advice) childObject);
  } else if (childObject instanceof Statement) {
    assertion.getStatements().add((Statement) childObject);
  } else {
    super.processChildElement(parentObject, childObject);
  }
}

代码示例来源:origin: coveo/saml-client

private void validateAssertion(Response response) throws SamlException {
 if (response.getAssertions().size() != 1) {
  throw new SamlException("The response doesn't contain exactly 1 assertion");
 }
 Assertion assertion = response.getAssertions().get(0);
 if (!assertion.getIssuer().getValue().equals(responseIssuer)) {
  throw new SamlException("The assertion issuer didn't match the expected value");
 }
 if (assertion.getSubject().getNameID() == null) {
  throw new SamlException(
    "The NameID value is missing from the SAML response; this is likely an IDP configuration issue");
 }
 enforceConditions(assertion.getConditions());
}

代码示例来源:origin: cloudfoundry/uaa

/** {@inheritDoc} */
protected void doDecode(MessageContext messageContext) throws MessageDecodingException {
  if (!(messageContext instanceof SAMLMessageContext)) {
    log.error("Invalid message context type, this decoder only support SAMLMessageContext");
    throw new MessageDecodingException(
      "Invalid message context type, this decoder only support SAMLMessageContext");
  }
  if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) {
    log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport");
    throw new MessageDecodingException(
      "Invalid inbound message transport type, this decoder only support HTTPInTransport");
  }
  SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;
  HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport();
  if (!inTransport.getHTTPMethod().equalsIgnoreCase("POST")) {
    throw new MessageDecodingException("This message decoder only supports the HTTP POST method");
  }
  String relayState = inTransport.getParameterValue("RelayState");
  samlMsgCtx.setRelayState(relayState);
  log.debug("Decoded SAML relay state of: {}", relayState);
  InputStream base64DecodedMessage = getBase64DecodedMessage(inTransport);
  Assertion inboundMessage = (Assertion) unmarshallMessage(base64DecodedMessage);
  Response response = SamlRedirectUtils.wrapAssertionIntoResponse(inboundMessage, inboundMessage.getIssuer().getValue());
  samlMsgCtx.setInboundMessage(response);
  samlMsgCtx.setInboundSAMLMessage(response);
  log.debug("Decoded SAML message");
  populateMessageContext(samlMsgCtx);
}

代码示例来源:origin: org.wso2.carbon.identity/org.wso2.carbon.identity.relyingparty

/**
 * @return the SAML signature.
 */
@Override
public Signature getSAMLSignature() {
  return assertion.getSignature();
}

代码示例来源:origin: org.apache.rampart/rampart-core

protected void processSAMLAssertion() {
  this.setAssertionId(assertion.getID());
  Subject subject = assertion.getSubject();
  //Read the validity period from the 'Conditions' element, else read it from SC Data
  if (assertion.getConditions() != null) {
    Conditions conditions = assertion.getConditions();
    if (conditions.getNotBefore() != null) {
      this.setDateNotBefore(conditions.getNotBefore().toDate());
    }
    if (conditions.getNotOnOrAfter() != null) {
      this.setDateNotOnOrAfter(conditions.getNotOnOrAfter().toDate());
    }
  } else {
    SubjectConfirmationData scData = subject.getSubjectConfirmations()
        .get(0).getSubjectConfirmationData();
    if (scData.getNotBefore() != null) {
      this.setDateNotBefore(scData.getNotBefore().toDate());
    }
    if (scData.getNotOnOrAfter() != null) {
      this.setDateNotOnOrAfter(scData.getNotOnOrAfter().toDate());
    }
  }
}

相关文章