Java Code Examples for org.opensaml.saml2.core.Assertion

The following examples show how to use org.opensaml.saml2.core.Assertion. These examples are extracted from open source projects. 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: carbon-identity   Source File: DefaultResponseBuilder.java    License: 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 2
Source Project: lams   Source File: AssertionSpecValidator.java    License: 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 3
Source Project: lams   Source File: AssertionUnmarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {
    Assertion assertion = (Assertion) samlObject;

    if (attribute.getLocalName().equals(Assertion.VERSION_ATTRIB_NAME)) {
        assertion.setVersion(SAMLVersion.valueOf(attribute.getValue()));
    } else if (attribute.getLocalName().equals(Assertion.ISSUE_INSTANT_ATTRIB_NAME)
            && !DatatypeHelper.isEmpty(attribute.getValue())) {
        assertion.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()));
    } else if (attribute.getLocalName().equals(Assertion.ID_ATTRIB_NAME)) {
        assertion.setID(attribute.getValue());
        attribute.getOwnerElement().setIdAttributeNode(attribute, true);
    } else {
        super.processAttribute(samlObject, attribute);
    }
}
 
Example 4
Source Project: lams   Source File: EvidenceUnmarshaller.java    License: 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 5
Source Project: lams   Source File: AssertionMarshaller.java    License: 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 6
Source Project: carbon-identity   Source File: DefaultSAML2SSOManager.java    License: 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 7
Source Project: carbon-identity   Source File: SAML2SSOAuthenticator.java    License: Apache License 2.0 6 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 8
Source Project: carbon-identity   Source File: DefaultSSOEncrypter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public EncryptedAssertion doEncryptedAssertion(Assertion assertion, X509Credential cred, String alias, String encryptionAlgorithm) throws IdentityException {
    try {

        Credential symmetricCredential = SecurityHelper.getSimpleCredential(
                SecurityHelper.generateSymmetricKey(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256));

        EncryptionParameters encParams = new EncryptionParameters();
        encParams.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256);
        encParams.setEncryptionCredential(symmetricCredential);

        KeyEncryptionParameters keyEncryptionParameters = new KeyEncryptionParameters();
        keyEncryptionParameters.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);
        keyEncryptionParameters.setEncryptionCredential(cred);

        Encrypter encrypter = new Encrypter(encParams, keyEncryptionParameters);
        encrypter.setKeyPlacement(Encrypter.KeyPlacement.INLINE);

        EncryptedAssertion encrypted = encrypter.encrypt(assertion);
        return encrypted;
    } catch (Exception e) {
        throw IdentityException.error("Error while Encrypting Assertion", e);
    }
}
 
Example 9
Source Project: carbon-identity   Source File: SAML2SSOManager.java    License: 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 10
Source Project: carbon-identity   Source File: LoggedInSessionBean.java    License: 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 11
Source Project: saml-sdk-java   Source File: SAMLClient.java    License: 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 12
Source Project: saml-generator   Source 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 13
Source Project: secure-data-service   Source File: SamlHelper.java    License: 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 14
Source Project: secure-data-service   Source File: SamlHelper.java    License: 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 15
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException {
    EntityAttributes entityAttrs = (EntityAttributes) parentObject;

    if (childObject instanceof Attribute) {
        entityAttrs.getAttributes().add((Attribute) childObject);
    } else if (childObject instanceof Assertion) {
        entityAttrs.getAssertions().add((Assertion) childObject);
    } else {
        super.processChildElement(parentObject, childObject);
    }
}
 
Example 16
Source Project: lams   Source File: BaseSAML2MessageDecoder.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extract information from a SAML StatusResponse message.
 * 
 * @param messageContext current message context
 * @param statusResponse the SAML message to process
 * 
 * @throws MessageDecodingException thrown if the response issuer has a format other than {@link NameIDType#ENTITY}
 *             or, if the response does not contain an issuer, if the contained assertions contain issuers that are
 *             not of {@link NameIDType#ENTITY} format or if the assertions contain different issuers
 */
protected void extractResponseInfo(SAMLMessageContext messageContext, StatusResponseType statusResponse)
        throws MessageDecodingException {

    messageContext.setInboundSAMLMessageId(statusResponse.getID());
    messageContext.setInboundSAMLMessageIssueInstant(statusResponse.getIssueInstant());

    // If response doesn't have an issuer, look at the first
    // enclosed assertion
    String messageIssuer = null;
    if (statusResponse.getIssuer() != null) {
        messageIssuer = extractEntityId(statusResponse.getIssuer());
    } else if (statusResponse instanceof Response) {
        List<Assertion> assertions = ((Response) statusResponse).getAssertions();
        if (assertions != null && assertions.size() > 0) {
            log.info("Status response message had no issuer, attempting to extract issuer from enclosed Assertion(s)");
            String assertionIssuer;
            for (Assertion assertion : assertions) {
                if (assertion != null && assertion.getIssuer() != null) {
                    assertionIssuer = extractEntityId(assertion.getIssuer());
                    if (messageIssuer != null && !messageIssuer.equals(assertionIssuer)) {
                        throw new MessageDecodingException("SAML 2 assertions, within response "
                                + statusResponse.getID() + " contain different issuer IDs");
                    }
                    messageIssuer = assertionIssuer;
                }
            }
        }
    }

    messageContext.setInboundMessageIssuer(messageIssuer);
}
 
Example 17
Source Project: lams   Source File: Decrypter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypt the specified EncryptedAssertion.
 * 
 * @param encryptedAssertion the EncryptedAssertion to decrypt
 * @return an Assertion 
 * @throws DecryptionException thrown when decryption generates an error
 */
public Assertion decrypt(EncryptedAssertion encryptedAssertion) throws DecryptionException {
    SAMLObject samlObject = decryptData(encryptedAssertion);
    if (! (samlObject instanceof Assertion)) {
        throw new DecryptionException("Decrypted SAMLObject was not an instance of Assertion");
    }
    return (Assertion) samlObject;
}
 
Example 18
@SuppressWarnings("unchecked")
@Test
public void processArtifactBindingValidRequest() throws URISyntaxException {
    setRealm(false);

    Mockito.when(edOrg.getEntityId()).thenReturn(targetEdorg);
    Mockito.when(realm.getEntityId()).thenReturn("My Realm");
    Mockito.when(repo.findOne(eq("realm"), any(NeutralQuery.class))).thenReturn(realm);
    Mockito.when(repo.findById(eq("realm"), anyString())).thenReturn(realm);
    Mockito.when(repo.findOne(eq(EntityNames.EDUCATION_ORGANIZATION), any(NeutralQuery.class))).thenReturn(edOrg);

    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    UriInfo uriInfo = Mockito.mock(UriInfo.class);

    URI uri = new URI(issuerString);

    Mockito.when(uriInfo.getRequestUri()).thenReturn(uri);
    Mockito.when(uriInfo.getAbsolutePath()).thenReturn(uri);

    Mockito.when(request.getParameter("SAMLart")).thenReturn("AAQAAjh3bwgbBZ+LiIx3/RVwDGy0aRUu+xxuNtTZVbFofgZZVCKJQwQNQ7Q=");
    Mockito.when(request.getParameter("RelayState")).thenReturn("My Realm");

    Assertion assertion = createAssertion("01/01/2011", "01/10/2011", issuerString);
    Mockito.when(samlHelper.getAssertion(Mockito.any(org.opensaml.saml2.core.Response.class), Mockito.any(KeyStore.PrivateKeyEntry.class))).thenReturn(assertion);

    Response response = Mockito.mock(Response.class);

    SamlFederationResource spyResource = Mockito.spy(resource);
    Mockito.doReturn(response).when(spyResource).authenticateUser(Mockito.any(LinkedMultiValueMap.class), Mockito.any(Entity.class), Mockito.anyString(),
            Mockito.anyString(), Mockito.any(Entity.class), Mockito.any(URI.class));

    Response resResponse = spyResource.processArtifactBinding(request, uriInfo);
    Assert.assertEquals(response, resResponse);
}
 
Example 19
Source Project: secure-data-service   Source File: SamlHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPeerDecryption() {
    Resource peerAssertionResource = new ClassPathResource("saml/peerEncryptedAssertion.xml");
    EncryptedAssertion encAssertion = createAssertion(peerAssertionResource);

    Assertion assertion = samlHelper.decryptAssertion(encAssertion, encryptPKEntry);
    verifyAssertion(assertion);
}
 
Example 20
Source Project: lams   Source File: ResponseUnmarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    Response resp = (Response) parentSAMLObject;

    if (childSAMLObject instanceof Assertion) {
        resp.getAssertions().add((Assertion) childSAMLObject);
    } else if (childSAMLObject instanceof EncryptedAssertion) {
        resp.getEncryptedAssertions().add((EncryptedAssertion) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example 21
private SAMLCredential stubSAMLCredential() {
	return new SAMLCredential(
			mock(NameID.class),
			mock(Assertion.class),
			"entity",
			"local");
}
 
Example 22
/**
 * Creates an OAuth2 access token from a SAML bearer assertion
 * POST /api/v1/auth/token
 */
private static String postOAuth2AccessToken(PrivateKey idpPrivateKey) throws Exception {
    
    System.out.println("\n***************************************************************");
    String urlString = BASE_URL + "/api/v1/auth/token";
    System.out.println("POST " + urlString);
  
    URL requestUrl = new URL(urlString);
    
    Assertion assertion = buildSAML2Assertion(clientSecret == null);
    String signedAssertion = signAssertion(assertion, idpPrivateKey);
    System.out.println("Signed assertion: " + signedAssertion);
    
    List<Pair<String,String>> postParams = new ArrayList<Pair<String,String>>();
    postParams.add(new Pair<String,String>("client_id", URLEncoder.encode(CLIENT_KEY, "UTF-8")));
    if (clientSecret != null) {
        postParams.add(new Pair<String,String>("client_secret", URLEncoder.encode(clientSecret, "UTF-8")));
    }
    postParams.add(new Pair<String,String>("grant_type", URLEncoder.encode(SAML2_BEARER_GRANT_TYPE, "UTF-8")));
    String base64SamlAssertion = new String(Base64.encodeBytes(signedAssertion.getBytes(), Base64.DONT_BREAK_LINES));
   
    postParams.add(new Pair<String,String>("assertion", URLEncoder.encode(base64SamlAssertion, "UTF-8")));   
   
    String requestBody = joinPostBodyParams(postParams);
    System.out.println("Request body: " + requestBody);
     
    return postOAuth2AccessTokenHelper(requestUrl,requestBody);
}
 
Example 23
@Test
public void processArtifactBindingInvalidCondition() throws URISyntaxException {
    setRealm(false);
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    UriInfo uriInfo = Mockito.mock(UriInfo.class);

    URI uri = new URI(issuerString);

    Mockito.when(uriInfo.getRequestUri()).thenReturn(uri);
    Mockito.when(uriInfo.getAbsolutePath()).thenReturn(uri);

    Mockito.when(request.getParameter("SAMLart")).thenReturn("AAQAAjh3bwgbBZ+LiIx3/RVwDGy0aRUu+xxuNtTZVbFofgZZVCKJQwQNQ7Q=");
    Mockito.when(request.getParameter("RelayState")).thenReturn("My Realm");

    List<Assertion> assertions = new ArrayList<Assertion>();

    DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");
    DateTime datetime = DateTime.now();
    datetime = datetime.plusMonths(2) ;
    Assertion assertion = createAssertion(datetime.toString(fmt), "01/10/2011", issuerString);
    assertions.add(assertion);
    Mockito.when(samlHelper.getAssertion(Mockito.any(org.opensaml.saml2.core.Response.class), Mockito.any(KeyStore.PrivateKeyEntry.class))).thenReturn(assertion);

    //invalid condition
    expectedException.expect(APIAccessDeniedException.class);
    expectedException.expectMessage("Authorization could not be verified.");
    resource.processArtifactBinding(request, uriInfo);

    //null subject
    Mockito.when(assertion.getSubject()).thenReturn(null);
    resource.processArtifactBinding(request, uriInfo);

    //invalid subject
    assertions.clear();
    assertions.add(createAssertion("01/10/2011", datetime.toString(fmt),  issuerString));
    resource.processArtifactBinding(request, uriInfo);
}
 
Example 24
/**
 * Creates an OAuth2 access token from a SAML bearer assertion
 * POST /api/v1/auth/token
 */
private static String postOAuth2AccessToken(
        String baseUrl,
        String clientKey,
        String clientSecret,
        String idpId,
        String subjectNameId,
        String subjectNameIdFormat,
        String subjectNameIdQualifier,
        PrivateKey idpPrivateKey) throws Exception {
    
    System.out.println("\n***************************************************************");
    String urlString = baseUrl + "/api/v1/auth/token";
    System.out.println("POST " + urlString);
  
    URL requestUrl = new URL(urlString);
    
    Assertion assertion = buildSAML2Assertion(baseUrl, subjectNameId, subjectNameIdFormat, subjectNameIdQualifier, idpId, clientKey, clientSecret == null);
    String signedAssertion = signAssertion(assertion, idpPrivateKey);
    System.out.println("Signed assertion: " + signedAssertion);
    
    List<Pair<String,String>> postParams = new ArrayList<Pair<String,String>>();
    postParams.add(new Pair<String,String>("client_id", URLEncoder.encode(clientKey, "UTF-8")));
    if (clientSecret != null) {
        postParams.add(new Pair<String,String>("client_secret", URLEncoder.encode(clientSecret, "UTF-8")));
    }
    postParams.add(new Pair<String,String>("grant_type", URLEncoder.encode(SAML2_BEARER_GRANT_TYPE, "UTF-8")));
    String base64SamlAssertion = new String(Base64.encodeBytes(signedAssertion.getBytes(), Base64.DONT_BREAK_LINES));
   
    postParams.add(new Pair<String,String>("assertion", URLEncoder.encode(base64SamlAssertion, "UTF-8")));   
   
    String requestBody = joinPostBodyParams(postParams);
    System.out.println("Request body: " + requestBody);
     
    return postOAuth2AccessTokenHelper(requestUrl,requestBody);
}
 
Example 25
Source Project: carbon-identity   Source File: DefaultSAML2SSOManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Validate the AudienceRestriction of SAML2 Response
 *
 * @param assertion SAML2 Assertion
 * @return validity
 */
private void validateAudienceRestriction(Assertion assertion) throws SAMLSSOException {

    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 (CollectionUtils.isNotEmpty(audienceRestriction.getAudiences())) {
                        boolean audienceFound = false;
                        for (Audience audience : audienceRestriction.getAudiences()) {
                            if (properties.get(IdentityApplicationConstants.Authenticator.SAML2SSO.SP_ENTITY_ID)
                                    .equals(audience.getAudienceURI())) {
                                audienceFound = true;
                                break;
                            }
                        }
                        if (!audienceFound) {
                            throw new SAMLSSOException("SAML Assertion Audience Restriction validation failed");
                        }
                    } else {
                        throw new SAMLSSOException("SAML Response's AudienceRestriction doesn't contain Audiences");
                    }
                }
            } else {
                throw new SAMLSSOException("SAML Response doesn't contain AudienceRestrictions");
            }
        } else {
            throw new SAMLSSOException("SAML Response doesn't contain Conditions");
        }
    }
}
 
Example 26
Source Project: carbon-identity   Source File: SAML2SSOUIAuthenticator.java    License: 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 27
Source Project: carbon-identity   Source File: SAML2SSOUIAuthenticator.java    License: 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 28
Source Project: carbon-identity   Source File: Util.java    License: 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 Project: carbon-identity   Source File: Util.java    License: 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 30
Source Project: carbon-identity   Source File: Util.java    License: 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();
}