Java Code Examples for org.opensaml.saml2.core.Issuer#setValue()

The following examples show how to use org.opensaml.saml2.core.Issuer#setValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthenticationRequestBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Build the issuer object
 *
 * @return Issuer object
 */
private static Issuer buildIssuer() {
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(Util.getServiceProviderId());
    return issuer;
}
 
Example 2
Source File: SAMLUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static AuthnRequest buildAuthnRequestObject(final String authnId, final String spId, final String idpUrl, final String consumerUrl) {
    // Issuer object
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(spId);

    // AuthnContextClass
    AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
    AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject(
            SAMLConstants.SAML20_NS,
            "AuthnContextClassRef", "saml");
    authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX);

    // AuthnContext
    RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
    RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

    // Creation of AuthRequestObject
    AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
    AuthnRequest authnRequest = authRequestBuilder.buildObject();
    authnRequest.setID(authnId);
    authnRequest.setDestination(idpUrl);
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setForceAuthn(false);
    authnRequest.setIsPassive(false);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
    authnRequest.setAssertionConsumerServiceURL(consumerUrl);
    authnRequest.setProviderName(spId);
    authnRequest.setIssuer(issuer);
    authnRequest.setRequestedAuthnContext(requestedAuthnContext);

    return authnRequest;
}
 
Example 3
Source File: SamlAssertionProducer.java    From saml-generator with Apache License 2.0 5 votes vote down vote up
private Issuer createIssuer(final String issuerName) {
	// create Issuer object
	IssuerBuilder issuerBuilder = new IssuerBuilder();
	Issuer issuer = issuerBuilder.buildObject();
	issuer.setValue(issuerName);	
	return issuer;
}
 
Example 4
Source File: AuthReqBuilder.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Build the issuer object
 *
 * @return Issuer object
 */
private static Issuer buildIssuer(String issuerId) {
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(issuerId);
    return issuer;
}
 
Example 5
Source File: LogoutRequestBuilder.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Build the logout request
 * @param subject name of the user
 * @param reason reason for generating logout request.
 * @return LogoutRequest object
 */
public LogoutRequest buildLogoutRequest(String subject,String sessionIndexId, String reason,
                                        String issuerId) {
    Util.doBootstrap();
    LogoutRequest logoutReq = new org.opensaml.saml2.core.impl.LogoutRequestBuilder().buildObject();
    logoutReq.setID(Util.createID());

    DateTime issueInstant = new DateTime();
    logoutReq.setIssueInstant(issueInstant);
    logoutReq.setNotOnOrAfter(new DateTime(issueInstant.getMillis() + 5 * 60 * 1000));

    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(issuerId);
    logoutReq.setIssuer(issuer);

    NameID nameId = new NameIDBuilder().buildObject();
    nameId.setFormat(SSOConstants.SAML2_NAME_ID_POLICY);
    nameId.setValue(subject);
    logoutReq.setNameID(nameId);

    SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
    sessionIndex.setSessionIndex(sessionIndexId);
    logoutReq.getSessionIndexes().add(sessionIndex);

    logoutReq.setReason(reason);

    return logoutReq;
}
 
Example 6
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected LogoutRequest buildLogoutRequest(String user, String sessionIdx) throws SSOAgentException {

        LogoutRequest logoutReq = new LogoutRequestBuilder().buildObject();

        logoutReq.setID(SSOAgentUtils.createID());
        logoutReq.setDestination(ssoAgentConfig.getSAML2().getIdPURL());

        DateTime issueInstant = new DateTime();
        logoutReq.setIssueInstant(issueInstant);
        logoutReq.setNotOnOrAfter(new DateTime(issueInstant.getMillis() + 5 * 60 * 1000));

        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer = issuerBuilder.buildObject();
        issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId());
        logoutReq.setIssuer(issuer);

        NameID nameId = new NameIDBuilder().buildObject();
        nameId.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:entity");
        nameId.setValue(user);
        logoutReq.setNameID(nameId);

        SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
        sessionIndex.setSessionIndex(sessionIdx);
        logoutReq.getSessionIndexes().add(sessionIndex);

        logoutReq.setReason("Single Logout");

        return logoutReq;
    }
 
Example 7
Source File: WSXACMLEntitlementServiceClient.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Create the issuer object to be added
 *
 * @return : the issuer of the statements
 */
private static Issuer createIssuer() {

    IssuerBuilder issuer = (IssuerBuilder) org.opensaml.xml.Configuration.getBuilderFactory().
            getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuerObject = issuer.buildObject();
    issuerObject.setValue(ISSUER_URL);
    issuerObject.setSPProvidedID("SPPProvierId");

    return issuerObject;
}
 
Example 8
Source File: WSXACMLEntitlementServiceClient.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Create the issuer object to be added
 *
 * @return : the issuer of the statements
 */
private static Issuer createIssuer() {

    IssuerBuilder issuer = (IssuerBuilder) org.opensaml.xml.Configuration.getBuilderFactory().
            getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuerObject = issuer.buildObject();
    issuerObject.setValue(ISSUER_URL);
    issuerObject.setSPProvidedID("SPPProvierId");

    return issuerObject;
}
 
Example 9
Source File: LogoutRequestBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Build the logout request
 *
 * @param subject name of the user
 * @param reason  reason for generating logout request.
 * @return LogoutRequest object
 * @throws Exception
 */
public LogoutRequest buildLogoutRequest(String subject, String reason, String sessionIndexStr) throws Exception {
    log.info("Building logout request");
    Util.doBootstrap();
    LogoutRequest logoutReq = new org.opensaml.saml2.core.impl.LogoutRequestBuilder().buildObject();
    logoutReq.setID(Util.createID());
    logoutReq.setDestination(Util.getIdentityProviderSSOServiceURL());

    DateTime issueInstant = new DateTime();
    logoutReq.setIssueInstant(issueInstant);
    logoutReq.setNotOnOrAfter(new DateTime(issueInstant.getMillis() + 5 * 60 * 1000));

    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(Util.getServiceProviderId());
    logoutReq.setIssuer(issuer);

    NameID nameId = new NameIDBuilder().buildObject();
    nameId.setFormat(SAML2SSOAuthenticatorConstants.SAML2_NAME_ID_POLICY_TRANSIENT);
    nameId.setValue(subject);
    logoutReq.setNameID(nameId);

    SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
    sessionIndex.setSessionIndex(sessionIndexStr);
    logoutReq.getSessionIndexes().add(sessionIndex);

    logoutReq.setReason(reason);

    Util.setSignature(logoutReq, XMLSignature.ALGO_ID_SIGNATURE_RSA, new SignKeyDataHolder());

    return logoutReq;
}
 
Example 10
Source File: SAML2LoginAPIAuthenticatorCmdTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private Response buildMockResponse() throws Exception {
    Response samlMessage = new ResponseBuilder().buildObject();
    samlMessage.setID("foo");
    samlMessage.setVersion(SAMLVersion.VERSION_20);
    samlMessage.setIssueInstant(new DateTime(0));
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue("MockedIssuer");
    samlMessage.setIssuer(issuer);
    Status status = new StatusBuilder().buildObject();
    StatusCode statusCode = new StatusCodeBuilder().buildObject();
    statusCode.setValue(StatusCode.SUCCESS_URI);
    status.setStatusCode(statusCode);
    samlMessage.setStatus(status);
    Assertion assertion = new AssertionBuilder().buildObject();
    Subject subject = new SubjectBuilder().buildObject();
    NameID nameID = new NameIDBuilder().buildObject();
    nameID.setValue("SOME-UNIQUE-ID");
    nameID.setFormat(NameIDType.PERSISTENT);
    subject.setNameID(nameID);
    assertion.setSubject(subject);
    AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject();
    authnStatement.setSessionIndex("Some Session String");
    assertion.getAuthnStatements().add(authnStatement);
    AttributeStatement attributeStatement = new AttributeStatementBuilder().buildObject();
    assertion.getAttributeStatements().add(attributeStatement);
    samlMessage.getAssertions().add(assertion);
    return samlMessage;
}
 
Example 11
Source File: WSXACMLMessageReceiver.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Create the issuer object to be added
 *
 * @return : the issuer of the statements
 */
private static Issuer createIssuer() {

    IssuerBuilder issuer = (IssuerBuilder) org.opensaml.xml.Configuration.getBuilderFactory().
            getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuerObject = issuer.buildObject();
    issuerObject.setValue("https://identity.carbon.wso2.org");
    issuerObject.setSPProvidedID("SPPProvierId");
    return issuerObject;
}
 
Example 12
Source File: SAMLUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static LogoutRequest buildLogoutRequest(String logoutUrl, String spId, String nameIdString) {
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(spId);
    NameID nameID = new NameIDBuilder().buildObject();
    nameID.setValue(nameIdString);
    LogoutRequest logoutRequest = new LogoutRequestBuilder().buildObject();
    logoutRequest.setID(generateSecureRandomId());
    logoutRequest.setDestination(logoutUrl);
    logoutRequest.setVersion(SAMLVersion.VERSION_20);
    logoutRequest.setIssueInstant(new DateTime());
    logoutRequest.setIssuer(issuer);
    logoutRequest.setNameID(nameID);
    return logoutRequest;
}
 
Example 13
Source File: IssuerGenerator.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public Issuer generateIssuer() {
	///Issuer
	Issuer issuer = new IssuerBuilder().buildObject();

	issuer.setValue(issuerName);
	issuer.setFormat(NameIDType.ENTITY);
	
	return issuer;
}
 
Example 14
Source File: DefaultSAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private AuthnRequest buildAuthnRequest(HttpServletRequest request,
                                         boolean isPassive, String idpUrl, AuthenticationContext context) throws SAMLSSOException {

      IssuerBuilder issuerBuilder = new IssuerBuilder();
      Issuer issuer = issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "Issuer", "samlp");

      String spEntityId = properties.get(IdentityApplicationConstants.Authenticator.SAML2SSO.SP_ENTITY_ID);

      if (spEntityId != null && !spEntityId.isEmpty()) {
          issuer.setValue(spEntityId);
      } else {
          issuer.setValue("carbonServer");
      }

      DateTime issueInstant = new DateTime();

/* Creation of AuthRequestObject */
      AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
      AuthnRequest authRequest = authRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol",
              "AuthnRequest", "samlp");
      authRequest.setForceAuthn(isForceAuthenticate(context));
      authRequest.setIsPassive(isPassive);
      authRequest.setIssueInstant(issueInstant);

String includeProtocolBindingProp = properties
              .get(IdentityApplicationConstants.Authenticator.SAML2SSO.INCLUDE_PROTOCOL_BINDING);
      if (StringUtils.isEmpty(includeProtocolBindingProp) || Boolean.parseBoolean(includeProtocolBindingProp)) {
          authRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
      }

      String acsUrl = null;
      AuthenticatorConfig authenticatorConfig =
              FileBasedConfigurationBuilder.getInstance().getAuthenticatorConfigMap()
                      .get(SSOConstants.AUTHENTICATOR_NAME);
      if (authenticatorConfig != null){
          String tmpAcsUrl = authenticatorConfig.getParameterMap().get(SSOConstants.ServerConfig.SAML_SSO_ACS_URL);
          if(StringUtils.isNotBlank(tmpAcsUrl)){
              acsUrl = tmpAcsUrl;
          }
      }

      if(acsUrl == null) {
          acsUrl = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH, true, true);
      }

      authRequest.setAssertionConsumerServiceURL(acsUrl);
      authRequest.setIssuer(issuer);
      authRequest.setID(SSOUtils.createID());
      authRequest.setVersion(SAMLVersion.VERSION_20);
      authRequest.setDestination(idpUrl);

String attributeConsumingServiceIndexProp = properties
              .get(IdentityApplicationConstants.Authenticator.SAML2SSO.ATTRIBUTE_CONSUMING_SERVICE_INDEX);
      if (StringUtils.isNotEmpty(attributeConsumingServiceIndexProp)) {
          try {	
              authRequest.setAttributeConsumingServiceIndex(Integer
                      .valueOf(attributeConsumingServiceIndexProp));
          } catch (NumberFormatException e) {
              log.error(
                      "Error while populating SAMLRequest with AttributeConsumingServiceIndex: "
                              + attributeConsumingServiceIndexProp, e);
          }
      }
      
      String includeNameIDPolicyProp = properties
              .get(IdentityApplicationConstants.Authenticator.SAML2SSO.INCLUDE_NAME_ID_POLICY);
      if (StringUtils.isEmpty(includeNameIDPolicyProp) || Boolean.parseBoolean(includeNameIDPolicyProp)) {
          NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
          NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
          nameIdPolicy.setFormat(NameIDType.UNSPECIFIED);
          //nameIdPolicy.setSPNameQualifier("Issuer");
          nameIdPolicy.setAllowCreate(true);
          authRequest.setNameIDPolicy(nameIdPolicy);
      }

//Get the inbound SAMLRequest
      AuthnRequest inboundAuthnRequest = getAuthnRequest(context);
      
      RequestedAuthnContext requestedAuthnContext = buildRequestedAuthnContext(inboundAuthnRequest);
      if (requestedAuthnContext != null) {
          authRequest.setRequestedAuthnContext(requestedAuthnContext);
      }

      Extensions extensions = getSAMLExtensions(request);
      if (extensions != null) {
          authRequest.setExtensions(extensions);
      }

      return authRequest;
  }
 
Example 15
Source File: ErrorResponseBuilder.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private static Issuer getIssuer() {
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue("WSO2 Identity Server");
    issuer.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:entity");
    return issuer;
}
 
Example 16
Source File: SAML2TokenBuilder.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public void createSAMLAssertion(DateTime notAfter, DateTime notBefore, String assertionId)
        throws IdentityProviderException {
    assertion = (Assertion) buildXMLObject(Assertion.DEFAULT_ELEMENT_NAME);
    Conditions conditions = (Conditions) buildXMLObject(Conditions.DEFAULT_ELEMENT_NAME);
    conditions.setNotBefore(notBefore);
    conditions.setNotOnOrAfter(notAfter);

    ServerConfiguration config = ServerConfiguration.getInstance();
    String host = "http://" + config.getFirstProperty("HostName");

    Issuer issuer = (Issuer) buildXMLObject(Issuer.DEFAULT_ELEMENT_NAME);
    issuer.setValue(host);
    assertion.setIssuer(issuer);
    assertion.setIssueInstant(new DateTime());

    if (appilesTo != null) {
        Audience audience = (Audience) buildXMLObject(Audience.DEFAULT_ELEMENT_NAME);
        audience.setAudienceURI(appilesTo);
        AudienceRestriction audienceRestrictions =
                (AudienceRestriction) buildXMLObject(AudienceRestriction.DEFAULT_ELEMENT_NAME);
        audienceRestrictions.getAudiences().add(audience);

        conditions.getAudienceRestrictions().add(audienceRestrictions);
    }

    assertion.setConditions(conditions);

    assertion.getAttributeStatements().add(this.attributeStmt);
    assertion.setID(assertionId);

    Subject subject = (Subject) buildXMLObject(Subject.DEFAULT_ELEMENT_NAME);
    SubjectConfirmation subjectConf =
            (SubjectConfirmation) buildXMLObject(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
    SubjectConfirmationData confData =
            (SubjectConfirmationData) buildXMLObject(SubjectConfirmationData.DEFAULT_ELEMENT_NAME);
    confData.setAddress(CONF_KEY);
    subjectConf.setSubjectConfirmationData(confData);
    subject.getSubjectConfirmations().add(subjectConf);
    assertion.setSubject(subject);

}
 
Example 17
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected AuthnRequest buildAuthnRequest(HttpServletRequest request) throws SSOAgentException {

        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer =
                issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion",
                        "Issuer", "samlp");
        issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId());

		/* NameIDPolicy */
        NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
        NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
        nameIdPolicy.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
        nameIdPolicy.setSPNameQualifier("Issuer");
        nameIdPolicy.setAllowCreate(true);

		/* AuthnContextClass */
        AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
        AuthnContextClassRef authnContextClassRef =
                authnContextClassRefBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion",
                        "AuthnContextClassRef",
                        "saml");
        authnContextClassRef.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

		/* AuthnContex */
        RequestedAuthnContextBuilder requestedAuthnContextBuilder =
                new RequestedAuthnContextBuilder();
        RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
        requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
        requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

        DateTime issueInstant = new DateTime();

		/* Creation of AuthRequestObject */
        AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
        AuthnRequest authRequest =
                authRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol",
                        "AuthnRequest", "samlp");

        authRequest.setForceAuthn(ssoAgentConfig.getSAML2().isForceAuthn());
        authRequest.setIsPassive(ssoAgentConfig.getSAML2().isPassiveAuthn());
        authRequest.setIssueInstant(issueInstant);
        authRequest.setProtocolBinding(ssoAgentConfig.getSAML2().getHttpBinding());
        authRequest.setAssertionConsumerServiceURL(ssoAgentConfig.getSAML2().getACSURL());
        authRequest.setIssuer(issuer);
        authRequest.setNameIDPolicy(nameIdPolicy);
        authRequest.setRequestedAuthnContext(requestedAuthnContext);
        authRequest.setID(SSOAgentUtils.createID());
        authRequest.setVersion(SAMLVersion.VERSION_20);
        authRequest.setDestination(ssoAgentConfig.getSAML2().getIdPURL());
        if (request.getAttribute(Extensions.LOCAL_NAME) != null) {
            authRequest.setExtensions((Extensions) request.getAttribute(Extensions.LOCAL_NAME));
        }

		/* Requesting Attributes. This Index value is registered in the IDP */
        if (ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex() != null &&
                ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex().trim().length() > 0) {
            authRequest.setAttributeConsumingServiceIndex(Integer.parseInt(
                    ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex()));
        }

        return authRequest;
    }
 
Example 18
Source File: SAMLClient.java    From saml-sdk-java with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private String createAuthnRequest(String requestId)
    throws SAMLException
{
    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    SAMLObjectBuilder<AuthnRequest> builder =
        (SAMLObjectBuilder<AuthnRequest>) builderFactory
        .getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);

    SAMLObjectBuilder<Issuer> issuerBuilder =
        (SAMLObjectBuilder<Issuer>) builderFactory
        .getBuilder(Issuer.DEFAULT_ELEMENT_NAME);

    AuthnRequest request = builder.buildObject();
    request.setAssertionConsumerServiceURL(spConfig.getAcs().toString());
    request.setDestination(idpConfig.getLoginUrl().toString());
    request.setIssueInstant(new DateTime());
    request.setID(requestId);

    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(spConfig.getEntityId());
    request.setIssuer(issuer);

    try {
        // samlobject to xml dom object
        Element elem = Configuration.getMarshallerFactory()
            .getMarshaller(request)
            .marshall(request);

        // and to a string...
        Document document = elem.getOwnerDocument();
        DOMImplementationLS domImplLS = (DOMImplementationLS) document
            .getImplementation();
        LSSerializer serializer = domImplLS.createLSSerializer();
        serializer.getDomConfig().setParameter("xml-declaration", false);
        return serializer.writeToString(elem);
    }
    catch (MarshallingException e) {
        throw new SAMLException(e);
    }
}
 
Example 19
Source File: OAuth2SAMLUtil.java    From jam-collaboration-sample with Apache License 2.0 4 votes vote down vote up
public static String buildSignedSAML2Assertion(
    final String idpId,
    final String destinationUri,
    
    final String subjectNameId,
    final String subjectNameIdFormat,
    final String subjectNameIdQualifier,

    final PrivateKey idpPrivateKey,
    final X509Certificate idpCertificate,
    final String spJamId,
    final Map<String, List<Object>> attributes) throws Exception {
            
    // Bootstrap the OpenSAML library
    try {
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
        
    }

    DateTime issueInstant = new DateTime();
    DateTime notOnOrAfter = issueInstant.plusMinutes(10);
    DateTime notBefore = issueInstant.minusMinutes(10);
    
    NameID nameID = makeEmailFormatName(subjectNameId, subjectNameIdFormat, subjectNameIdQualifier);
    
    SubjectConfirmationData subjectConfirmationData = (new SubjectConfirmationDataBuilder().buildObject());
    subjectConfirmationData.setRecipient(destinationUri);
    subjectConfirmationData.setNotOnOrAfter(notOnOrAfter);
    
    SubjectConfirmation subjectConfirmation = (new SubjectConfirmationBuilder().buildObject());
    subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER);
    subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData);

    Subject subject = (new SubjectBuilder().buildObject());
    subject.setNameID(nameID);
    subject.getSubjectConfirmations().add(subjectConfirmation);
    
    Issuer issuer = (new IssuerBuilder().buildObject());
    issuer.setValue(idpId);
    
    Audience audience = (new AudienceBuilder().buildObject());
    audience.setAudienceURI(spJamId);
    
    AudienceRestriction audienceRestriction = (new AudienceRestrictionBuilder().buildObject());
    audienceRestriction.getAudiences().add(audience);
    
    Conditions conditions = (new ConditionsBuilder().buildObject());
    conditions.setNotBefore(notBefore);
    conditions.setNotOnOrAfter(notOnOrAfter);
    conditions.getAudienceRestrictions().add(audienceRestriction);
   
    Assertion assertion = (new AssertionBuilder().buildObject());
    assertion.setID(UUID.randomUUID().toString());
    assertion.setVersion(SAMLVersion.VERSION_20);
    assertion.setIssueInstant(issueInstant);
    assertion.setIssuer(issuer);
    assertion.setSubject(subject);
    assertion.setConditions(conditions);

    return signAssertion(assertion, idpPrivateKey);
}
 
Example 20
Source File: OAuth2SAMLWorkflowSample.java    From jam-collaboration-sample with Apache License 2.0 4 votes vote down vote up
private static Assertion buildSAML2Assertion(
        String baseUrl,
        String subjectNameId,
        String subjectNameIdFormat,
        String subjectNameIdQualifier,
        String idpId,
        String clientKey,
        boolean includeClientKeyAttribute)
{
    // Bootstrap the OpenSAML library
    try {
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
    }

    DateTime issueInstant = new DateTime();
    DateTime notOnOrAfter = issueInstant.plusMinutes(10);
    DateTime notBefore = issueInstant.minusMinutes(10);
    
    NameID nameID = (new NameIDBuilder().buildObject());
    if (subjectNameIdFormat.equals("email")) {
        nameID.setFormat(NameIDType.EMAIL);
    } else if (subjectNameIdFormat.equals("unspecified")) {
        nameID.setFormat(NameIDType.UNSPECIFIED);
    } else {
        throw new IllegalArgumentException("subjectNameIdFormat must be 'email' or 'unspecified'.");
    }
    if (subjectNameIdQualifier != null) {
        nameID.setNameQualifier(subjectNameIdQualifier);
    }
    nameID.setValue(subjectNameId);
    
    SubjectConfirmationData subjectConfirmationData = (new SubjectConfirmationDataBuilder().buildObject());
    subjectConfirmationData.setRecipient(baseUrl + ACCESS_TOKEN_URL_PATH);
    subjectConfirmationData.setNotOnOrAfter(notOnOrAfter);
    
    SubjectConfirmation subjectConfirmation = (new SubjectConfirmationBuilder().buildObject());
    subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER);
    subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData);

    Subject subject = (new SubjectBuilder().buildObject());
    subject.setNameID(nameID);
    subject.getSubjectConfirmations().add(subjectConfirmation);
    
    Issuer issuer = (new IssuerBuilder().buildObject());
    issuer.setValue(idpId);
    
    Audience audience = (new AudienceBuilder().buildObject());
    audience.setAudienceURI(SP_ID_JAM);
    
    AudienceRestriction audienceRestriction = (new AudienceRestrictionBuilder().buildObject());
    audienceRestriction.getAudiences().add(audience);
    
    Conditions conditions = (new ConditionsBuilder().buildObject());
    conditions.setNotBefore(notBefore);
    conditions.setNotOnOrAfter(notOnOrAfter);
    conditions.getAudienceRestrictions().add(audienceRestriction);
   
    Assertion assertion = (new AssertionBuilder().buildObject());
    assertion.setID(UUID.randomUUID().toString());
    assertion.setVersion(SAMLVersion.VERSION_20);
    assertion.setIssueInstant(issueInstant);
    assertion.setIssuer(issuer);
    assertion.setSubject(subject);
    assertion.setConditions(conditions);
    
    if (includeClientKeyAttribute) {
        XSString attributeValue = (XSString)Configuration.getBuilderFactory().getBuilder(XSString.TYPE_NAME).buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME);
        attributeValue.setValue(clientKey);

        Attribute attribute = (new AttributeBuilder().buildObject());
        attribute.setName("client_id");
        attribute.getAttributeValues().add(attributeValue);

        AttributeStatement attributeStatement = (new AttributeStatementBuilder().buildObject());
        attributeStatement.getAttributes().add(attribute);
        assertion.getAttributeStatements().add(attributeStatement);
    }

    return assertion;
}