org.opensaml.common.SAMLVersion Java Examples

The following examples show how to use org.opensaml.common.SAMLVersion. 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: 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 #2
Source File: SAML1CallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            callback.setSamlVersion(SAMLVersion.VERSION_11);
            SubjectBean subjectBean = 
                new SubjectBean(
                    subjectName, subjectQualifier, confirmationMethod
                );
            if (SAML1Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
                try {
                    KeyInfoBean keyInfo = createKeyInfo();
                    subjectBean.setKeyInfo(keyInfo);
                } catch (Exception ex) {
                    throw new IOException("Problem creating KeyInfo: " +  ex.getMessage());
                }
            }
            createAndSetStatement(subjectBean, callback);
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example #3
Source File: AssertionUnmarshaller.java    From lams with 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 (Assertion.ID_ATTRIB_NAME.equals(attribute.getLocalName())) {
        assertion.setID(attribute.getValue());
    } else if (Assertion.ISSUER_ATTRIB_NAME.equals(attribute.getLocalName())) {
        assertion.setIssuer(attribute.getValue());
    } else if (Assertion.ISSUEINSTANT_ATTRIB_NAME.equals(attribute.getLocalName())
            && !DatatypeHelper.isEmpty(attribute.getValue())) {
        assertion.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()));
    } else if (Assertion.MINORVERSION_ATTRIB_NAME.equals(attribute.getLocalName())) {
        if (attribute.getValue().equals("0")) {
            assertion.setVersion(SAMLVersion.VERSION_10);
        } else {
            assertion.setVersion(SAMLVersion.VERSION_11);
        }
    } else {
        super.processAttribute(samlObject, attribute);
    }
}
 
Example #4
Source File: RequestAbstractTypeUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {
    RequestAbstractType req = (RequestAbstractType) samlObject;

    if (attribute.getLocalName().equals(RequestAbstractType.VERSION_ATTRIB_NAME)) {
        req.setVersion(SAMLVersion.valueOf(attribute.getValue()));
    } else if (attribute.getLocalName().equals(RequestAbstractType.ID_ATTRIB_NAME)) {
        req.setID(attribute.getValue());
        attribute.getOwnerElement().setIdAttributeNode(attribute, true);
    } else if (attribute.getLocalName().equals(RequestAbstractType.ISSUE_INSTANT_ATTRIB_NAME)
            && !DatatypeHelper.isEmpty(attribute.getValue())) {
        req.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()));
    } else if (attribute.getLocalName().equals(RequestAbstractType.DESTINATION_ATTRIB_NAME)) {
        req.setDestination(attribute.getValue());
    } else if (attribute.getLocalName().equals(RequestAbstractType.CONSENT_ATTRIB_NAME)) {
        req.setConsent(attribute.getValue());
    } else {
        super.processAttribute(samlObject, attribute);
    }
}
 
Example #5
Source File: StatusResponseTypeUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {
    StatusResponseType sr = (StatusResponseType) samlObject;

    if (attribute.getLocalName().equals(StatusResponseType.VERSION_ATTRIB_NAME)) {
        sr.setVersion(SAMLVersion.valueOf(attribute.getValue()));
    } else if (attribute.getLocalName().equals(StatusResponseType.ID_ATTRIB_NAME)) {
        sr.setID(attribute.getValue());
        attribute.getOwnerElement().setIdAttributeNode(attribute, true);
    } else if (attribute.getLocalName().equals(StatusResponseType.IN_RESPONSE_TO_ATTRIB_NAME)) {
        sr.setInResponseTo(attribute.getValue());
    } else if (attribute.getLocalName().equals(StatusResponseType.ISSUE_INSTANT_ATTRIB_NAME)
            && !DatatypeHelper.isEmpty(attribute.getValue())) {
        sr.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()));
    } else if (attribute.getLocalName().equals(StatusResponseType.DESTINATION_ATTRIB_NAME)) {
        sr.setDestination(attribute.getValue());
    } else if (attribute.getLocalName().equals(StatusResponseType.CONSENT_ATTRIB_NAME)) {
        sr.setConsent(attribute.getValue());
    } else {
        super.processAttribute(samlObject, attribute);
    }
}
 
Example #6
Source File: ErrorResponseBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Build the error response
 *
 * @param inResponseToID
 * @param statusCodes
 * @param statusMsg
 * @return
 */
public Response buildResponse(String inResponseToID, List<String> statusCodes, String statusMsg,
                              String destination) throws IdentityException {
    if (statusCodes == null || statusCodes.isEmpty()) {
        throw IdentityException.error("No Status Values");
    }
    response.setIssuer(SAMLSSOUtil.getIssuer());
    Status status = new StatusBuilder().buildObject();
    StatusCode statusCode = null;
    for (String statCode : statusCodes) {
        statusCode = buildStatusCode(statCode, statusCode);
    }
    status.setStatusCode(statusCode);
    buildStatusMsg(status, statusMsg);
    response.setStatus(status);
    response.setVersion(SAMLVersion.VERSION_20);
    response.setID(SAMLSSOUtil.createID());
    if (inResponseToID != null) {
        response.setInResponseTo(inResponseToID);
    }
    if (destination != null) {
        response.setDestination(destination);
    }
    response.setIssueInstant(new DateTime());
    return response;
}
 
Example #7
Source File: SAML1CallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            callback.setSamlVersion(SAMLVersion.VERSION_11);
            SubjectBean subjectBean = 
                new SubjectBean(
                    subjectName, subjectQualifier, confirmationMethod
                );
            if (SAML1Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
                try {
                    KeyInfoBean keyInfo = createKeyInfo();
                    subjectBean.setKeyInfo(keyInfo);
                } catch (Exception ex) {
                    throw new IOException("Problem creating KeyInfo: " +  ex.getMessage());
                }
            }
            createAndSetStatement(subjectBean, callback);
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example #8
Source File: SAML2CallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            callback.setSamlVersion(SAMLVersion.VERSION_20);
            SubjectBean subjectBean = 
                new SubjectBean(
                    subjectName, subjectQualifier, confirmationMethod
                );
            if (SAML2Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
                try {
                    KeyInfoBean keyInfo = createKeyInfo();
                    subjectBean.setKeyInfo(keyInfo);
                } catch (Exception ex) {
                    throw new IOException("Problem creating KeyInfo: " +  ex.getMessage());
                }
            }
            callback.setSubject(subjectBean);
            createAndSetStatement(null, callback);
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example #9
Source File: ErrorResponseBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static String generateErrorneousResponse() {
    Response response = new ResponseBuilder().buildObject();
    response.setIssuer(getIssuer());
    response.setStatus(buildStatus());
    response.setVersion(SAMLVersion.VERSION_20);
    response.setID(UIDGenerator.generateUID());

    try {
        return encode(marshall(response));
    } catch (IdentityException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while encoding.", e);
        }
        return null;
    }
}
 
Example #10
Source File: SAML2CallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            callback.setSamlVersion(SAMLVersion.VERSION_20);
            SubjectBean subjectBean = 
                new SubjectBean(
                    subjectName, subjectQualifier, confirmationMethod
                );
            if (SAML2Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
                try {
                    KeyInfoBean keyInfo = createKeyInfo();
                    subjectBean.setKeyInfo(keyInfo);
                } catch (Exception ex) {
                    throw new IOException("Problem creating KeyInfo: " +  ex.getMessage());
                }
            }
            callback.setSubject(subjectBean);
            createAndSetStatement(null, callback);
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example #11
Source File: SAML1CallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            callback.setSamlVersion(SAMLVersion.VERSION_11);
            SubjectBean subjectBean = 
                new SubjectBean(
                    subjectName, subjectQualifier, confirmationMethod
                );
            if (SAML1Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
                try {
                    KeyInfoBean keyInfo = createKeyInfo();
                    subjectBean.setKeyInfo(keyInfo);
                } catch (Exception ex) {
                    throw new IOException("Problem creating KeyInfo: " +  ex.getMessage());
                }
            }
            createAndSetStatement(subjectBean, callback);
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example #12
Source File: SAML2CallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            callback.setSamlVersion(SAMLVersion.VERSION_20);
            SubjectBean subjectBean = 
                new SubjectBean(
                    subjectName, subjectQualifier, confirmationMethod
                );
            if (SAML2Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
                try {
                    KeyInfoBean keyInfo = createKeyInfo();
                    subjectBean.setKeyInfo(keyInfo);
                } catch (Exception ex) {
                    throw new IOException("Problem creating KeyInfo: " +  ex.getMessage());
                }
            }
            callback.setSubject(subjectBean);
            createAndSetStatement(null, callback);
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example #13
Source File: SAML1CallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            callback.setSamlVersion(SAMLVersion.VERSION_11);
            SubjectBean subjectBean = 
                new SubjectBean(
                    subjectName, subjectQualifier, confirmationMethod
                );
            if (SAML1Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
                try {
                    KeyInfoBean keyInfo = createKeyInfo();
                    subjectBean.setKeyInfo(keyInfo);
                } catch (Exception ex) {
                    throw new IOException("Problem creating KeyInfo: " +  ex.getMessage());
                }
            }
            createAndSetStatement(subjectBean, callback);
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example #14
Source File: SAML2CallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            callback.setSamlVersion(SAMLVersion.VERSION_20);
            SubjectBean subjectBean = 
                new SubjectBean(
                    subjectName, subjectQualifier, confirmationMethod
                );
            if (SAML2Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
                try {
                    KeyInfoBean keyInfo = createKeyInfo();
                    subjectBean.setKeyInfo(keyInfo);
                } catch (Exception ex) {
                    throw new IOException("Problem creating KeyInfo: " +  ex.getMessage());
                }
            }
            callback.setSubject(subjectBean);
            createAndSetStatement(null, callback);
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example #15
Source File: AbstractSaml10ResponseView.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
protected void renderMergedOutputModel(
        final Map<String, Object> model, final HttpServletRequest request, final HttpServletResponse response) throws Exception {

    response.setCharacterEncoding(this.encoding);

    final WebApplicationService service = this.samlArgumentExtractor.extractService(request);
    final String serviceId = service != null ? service.getId() : "UNKNOWN";

    try {
        final Response samlResponse = newSamlObject(Response.class);
        samlResponse.setID(generateId());
        samlResponse.setIssueInstant(new DateTime());
        samlResponse.setVersion(SAMLVersion.VERSION_11);
        samlResponse.setRecipient(serviceId);
        if (service instanceof SamlService) {
            final SamlService samlService = (SamlService) service;

            if (samlService.getRequestID() != null) {
                samlResponse.setInResponseTo(samlService.getRequestID());
            }
        }
        prepareResponse(samlResponse, model);

        final BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext();
        messageContext.setOutboundMessageTransport(new HttpServletResponseAdapter(response, request.isSecure()));
        messageContext.setOutboundSAMLMessage(samlResponse);
        this.encoder.encode(messageContext);
    } catch (final Exception e) {
        logger.error("Error generating SAML response for service {}.", serviceId);
        throw e;
    }
}
 
Example #16
Source File: SAMLUtils.java    From steady with Apache License 2.0 5 votes vote down vote up
public static List<String> parseRolesInAssertion(Object assertion, String roleAttributeName) {
    if (((AssertionWrapper) assertion).getSamlVersion().equals(SAMLVersion.VERSION_20)) {
        return parseRolesInAssertion(((AssertionWrapper)assertion).getSaml2(), roleAttributeName);
    } else {
        return parseRolesInAssertion(((AssertionWrapper)assertion).getSaml1(), roleAttributeName);
    }
}
 
Example #17
Source File: RequestAbstractTypeSchemaValidator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validates the Version attribute.
 * 
 * @param request request to validate
 * @throws ValidationException if invalid
 */
protected void validateVersion(RequestAbstractType request) throws ValidationException {
    if (request.getVersion() == null) {
        throw new ValidationException("Version attribute must not be null");
    }
    if (request.getVersion().toString() != SAMLVersion.VERSION_20.toString()) {
        throw new ValidationException("Wrong SAML Version");
    }
}
 
Example #18
Source File: SamlTokenPolicyValidator.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Check the policy version against the received assertion
 */
private boolean checkVersion(SamlToken samlToken, AssertionWrapper assertionWrapper) {
    if ((samlToken.isUseSamlVersion11Profile10()
        || samlToken.isUseSamlVersion11Profile11())
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_11) {
        return false;
    } else if (samlToken.isUseSamlVersion20Profile11()
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_20) {
        return false;
    }
    return true;
}
 
Example #19
Source File: SAMLUtils.java    From steady with Apache License 2.0 5 votes vote down vote up
public static List<String> parseRolesInAssertion(Object assertion, String roleAttributeName) {
    if (((AssertionWrapper) assertion).getSamlVersion().equals(SAMLVersion.VERSION_20)) {
        return parseRolesInAssertion(((AssertionWrapper)assertion).getSaml2(), roleAttributeName);
    } else {
        return parseRolesInAssertion(((AssertionWrapper)assertion).getSaml1(), roleAttributeName);
    }
}
 
Example #20
Source File: SamlTokenPolicyValidator.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Check the policy version against the received assertion
 */
private boolean checkVersion(SamlToken samlToken, AssertionWrapper assertionWrapper) {
    if ((samlToken.isUseSamlVersion11Profile10()
        || samlToken.isUseSamlVersion11Profile11())
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_11) {
        return false;
    } else if (samlToken.isUseSamlVersion20Profile11()
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_20) {
        return false;
    }
    return true;
}
 
Example #21
Source File: StatusResponseTypeSchemaValidator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validates the Version attribute
 * 
 * @param response
 * @throws ValidationException
 */
protected void validateVersion(StatusResponse response) throws ValidationException {
    if (response.getVersion() == null)
        throw new ValidationException("Version attribute must not be null");
    if (response.getVersion().toString() != SAMLVersion.VERSION_20.toString())
        throw new ValidationException("Wrong SAML Version");
}
 
Example #22
Source File: SamlTokenPolicyValidator.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Check the policy version against the received assertion
 */
private boolean checkVersion(SamlToken samlToken, AssertionWrapper assertionWrapper) {
    if ((samlToken.isUseSamlVersion11Profile10()
        || samlToken.isUseSamlVersion11Profile11())
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_11) {
        return false;
    } else if (samlToken.isUseSamlVersion20Profile11()
        && assertionWrapper.getSamlVersion() != SAMLVersion.VERSION_20) {
        return false;
    }
    return true;
}
 
Example #23
Source File: AssertionUnmarshaller.java    From lams with GNU General Public License v2.0 5 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 #24
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 #25
Source File: SAMLResponseBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Build SAML response using IdP configuration & user name
 *
 * @param ssoIdPConfigs
 * @param userName
 * @return SAML Response object
 * @throws IdentityException
 */
public Response buildSAMLResponse(SAMLSSOServiceProviderDO ssoIdPConfigs, String userName)
        throws IdentityException {
    if (log.isDebugEnabled()) {
        log.debug("Building SAML Response for the consumer '" +
                ssoIdPConfigs.getAssertionConsumerUrl() + "'");
    }
    Response response = new org.opensaml.saml2.core.impl.ResponseBuilder().buildObject();
    response.setIssuer(SAMLSSOUtil.getIssuer());
    response.setID(SAMLSSOUtil.createID());
    response.setDestination(ssoIdPConfigs.getAssertionConsumerUrl());
    response.setStatus(buildStatus(SAMLSSOConstants.StatusCodes.SUCCESS_CODE, null));
    response.setVersion(SAMLVersion.VERSION_20);
    DateTime issueInstant = new DateTime();
    DateTime notOnOrAfter =
            new DateTime(issueInstant.getMillis() +
                    SAMLSSOUtil.getSAMLResponseValidityPeriod() * 60 *
                            1000);
    response.setIssueInstant(issueInstant);
    Assertion assertion = buildSAMLAssertion(ssoIdPConfigs, notOnOrAfter, userName);
    if (ssoIdPConfigs.isDoEnableEncryptedAssertion()) {
        String domainName = MultitenantUtils.getTenantDomain(userName);
        String alias = ssoIdPConfigs.getCertAlias();
        if (alias != null) {
            EncryptedAssertion encryptedAssertion =
                    SAMLSSOUtil.setEncryptedAssertion(assertion,
                            EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256,
                            alias,
                            domainName);
            response.getEncryptedAssertions().add(encryptedAssertion);
        }
    } else {
        response.getAssertions().add(assertion);
    }
    if (ssoIdPConfigs.isDoSignResponse()) {
        SAMLSSOUtil.setSignature(response, ssoIdPConfigs.getSigningAlgorithmUri(), ssoIdPConfigs
                .getDigestAlgorithmUri(), new SignKeyDataHolder(userName));
    }
    return response;
}
 
Example #26
Source File: AuthReqBuilder.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Generate an authentication request.
 *
 * @return AuthnRequest Object
 * @throws Exception error when bootstrapping
 */
public AuthnRequest buildAuthenticationRequest(String issuerId) throws Exception {
    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( issuerId));
    authnRequest.setNameIDPolicy(buildNameIDPolicy());
    return authnRequest;
}
 
Example #27
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 #28
Source File: SAMLUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static AuthnRequest buildAuthnRequestObject(final String authnId, final String spId, final String idpUrl, final String consumerUrl) {
    // Issuer object
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(spId);

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

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

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

    return authnRequest;
}
 
Example #29
Source File: SAMLUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static LogoutRequest buildLogoutRequest(String logoutUrl, String spId, String nameIdString) {
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(spId);
    NameID nameID = new NameIDBuilder().buildObject();
    nameID.setValue(nameIdString);
    LogoutRequest logoutRequest = new LogoutRequestBuilder().buildObject();
    logoutRequest.setID(generateSecureRandomId());
    logoutRequest.setDestination(logoutUrl);
    logoutRequest.setVersion(SAMLVersion.VERSION_20);
    logoutRequest.setIssueInstant(new DateTime());
    logoutRequest.setIssuer(issuer);
    logoutRequest.setNameID(nameID);
    return logoutRequest;
}
 
Example #30
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;
}