Java Code Examples for org.opensaml.saml2.core.NameID#setFormat()

The following examples show how to use org.opensaml.saml2.core.NameID#setFormat() . 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: OAuth2SAMLUtil.java    From jam-collaboration-sample with Apache License 2.0 6 votes vote down vote up
public static NameID makeEmailFormatName(final String subjectNameId, final String subjectNameIdFormat, final String subjectNameIdQualifier) {
    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);
    
    return nameID;
}
 
Example 2
Source File: SubjectGenerator.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public NameID builderNameID(String value,String strSPNameQualifier){
	//Response/Assertion/Subject/NameID	
	NameID nameID = new NameIDBuilder().buildObject();
	nameID.setValue(value);
	//nameID.setFormat(NameIDType.PERSISTENT);
	nameID.setFormat(NameIDType.UNSPECIFIED);
	//nameID.setSPNameQualifier(strSPNameQualifier);
	
	return nameID;
}
 
Example 3
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 4
Source File: AuthenticationRequestBuilder.java    From carbon-identity with 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 5
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 6
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 7
Source File: SamlAssertionProducer.java    From saml-generator with 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 8
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 9
Source File: OAuth2SAMLWorkflowSample.java    From jam-collaboration-sample with 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 10
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;
}
 
Example 11
Source File: DefaultSAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private LogoutRequest buildLogoutRequest(String user, String sessionIndexStr, String idpUrl, String nameQualifier, String spNameQualifier)
        throws SAMLSSOException {

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

    logoutReq.setID(SSOUtils.createID());
    logoutReq.setDestination(idpUrl);

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

    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();

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

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

    logoutReq.setIssuer(issuer);

    NameID nameId = new NameIDBuilder().buildObject();
    nameId.setFormat(NameIDType.UNSPECIFIED);
    nameId.setValue(user);
    nameId.setNameQualifier(nameQualifier);
    nameId.setSPNameQualifier(spNameQualifier);
    logoutReq.setNameID(nameId);

    SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();

    if (sessionIndexStr != null) {
        sessionIndex.setSessionIndex(sessionIndexStr);
    } else {
        sessionIndex.setSessionIndex(UUID.randomUUID().toString());
    }

    logoutReq.getSessionIndexes().add(sessionIndex);
    logoutReq.setReason("Single Logout");

    return logoutReq;
}
 
Example 12
Source File: SingleLogoutMessageBuilder.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public LogoutRequest buildLogoutRequest(String subject, String sessionId, String reason, String destination,
                                        String nameIDFormat, String tenantDomain, String
                                                requestsigningAlgorithmUri, String requestDigestAlgoUri) throws
        IdentityException {

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

    logoutReq.setID(SAMLSSOUtil.createID());

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

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

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

    if (destination != null) {
        logoutReq.setDestination(destination);
    }

    logoutReq.setReason(reason);

    int tenantId;
    if (StringUtils.isEmpty(tenantDomain) || "null".equals(tenantDomain)) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        tenantId = MultitenantConstants.SUPER_TENANT_ID;
    } else {
        try {
            tenantId = SAMLSSOUtil.getRealmService().getTenantManager().getTenantId(tenantDomain);
        } catch (UserStoreException e) {
            throw IdentityException.error("Error occurred while retrieving tenant id from tenant domain", e);
        }

        if(MultitenantConstants.INVALID_TENANT_ID == tenantId) {
            throw IdentityException.error("Invalid tenant domain - '" + tenantDomain + "'" );
        }
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        SAMLSSOUtil.setSignature(logoutReq, requestsigningAlgorithmUri, requestDigestAlgoUri, new
                SignKeyDataHolder(null));
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

    return logoutReq;
}