org.opensaml.saml2.core.Assertion Java Examples

The following examples show how to use org.opensaml.saml2.core.Assertion. 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: SAML2SSOAuthenticator.java    From carbon-identity with Apache License 2.0 8 votes vote down vote up
/**
 * Get the Assertion from the SAML2 Response
 *
 * @param response SAML2 Response
 * @return assertion
 */
private Assertion getAssertionFromResponse(Response response) {
    Assertion assertion = null;
    if (response != null) {
        List<Assertion> assertions = response.getAssertions();
        if (assertions != null && assertions.size() > 0) {
            assertion = assertions.get(0);
        } else {
            log.error("SAML2 Response doesn't contain Assertions");
        }
    }
    return assertion;
}
 
Example #2
Source File: DefaultResponseBuilder.java    From carbon-identity with Apache License 2.0 7 votes vote down vote up
public Response buildResponse(SAMLSSOAuthnReqDTO authReqDTO, Assertion assertion)
        throws IdentityException {

    if (log.isDebugEnabled()) {
        log.debug("Building SAML Response for the consumer '"
                + authReqDTO.getAssertionConsumerURL() + "'");
    }
    Response response = new org.opensaml.saml2.core.impl.ResponseBuilder().buildObject();
    response.setIssuer(SAMLSSOUtil.getIssuer());
    response.setID(SAMLSSOUtil.createID());
    response.setInResponseTo(authReqDTO.getId());
    response.setDestination(authReqDTO.getAssertionConsumerURL());
    response.setStatus(buildStatus(SAMLSSOConstants.StatusCodes.SUCCESS_CODE, null));
    response.setVersion(SAMLVersion.VERSION_20);
    DateTime issueInstant = new DateTime();
    response.setIssueInstant(issueInstant);
    response.getAssertions().add(assertion);
    if (authReqDTO.isDoSignResponse()) {
        SAMLSSOUtil.setSignature(response, authReqDTO.getSigningAlgorithmUri(), authReqDTO.getDigestAlgorithmUri
                (), new SignKeyDataHolder(authReqDTO.getUser().getAuthenticatedSubjectIdentifier()));
    }
    return response;
}
 
Example #3
Source File: SamlHelper.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) {
    BasicX509Credential decryptionCredential = new BasicX509Credential();

    decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey());

    StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential);

    ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver();
    keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver());
    keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver());
    keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver());

    Decrypter decrypter = new Decrypter(null, resolver, keyResolver);
    decrypter.setRootInNewDocument(true);
    Assertion assertion = null;
    try {
        assertion = decrypter.decrypt(encryptedAssertion);
    } catch (DecryptionException e) {
        raiseSamlValidationError("Unable to decrypt SAML assertion", null);
    }
    return assertion;
}
 
Example #4
Source File: DefaultSAML2SSOManager.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private Map<ClaimMapping, String> getAssertionStatements(Assertion assertion) {

        Map<ClaimMapping, String> results = new HashMap<ClaimMapping, String>();

        if (assertion != null) {

            List<AttributeStatement> attributeStatementList = assertion.getAttributeStatements();

            if (attributeStatementList != null) {
                for (AttributeStatement statement : attributeStatementList) {
                    List<Attribute> attributesList = statement.getAttributes();
                    for (Attribute attribute : attributesList) {
                        Element value = attribute.getAttributeValues().get(0)
                                .getDOM();
                        String attributeValue = value.getTextContent();
                        results.put(ClaimMapping.build(attribute.getName(),
                                attribute.getName(), null, false), attributeValue);
                    }
                }
            }
        }
        return results;
    }
 
Example #5
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getAssertionStatements(Assertion assertion) {

        Map<String, String> results = new HashMap<String, String>();

        if (assertion != null && assertion.getAttributeStatements() != null) {

            List<AttributeStatement> attributeStatementList = assertion.getAttributeStatements();


            for (AttributeStatement statement : attributeStatementList) {
                List<Attribute> attributesList = statement.getAttributes();
                for (Attribute attribute : attributesList) {
                    Element value = attribute.getAttributeValues().get(0).getDOM();
                    String attributeValue = value.getTextContent();
                    results.put(attribute.getName(), attributeValue);
                }
            }

        }
        return results;
    }
 
Example #6
Source File: SamlHelper.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Validates that the certificate in the saml assertion is valid and trusted.
 * @param samlResponse
 *      SAML response form the IdP.
 * @param assertion
 *      SAML assertion
 */
public void validateSignature(Response samlResponse, Assertion assertion)  {
    if(samlResponse.getSignature() == null && assertion.getSignature() == null) {
        raiseSamlValidationError("Invalid SAML message: Response is not signed", null);
    }

    String issuer = samlResponse.getIssuer().getValue();

    if(samlResponse.getSignature() != null) {
        validateFormatAndCertificate(samlResponse.getSignature(), samlResponse.getDOM(), issuer);
    }

    if(assertion.getSignature() != null) {
        validateFormatAndCertificate(assertion.getSignature(), assertion.getDOM(), issuer);
    }
}
 
Example #7
Source File: AssertionMarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException {
    Assertion assertion = (Assertion) samlObject;

    if (assertion.getVersion() != null) {
        domElement.setAttributeNS(null, Assertion.VERSION_ATTRIB_NAME, assertion.getVersion().toString());
    }

    if (assertion.getIssueInstant() != null) {
        String issueInstantStr = Configuration.getSAMLDateFormatter().print(assertion.getIssueInstant());
        domElement.setAttributeNS(null, Assertion.ISSUE_INSTANT_ATTRIB_NAME, issueInstantStr);
    }

    if (assertion.getID() != null) {
        domElement.setAttributeNS(null, Assertion.ID_ATTRIB_NAME, assertion.getID());
        domElement.setIdAttributeNS(null, Assertion.ID_ATTRIB_NAME, true);
    }
}
 
Example #8
Source File: EvidenceUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException {
    Evidence evidence = (Evidence) parentObject;

    if (childObject instanceof AssertionIDRef) {
        evidence.getAssertionIDReferences().add((AssertionIDRef) childObject);
    } else if (childObject instanceof AssertionURIRef) {
        evidence.getAssertionURIReferences().add((AssertionURIRef) childObject);
    } else if (childObject instanceof Assertion) {
        evidence.getAssertions().add((Assertion) childObject);
    } else if (childObject instanceof EncryptedAssertion) {
        evidence.getEncryptedAssertions().add((EncryptedAssertion) childObject);
    } else {
        super.processChildElement(parentObject, childObject);
    }
}
 
Example #9
Source File: AssertionSpecValidator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example #10
Source File: SamlAssertionProducer.java    From saml-generator with 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 #11
Source File: LoggedInSessionBean.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void readObject(java.io.ObjectInputStream stream)
        throws IOException, ClassNotFoundException, SSOAgentException {

    subjectId = (String) stream.readObject();

    responseString = (String) stream.readObject();
    if (responseString != null && !EMPTY_STRING.equals(responseString)) {
        response = (Response) SSOAgentUtils.unmarshall(responseString);
    }

    assertionString = (String) stream.readObject();
    if (responseString != null && !EMPTY_STRING.equals(assertionString)) {
        assertion = (Assertion) SSOAgentUtils.unmarshall(assertionString);
    }

    sessionIndex = (String) stream.readObject();
    String accessTokenResponseBeanString = (String) stream.readObject();
    if (!EMPTY_STRING.equals(accessTokenResponseBeanString)) {
        accessTokenResponseBean = accessTokenResponseBean.deSerialize(accessTokenResponseBeanString);
    } else {
        accessTokenResponseBean = null;
    }
    subjectAttributes = (Map) stream.readObject();
}
 
Example #12
Source File: SAMLClient.java    From saml-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Decrypt an assertion using the privkey stored in SPConfig.
 */
private Assertion decrypt(EncryptedAssertion encrypted)
    throws DecryptionException
{
    if (spConfig.getPrivateKey() == null)
        throw new DecryptionException("Encrypted assertion found but no SP key available");
    BasicCredential cred = new BasicCredential();
    cred.setPrivateKey(spConfig.getPrivateKey());
    StaticKeyInfoCredentialResolver resolver =
        new StaticKeyInfoCredentialResolver(cred);
    Decrypter decrypter =
        new Decrypter(null, resolver, new InlineEncryptedKeyResolver());
    decrypter.setRootInNewDocument(true);

    return decrypter.decrypt(encrypted);
}
 
Example #13
Source File: SAMLUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static String getValueFromAssertions(final List<Assertion> assertions, final String attributeKey) {
    if (assertions == null || attributeKey == null) {
        return null;
    }
    for (Assertion assertion : assertions) {
        String value = getValueFromAttributeStatements(assertion.getAttributeStatements(), attributeKey);
        if (value != null) {
            return value;
        }
    }
    return null;
}
 
Example #14
Source File: SamlHelper.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param samlAssertion
 * @return
 */
public LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion) {
    LinkedMultiValueMap<String, String> attributes = new LinkedMultiValueMap<String, String>();

    AttributeStatement attributeStatement = samlAssertion.getAttributeStatements().get(0);

    for (org.opensaml.saml2.core.Attribute attribute : attributeStatement.getAttributes()) {
        String samlAttributeName = attribute.getName();
        List<XMLObject> valueObjects = attribute.getAttributeValues();
        for (XMLObject valueXmlObject : valueObjects) {
            attributes.add(samlAttributeName, valueXmlObject.getDOM().getTextContent());
        }
    }
    return attributes;
}
 
Example #15
Source File: SamlAssertionProducer.java    From saml-generator with Apache License 2.0 5 votes vote down vote up
private Response createResponse(final DateTime issueDate, Issuer issuer, Status status, Assertion assertion) {
	ResponseBuilder responseBuilder = new ResponseBuilder();
	Response response = responseBuilder.buildObject();
	response.setID(UUID.randomUUID().toString());
	response.setIssueInstant(issueDate);
	response.setVersion(SAMLVersion.VERSION_20);
	response.setIssuer(issuer);
	response.setStatus(status);
	response.getAssertions().add(assertion);
	return response;
}
 
Example #16
Source File: SAML2SSOAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the AudienceRestriction of SAML2 XMLObject
 *
 * @param xmlObject Unmarshalled SAML2 Response
 * @return validity
 */
private boolean validateAudienceRestrictionInXML(XMLObject xmlObject) {
    if (xmlObject instanceof Response) {
        return validateAudienceRestrictionInResponse((Response) xmlObject);
    } else if (xmlObject instanceof Assertion) {
        return validateAudienceRestrictionInAssertion((Assertion) xmlObject);
    } else {
        log.error("Only Response and Assertion objects are validated in this authendicator");
        return false;
    }
}
 
Example #17
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 #18
Source File: SAMLSSORelyingPartyObject.java    From carbon-commons with 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 #19
Source File: SamlHelper.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry) {
    Assertion assertion;
    if (isAssertionEncrypted(samlResponse)) {
        assertion = decryptAssertion(samlResponse.getEncryptedAssertions().get(0), keystoreEntry);
    } else {
        assertion = samlResponse.getAssertions().get(0);
    }
    return assertion;
}
 
Example #20
Source File: SamlHelperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testInlineDecryption() {
    Resource inlineAssertionResource = new ClassPathResource("saml/inlineEncryptedAssertion.xml");
    EncryptedAssertion encAssertion = createAssertion(inlineAssertionResource);

    Assertion assertion = samlHelper.decryptAssertion(encAssertion, encryptPKEntry);
    verifyAssertion(assertion);
}
 
Example #21
Source File: SAML2SSOAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get roles from the SAML2 Response
 *
 * @param response SAML2 Response
 * @return roles array
 */
private String[] getRolesFromResponse(Response response) {
    List<Assertion> assertions = response.getAssertions();
    Assertion assertion = null;
    if (assertions != null && assertions.size() > 0) {
        assertion = assertions.get(0);
        return getRolesFromAssertion(assertion);
    }
    return null;
}
 
Example #22
Source File: SAML2SSOAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get roles from the SAML2 XMLObject
 *
 * @param xmlObject SAML2 XMLObject
 * @return String array of roles
 */
private String[] getRoles(XMLObject xmlObject) {
    String[] arrRoles = {};
    if (xmlObject instanceof Response) {
        return getRolesFromResponse((Response) xmlObject);
    } else if (xmlObject instanceof Assertion) {
        return getRolesFromAssertion((Assertion) xmlObject);
    } else {
        return arrRoles;
    }
}
 
Example #23
Source File: SAML2SSOAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the AudienceRestriction of SAML2 Assertion
 *
 * @param assertion SAML2 Assertion
 * @return validity
 */
public boolean validateAudienceRestrictionInAssertion(Assertion assertion) {
    if (assertion != null) {
        Conditions conditions = assertion.getConditions();
        if (conditions != null) {
            List<AudienceRestriction> audienceRestrictions = conditions.getAudienceRestrictions();
            if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) {
                for (AudienceRestriction audienceRestriction : audienceRestrictions) {
                    if (audienceRestriction.getAudiences() != null && audienceRestriction.getAudiences().size() > 0) {
                        for (Audience audience : audienceRestriction.getAudiences()) {
                            String spId = org.wso2.carbon.identity.authenticator.saml2.sso.common.Util.getServiceProviderId();
                            if (spId == null) {
                                org.wso2.carbon.identity.authenticator.saml2.sso.common.Util.initSSOConfigParams();
                                spId = org.wso2.carbon.identity.authenticator.saml2.sso.common.Util.getServiceProviderId();
                            }
                            if (spId != null) {
                                if (spId.equals(audience.getAudienceURI())) {
                                    return true;
                                }
                            } else {
                                log.warn("No SAML2 service provider ID defined.");
                            }
                        }
                    } else {
                        log.warn("SAML2 Response's AudienceRestriction doesn't contain Audiences");
                    }
                }
            } else {
                log.error("SAML2 Response doesn't contain AudienceRestrictions");
            }
        } else {
            log.error("SAML2 Response doesn't contain Conditions");
        }
    }
    return false;
}
 
Example #24
Source File: SAML2SSOUIAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get the username from the SAML2 Response
 *
 * @param response SAML2 Response
 * @return username username contained in the SAML Response
 */
private String getUsernameFromResponse(Response response) {
    List<Assertion> assertions = response.getAssertions();
    Assertion assertion = null;
    if (assertions != null && assertions.size() > 0) {
        // There can be only one assertion in a SAML Response, so get the first one
        assertion = assertions.get(0);
        return assertion.getSubject().getNameID().getValue();
    }
    return null;
}
 
Example #25
Source File: SAML2SSOAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the signature of a SAML2 Assertion
 *
 * @param assertion  SAML2 Assertion
 * @param domainName domain name of the subject
 * @return true, if signature is valid.
 */
private boolean validateSignature(Assertion assertion, String domainName) {
    boolean isSignatureValid = false;
    if (assertion.getSignature() == null) {
        log.error("SAML Assertion is not signed. So authentication process will be terminated.");
    } else {
        isSignatureValid = validateSignature(assertion.getSignature(), domainName);
    }
    return isSignatureValid;
}
 
Example #26
Source File: SAML2SSOAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the signature of a SAML2 XMLObject
 *
 * @param xmlObject  SAML2 XMLObject
 * @param domainName domain name of the subject
 * @return true, if signature is valid.
 */
private boolean validateSignature(XMLObject xmlObject, String domainName) {
    if (xmlObject instanceof Response) {
        return validateSignature((Response) xmlObject, domainName);
    } else if (xmlObject instanceof Assertion) {
        return validateSignature((Assertion) xmlObject, domainName);
    } else {
        log.error("Only Response and Assertion objects are validated in this authendicator");
        return false;
    }
}
 
Example #27
Source File: Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get the username from the SAML2 Response
 *
 * @param response SAML2 Response
 * @return username username contained in the SAML Response
 */
public static String getUsernameFromResponse(Response response) {

    List<Assertion> assertions = response.getAssertions();
    Assertion assertion = null;
    if (assertions != null && assertions.size() > 0) {
        // There can be only one assertion in a SAML Response, so get the
        // first one
        assertion = assertions.get(0);
        return getUsernameFromAssertion(assertion);

    }
    return null;
}
 
Example #28
Source File: Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get the username from the SAML2 XMLObject
 *
 * @param xmlObject SAML2 XMLObject
 * @return username
 */
public static String getUsername(XMLObject xmlObject) {

    if (xmlObject instanceof Response) {
        return getUsernameFromResponse((Response) xmlObject);
    } else if (xmlObject instanceof Assertion) {
        return getUsernameFromAssertion((Assertion) xmlObject);
    } else {
        return null;
    }
}
 
Example #29
Source File: SAML2SSOUIAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Read the session index from a Response
 *
 * @param response SAML Response
 * @return Session Index value contained in the Response
 */
private String getSessionIndexFromResponse(Response response) {
    List<Assertion> assertions = response.getAssertions();
    String sessionIndex = null;
    if (assertions != null && assertions.size() > 0) {
        // There can be only one assertion in a SAML Response, so get the first one
        List<AuthnStatement> authnStatements = assertions.get(0).getAuthnStatements();
        if (authnStatements != null && authnStatements.size() > 0) {
            // There can be only one authentication stmt inside the SAML assertion of a SAML Response
            AuthnStatement authStmt = authnStatements.get(0);
            sessionIndex = authStmt.getSessionIndex();
        }
    }
    return sessionIndex;
}
 
Example #30
Source File: Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get the username from the SAML2 Assertion
 *
 * @param assertion SAML2 assertion
 * @return username
 */
public static String getUsernameFromAssertion(Assertion assertion) {

    String loginAttributeName = getLoginAttributeName();

    if (loginAttributeName != null) {
        // There can be multiple AttributeStatements in Assertion
        List<AttributeStatement> attributeStatements = assertion
                .getAttributeStatements();
        if (attributeStatements != null) {
            for (AttributeStatement attributeStatement : attributeStatements) {
                // There can be multiple Attributes in a
                // attributeStatement
                List<Attribute> attributes = attributeStatement
                        .getAttributes();
                if (attributes != null) {
                    for (Attribute attribute : attributes) {
                        String attributeName = attribute.getDOM()
                                .getAttribute("Name");
                        if (attributeName.equals(loginAttributeName)) {
                            List<XMLObject> attributeValues = attribute
                                    .getAttributeValues();
                            // There can be multiple attribute values in
                            // a attribute, but get the first one
                            return attributeValues.get(0).getDOM()
                                    .getTextContent();
                        }
                    }
                }
            }
        }
    }
    return assertion.getSubject().getNameID().getValue();
}