org.opensaml.saml2.core.Subject Java Examples

The following examples show how to use org.opensaml.saml2.core.Subject. 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 Project: lams   Author: lamsfoundation   File: AssertionUnmarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@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);
    }
}
 
Example #2
Source Project: lams   Author: lamsfoundation   File: AuthnRequestUnmarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    AuthnRequest req = (AuthnRequest) parentSAMLObject;

    if (childSAMLObject instanceof Subject) {
        req.setSubject((Subject) childSAMLObject);
    } else if (childSAMLObject instanceof NameIDPolicy) {
        req.setNameIDPolicy((NameIDPolicy) childSAMLObject);
    } else if (childSAMLObject instanceof Conditions) {
        req.setConditions((Conditions) childSAMLObject);
    } else if (childSAMLObject instanceof RequestedAuthnContext) {
        req.setRequestedAuthnContext((RequestedAuthnContext) childSAMLObject);
    } else if (childSAMLObject instanceof Scoping) {
        req.setScoping((Scoping) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #3
Source Project: lams   Author: lamsfoundation   File: SubjectUnmarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException {
    Subject subject = (Subject) parentObject;

    if (childObject instanceof BaseID) {
        subject.setBaseID((BaseID) childObject);
    } else if (childObject instanceof NameID) {
        subject.setNameID((NameID) childObject);
    } else if (childObject instanceof EncryptedID) {
        subject.setEncryptedID((EncryptedID) childObject);
    } else if (childObject instanceof SubjectConfirmation) {
        subject.getSubjectConfirmations().add((SubjectConfirmation) childObject);
    } else {
        super.processChildElement(parentObject, childObject);
    }
}
 
Example #4
Source Project: MaxKey   Author: shimingxy   File: SubjectGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public Subject generateSubject( 
						String assertionConsumerURL, 
						String inResponseTo, 
						int validInSeconds) {
	
	String nameIdValue =WebContext.getUserInfo().getUsername();
	NameID nameID =builderNameID(nameIdValue,assertionConsumerURL);
	Subject subject =builderSubject(nameID);
	
	String clientAddress=WebContext.getRequestIpAddress(WebContext.getRequest());
	SubjectConfirmation subjectConfirmation =builderSubjectConfirmation(
							assertionConsumerURL,
							inResponseTo,
							validInSeconds,
							clientAddress);

	subject.getSubjectConfirmations().add(subjectConfirmation);
	
	return subject;
}
 
Example #5
Source Project: saml-generator   Author: rackerlabs   File: SamlAssertionProducer.java    License: Apache License 2.0 6 votes vote down vote up
private Assertion createAssertion(final DateTime issueDate, Subject subject, Issuer issuer, AuthnStatement authnStatement,
		                          AttributeStatement attributeStatement) {
	AssertionBuilder assertionBuilder = new AssertionBuilder();
	Assertion assertion = assertionBuilder.buildObject();
	assertion.setID(UUID.randomUUID().toString());
	assertion.setIssueInstant(issueDate);
	assertion.setSubject(subject);
	assertion.setIssuer(issuer);
	
	if (authnStatement != null)
		assertion.getAuthnStatements().add(authnStatement);
	
	if (attributeStatement != null)
		assertion.getAttributeStatements().add(attributeStatement);
	
	return assertion;
}
 
Example #6
Source Project: lams   Author: lamsfoundation   File: SubjectSchemaValidator.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void validate(Subject subject) throws ValidationException {
    if (subject.getBaseID() == null && subject.getNameID() == null
            && (subject.getSubjectConfirmations() == null || subject.getSubjectConfirmations().size() == 0)) {
        throw new ValidationException("ID or SubjectConfirmation required");
    }
}
 
Example #7
Source Project: lams   Author: lamsfoundation   File: SubjectQueryUnmarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    SubjectQuery sq = (SubjectQuery) parentSAMLObject;

    if (childSAMLObject instanceof Subject) {
        sq.setSubject((Subject) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #8
Source Project: carbon-identity   Author: wso2-attic   File: SSOAssertionConsumerService.java    License: Apache License 2.0 5 votes vote down vote up
private void handleFederatedSAMLRequest(HttpServletRequest req, HttpServletResponse resp,
                                        String ssoTokenID, String samlRequest,
                                        String relayState, String authMode, Subject subject,
                                        String rpSessionId)
        throws IOException, ServletException, SAML2SSOUIAuthenticatorException {
    // Instantiate the service client.
    HttpSession session = req.getSession();
    String serverURL = CarbonUIUtil.getServerURL(session.getServletContext(), session);
    ConfigurationContext configContext =
            (ConfigurationContext) session.getServletContext()
                    .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
    SAMLSSOServiceClient ssoServiceClient = new SAMLSSOServiceClient(serverURL, configContext);

    String method = req.getMethod();
    boolean isPost = false;

    if ("post".equalsIgnoreCase(method)) {
        isPost = true;
    }

    SAMLSSOReqValidationResponseDTO signInRespDTO =
            ssoServiceClient.validate(samlRequest,
                    null, ssoTokenID,
                    rpSessionId,
                    authMode, isPost);
    if (signInRespDTO.getValid()) {
        handleRequestFromLoginPage(req, resp, ssoTokenID,
                signInRespDTO.getAssertionConsumerURL(),
                signInRespDTO.getId(), signInRespDTO.getIssuer(),
                subject.getNameID().getValue(), subject.getNameID()
                        .getValue(),
                signInRespDTO.getRpSessionId(),
                signInRespDTO.getRequestMessageString(), relayState);
    }
}
 
Example #9
Source Project: carbon-identity   Author: wso2-attic   File: AuthenticationRequestBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate an authentication request with passive support.
 *
 * @return AuthnRequest Object
 * @throws Exception
 */
public AuthnRequest buildAuthenticationRequest(String subjectName, String nameIdPolicyFormat, boolean isPassive)
        throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Building Authentication Request");
    }
    Util.doBootstrap();
    AuthnRequest authnRequest = (AuthnRequest) Util
            .buildXMLObject(AuthnRequest.DEFAULT_ELEMENT_NAME);
    authnRequest.setID(Util.createID());
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setIssuer(buildIssuer());
    authnRequest.setNameIDPolicy(buildNameIDPolicy(nameIdPolicyFormat));
    authnRequest.setIsPassive(isPassive);
    authnRequest.setDestination(Util.getIdentityProviderSSOServiceURL());
    String acs = Util.getAssertionConsumerServiceURL();
    if (acs != null && acs.trim().length() > 0) {
        authnRequest.setAssertionConsumerServiceURL(acs);
    } else {
        authnRequest.setAssertionConsumerServiceURL(CarbonUIUtil.getAdminConsoleURL("").replace("carbon/", "acs"));
    }

    if (subjectName != null) {
        Subject subject = new SubjectBuilder().buildObject();
        NameID nameId = new NameIDBuilder().buildObject();
        nameId.setValue(subjectName);
        nameId.setFormat(NameIdentifier.EMAIL);
        subject.setNameID(nameId);
        authnRequest.setSubject(subject);

    }

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

    return authnRequest;
}
 
Example #10
Source Project: carbon-commons   Author: wso2   File: SAMLSSORelyingPartyObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Extract the name of authenticated user from SAML response.
 *
 * @param cx
 * @param thisObj
 * @param args
 * @param funObj
 * @return
 * @throws Exception
 */
public static String jsFunction_getSAMLResponseNameId(Context cx, Scriptable thisObj,
                                                      Object[] args,
                                                      Function funObj)
        throws Exception {
    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String)) {
        throw new ScriptException("Invalid argument. The SAML response is missing.");
    }
    String decodedString = Util.decode((String) args[0]);
    XMLObject samlObject = Util.unmarshall(decodedString);
    String username = null;

    if (samlObject instanceof Response) {
        Response samlResponse = (Response) samlObject;
        List<Assertion> assertions = samlResponse.getAssertions();

        // extract the username
        if (assertions != null && assertions.size() > 0) {
            Subject subject = assertions.get(0).getSubject();
            if (subject != null) {
                if (subject.getNameID() != null) {
                    username = subject.getNameID().getValue();
                }
            }
        }
    }
    if (username == null) {
        throw new Exception("Failed to get subject assertion from SAML response.");
    }
    return username;
}
 
Example #11
Source Project: saml-generator   Author: rackerlabs   File: SamlAssertionProducer.java    License: Apache License 2.0 5 votes vote down vote up
private Subject createSubject(final String subjectId, final Integer samlAssertionDays) {
	DateTime currentDate = new DateTime();
	if (samlAssertionDays != null)
		currentDate = currentDate.plusDays(samlAssertionDays);
	
	// create name element
	NameIDBuilder nameIdBuilder = new NameIDBuilder(); 
	NameID nameId = nameIdBuilder.buildObject();
	nameId.setValue(subjectId);
	nameId.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");

	SubjectConfirmationDataBuilder dataBuilder = new SubjectConfirmationDataBuilder();
	SubjectConfirmationData subjectConfirmationData = dataBuilder.buildObject();
	subjectConfirmationData.setNotOnOrAfter(currentDate);
	
	SubjectConfirmationBuilder subjectConfirmationBuilder = new SubjectConfirmationBuilder();
	SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
	subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:bearer");
	subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData);
	
	// create subject element
	SubjectBuilder subjectBuilder = new SubjectBuilder();
	Subject subject = subjectBuilder.buildObject();
	subject.setNameID(nameId);
	subject.getSubjectConfirmations().add(subjectConfirmation);
	
	return subject;
}
 
Example #12
Source Project: cloudstack   Author: apache   File: SAML2LoginAPIAuthenticatorCmdTest.java    License: 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 #13
Source Project: lams   Author: lamsfoundation   File: AuthnRequestImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public Subject getSubject() {
    return this.subject;
}
 
Example #14
Source Project: lams   Author: lamsfoundation   File: AuthnRequestImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public void setSubject(Subject newSubject) {
    this.subject = prepareForAssignment(this.subject, newSubject);
}
 
Example #15
Source Project: lams   Author: lamsfoundation   File: SubjectQueryImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public Subject getSubject() {
    return this.subject;
}
 
Example #16
Source Project: lams   Author: lamsfoundation   File: SubjectQueryImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void setSubject(Subject newSubject) {
    this.subject = prepareForAssignment(this.subject, newSubject);
}
 
Example #17
Source Project: lams   Author: lamsfoundation   File: SubjectBuilder.java    License: GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public Subject buildObject() {
    return buildObject(SAMLConstants.SAML20_NS, Subject.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX);
}
 
Example #18
Source Project: lams   Author: lamsfoundation   File: SubjectBuilder.java    License: GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public Subject buildObject(String namespaceURI, String localName, String namespacePrefix) {
    return new SubjectImpl(namespaceURI, localName, namespacePrefix);
}
 
Example #19
Source Project: lams   Author: lamsfoundation   File: AssertionImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public Subject getSubject() {
    return subject;
}
 
Example #20
Source Project: lams   Author: lamsfoundation   File: AssertionImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public void setSubject(Subject newSubject) {
    this.subject = prepareForAssignment(this.subject, newSubject);
}
 
Example #21
Source Project: MaxKey   Author: shimingxy   File: SubjectGenerator.java    License: Apache License 2.0 4 votes vote down vote up
public Subject builderSubject (NameID nameID){
	//Response/Assertion/Subject
	Subject subject = new SubjectBuilder().buildObject();
	subject.setNameID(nameID);
	return subject;
}
 
Example #22
Source Project: jam-collaboration-sample   Author: SAP-samples   File: OAuth2SAMLWorkflowSample.java    License: Apache License 2.0 4 votes vote down vote up
private static Assertion buildSAML2Assertion(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 (SUBJECT_NAME_ID_FORMAT.equals("email")) {
        nameID.setFormat(NameIDType.EMAIL);
    } else if (SUBJECT_NAME_ID_FORMAT.equals("unspecified")) {
        nameID.setFormat(NameIDType.UNSPECIFIED);
    } else {
        throw new IllegalArgumentException("SUBJECT_NAME_ID_FORMAT must be 'email' or 'unspecified'.");
    }
    if (subjectNameIdQualifier != null) {
        nameID.setNameQualifier(subjectNameIdQualifier);
    }
    nameID.setValue(SUBJECT_NAME_ID);
    
    SubjectConfirmationData subjectConfirmationData = (new SubjectConfirmationDataBuilder().buildObject());
    subjectConfirmationData.setRecipient(BASE_URL + 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(IDP_ID);
    
    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(CLIENT_KEY);

        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;
}
 
Example #23
Source Project: jam-collaboration-sample   Author: SAP-samples   File: OAuth2SAMLWorkflowSample.java    License: 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;
}
 
Example #24
Source Project: jam-collaboration-sample   Author: SAP-samples   File: OAuth2SAMLUtil.java    License: 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 #25
Source Project: carbon-identity   Author: wso2-attic   File: SAML2TokenBuilder.java    License: 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 #26
Source Project: carbon-commons   Author: wso2   File: SAMLSSORelyingPartyObject.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Set the current session as authenticated by mapping with current session id to session index.
 *
 * @param cx
 * @param thisObj
 * @param args    -args[0]- current session id, args[1]-SAML response
 * @param funObj
 * @throws Exception
 */
public static void jsFunction_setSessionAuthenticated(Context cx, Scriptable thisObj,
                                                      Object[] args,
                                                      Function funObj)
        throws Exception {
    int argLength = args.length;
    if (argLength != 2 || !(args[0] instanceof String) || !(args[1] instanceof String)) {
        throw new ScriptException("Invalid argument. Current session id and SAML response are missing.");
    }
    String decodedString = Util.decode((String) args[1]);
    SAMLSSORelyingPartyObject relyingPartyObject = (SAMLSSORelyingPartyObject) thisObj;
    XMLObject samlObject = Util.unmarshall(decodedString);
    String sessionIndex = null;
    String username = null;
    if (samlObject instanceof Response) {
        Response samlResponse = (Response) samlObject;
        List<Assertion> assertions = samlResponse.getAssertions();

        // extract the session index
        if (assertions != null && assertions.size() > 0) {
            List<AuthnStatement> authenticationStatements = assertions.get(0).getAuthnStatements();
            AuthnStatement authnStatement = authenticationStatements.get(0);
            if (authnStatement != null) {
                if (authnStatement.getSessionIndex() != null) {
                    sessionIndex = authnStatement.getSessionIndex();
                }
            }
        }

        // extract the username
        if (assertions != null && assertions.size() > 0) {
            Subject subject = assertions.get(0).getSubject();
            if (subject != null) {
                if (subject.getNameID() != null) {
                    username = subject.getNameID().getValue();
                }
            }
        }
    }
    if (sessionIndex == null) {
        throw new Exception("Failed to get session index from authentication statement in SAML response.");
    }
    if (username == null) {
        throw new Exception("Failed to get subject assertion from SAML response.");
    }

    SessionInfo sessionInfo = new SessionInfo((String) args[0]);
    sessionInfo.setSessionIndex(sessionIndex);
    sessionInfo.setLoggedInUser(username);
    sessionInfo.setSamlToken((String) args[1]);//We expect an encoded SamlToken here.
    relyingPartyObject.addSessionInfo(sessionInfo);

}
 
Example #27
Source Project: saml-generator   Author: rackerlabs   File: SamlAssertionProducer.java    License: Apache License 2.0 4 votes vote down vote up
public Response createSAMLResponse(final String subjectId, final DateTime authenticationTime,
		                           final String credentialType, final HashMap<String, List<String>> attributes, String issuer, Integer samlAssertionDays) {
	
	try {
		DefaultBootstrap.bootstrap();
		
		Signature signature = createSignature();
		Status status = createStatus();
		Issuer responseIssuer = null;
		Issuer assertionIssuer = null;
		Subject subject = null;
		AttributeStatement attributeStatement = null;
		
		if (issuer != null) {
			responseIssuer = createIssuer(issuer);
			assertionIssuer = createIssuer(issuer);
		}
		
		if (subjectId != null) {
			subject = createSubject(subjectId, samlAssertionDays);
		}
		
		if (attributes != null && attributes.size() != 0) {
			attributeStatement = createAttributeStatement(attributes);
		}
		
		AuthnStatement authnStatement = createAuthnStatement(authenticationTime);
		
		Assertion assertion = createAssertion(new DateTime(), subject, assertionIssuer, authnStatement, attributeStatement);
		
		Response response = createResponse(new DateTime(), responseIssuer, status, assertion);
		response.setSignature(signature);
		
		ResponseMarshaller marshaller = new ResponseMarshaller();
		Element element = marshaller.marshall(response);
		
		if (signature != null) {
			Signer.signObject(signature);
		}
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		XMLHelper.writeNode(element, baos);
	
		return response;
		
	} catch (Throwable t) {
		t.printStackTrace();
		return null;
	}
}
 
Example #28
Source Project: secure-data-service   Author: inbloom   File: SamlFederationResourceTest.java    License: Apache License 2.0 3 votes vote down vote up
private Assertion createAssertion(String conditionNotBefore,  String subjectNotBefore, String recipient) {
    Assertion assertion = Mockito.mock(Assertion.class);

    Conditions conditions = Mockito.mock(Conditions.class);

    DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");

    DateTime datetime = DateTime.now();
    datetime = datetime.plusMonths(1) ;

    Mockito.when(conditions.getNotBefore()).thenReturn(DateTime.parse(conditionNotBefore, fmt));
    Mockito.when(conditions.getNotOnOrAfter()).thenReturn(DateTime.parse(datetime.toString(fmt), fmt));

    Subject subject = Mockito.mock(Subject.class);
    SubjectConfirmationData subjectConfirmationData = Mockito.mock(SubjectConfirmationData.class);

    SubjectConfirmation subjectConfirmation = Mockito.mock(SubjectConfirmation.class);
    Mockito.when(subjectConfirmation.getSubjectConfirmationData()).thenReturn(subjectConfirmationData);

    ArrayList<SubjectConfirmation> res = new ArrayList<SubjectConfirmation>();
    res.add(subjectConfirmation);

    Mockito.when(subject.getSubjectConfirmations()).thenReturn(res);

    Mockito.when(subjectConfirmationData.getNotBefore()).thenReturn(DateTime.parse(subjectNotBefore, fmt));
    Mockito.when(subjectConfirmationData.getNotOnOrAfter()).thenReturn(DateTime.parse(datetime.toString(fmt), fmt));
    Mockito.when(subjectConfirmationData.getRecipient()).thenReturn(recipient);

    Mockito.when(assertion.getConditions()).thenReturn(conditions);
    Mockito.when(assertion.getSubject()).thenReturn(subject);

    return assertion;
}