org.opensaml.saml2.core.Issuer Java Examples

The following examples show how to use org.opensaml.saml2.core.Issuer. 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: StatusResponseTypeUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    StatusResponseType sr = (StatusResponseType) parentSAMLObject;

    if (childSAMLObject instanceof Issuer) {
        sr.setIssuer((Issuer) childSAMLObject);
    } else if (childSAMLObject instanceof Signature) {
        sr.setSignature((Signature) childSAMLObject);
    } else if (childSAMLObject instanceof Extensions) {
        sr.setExtensions((Extensions) childSAMLObject);
    } else if (childSAMLObject instanceof Status) {
        sr.setStatus((Status) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #2
Source File: ArtifactResponseUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    ArtifactResponse artifactResponse = (ArtifactResponse) parentSAMLObject;

    if (childSAMLObject instanceof Issuer) {
        artifactResponse.setIssuer((Issuer) childSAMLObject);
    } else if (childSAMLObject instanceof Signature) {
        artifactResponse.setSignature((Signature) childSAMLObject);
    } else if (childSAMLObject instanceof Extensions) {
        artifactResponse.setExtensions((Extensions) childSAMLObject);
    } else if (childSAMLObject instanceof Status) {
        artifactResponse.setStatus((Status) childSAMLObject);
    } else {
        artifactResponse.setMessage((SAMLObject) childSAMLObject);
    }
}
 
Example #3
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 #4
Source File: AssertionUnmarshaller.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 {
    Assertion assertion = (Assertion) parentObject;

    if (childObject instanceof Issuer) {
        assertion.setIssuer((Issuer) childObject);
    } else if (childObject instanceof Signature) {
        assertion.setSignature((Signature) childObject);
    } else if (childObject instanceof Subject) {
        assertion.setSubject((Subject) childObject);
    } else if (childObject instanceof Conditions) {
        assertion.setConditions((Conditions) childObject);
    } else if (childObject instanceof Advice) {
        assertion.setAdvice((Advice) childObject);
    } else if (childObject instanceof Statement) {
        assertion.getStatements().add((Statement) childObject);
    } else {
        super.processChildElement(parentObject, childObject);
    }
}
 
Example #5
Source File: RequestAbstractTypeUnmarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    RequestAbstractType req = (RequestAbstractType) parentSAMLObject;

    if (childSAMLObject instanceof Issuer) {
        req.setIssuer((Issuer) childSAMLObject);
    } else if (childSAMLObject instanceof Signature) {
        req.setSignature((Signature) childSAMLObject);
    } else if (childSAMLObject instanceof Extensions) {
        req.setExtensions((Extensions) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #6
Source File: LogoutRequestBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Build the logout request
 *
 * @param subject name of the user
 * @param reason  reason for generating logout request.
 * @return LogoutRequest object
 * @throws Exception
 */
public LogoutRequest buildLogoutRequest(String subject, String reason, String sessionIndexStr) throws Exception {
    log.info("Building logout request");
    Util.doBootstrap();
    LogoutRequest logoutReq = new org.opensaml.saml2.core.impl.LogoutRequestBuilder().buildObject();
    logoutReq.setID(Util.createID());
    logoutReq.setDestination(Util.getIdentityProviderSSOServiceURL());

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

    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(Util.getServiceProviderId());
    logoutReq.setIssuer(issuer);

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

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

    logoutReq.setReason(reason);

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

    return logoutReq;
}
 
Example #7
Source File: AuthenticationRequestBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Build the issuer object
 *
 * @return Issuer object
 */
private static Issuer buildIssuer() {
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(Util.getServiceProviderId());
    return issuer;
}
 
Example #8
Source File: WSXACMLMessageReceiver.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Check for the validity of the issuer
 *
 * @param issuer :who makes the claims inside the Query
 * @return whether the issuer is valid
 */
private boolean validateIssuer(Issuer issuer) {

    boolean isValidated = false;

    if (issuer.getValue().equals("https://identity.carbon.wso2.org")
            && issuer.getSPProvidedID().equals("SPPProvierId")) {
        isValidated = true;
    }
    return isValidated;
}
 
Example #9
Source File: WSXACMLMessageReceiver.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Create the issuer object to be added
 *
 * @return : the issuer of the statements
 */
private static Issuer createIssuer() {

    IssuerBuilder issuer = (IssuerBuilder) org.opensaml.xml.Configuration.getBuilderFactory().
            getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuerObject = issuer.buildObject();
    issuerObject.setValue("https://identity.carbon.wso2.org");
    issuerObject.setSPProvidedID("SPPProvierId");
    return issuerObject;
}
 
Example #10
Source File: WSXACMLEntitlementServiceClient.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Create the issuer object to be added
 *
 * @return : the issuer of the statements
 */
private static Issuer createIssuer() {

    IssuerBuilder issuer = (IssuerBuilder) org.opensaml.xml.Configuration.getBuilderFactory().
            getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuerObject = issuer.buildObject();
    issuerObject.setValue(ISSUER_URL);
    issuerObject.setSPProvidedID("SPPProvierId");

    return issuerObject;
}
 
Example #11
Source File: WSXACMLEntitlementServiceClient.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Check for the validity of the issuer
 *
 * @param issuer :who makes the claims inside the Query
 * @return whether the issuer is valid
 */
private boolean validateIssuer(Issuer issuer) {

    boolean isValidated = false;
    if (ISSUER_URL.equals(issuer.getValue())
            && "SPPProvider".equals(issuer.getSPProvidedID())) {
        isValidated = true;
    }
    return isValidated;
}
 
Example #12
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected LogoutRequest buildLogoutRequest(String user, String sessionIdx) throws SSOAgentException {

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

        logoutReq.setID(SSOAgentUtils.createID());
        logoutReq.setDestination(ssoAgentConfig.getSAML2().getIdPURL());

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

        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer = issuerBuilder.buildObject();
        issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId());
        logoutReq.setIssuer(issuer);

        NameID nameId = new NameIDBuilder().buildObject();
        nameId.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:entity");
        nameId.setValue(user);
        logoutReq.setNameID(nameId);

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

        logoutReq.setReason("Single Logout");

        return logoutReq;
    }
 
Example #13
Source File: IssuerGenerator.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public Issuer generateIssuer() {
	///Issuer
	Issuer issuer = new IssuerBuilder().buildObject();

	issuer.setValue(issuerName);
	issuer.setFormat(NameIDType.ENTITY);
	
	return issuer;
}
 
Example #14
Source File: LogoutRequestBuilder.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Build the logout request
 * @param subject name of the user
 * @param reason reason for generating logout request.
 * @return LogoutRequest object
 */
public LogoutRequest buildLogoutRequest(String subject,String sessionIndexId, String reason,
                                        String issuerId) {
    Util.doBootstrap();
    LogoutRequest logoutReq = new org.opensaml.saml2.core.impl.LogoutRequestBuilder().buildObject();
    logoutReq.setID(Util.createID());

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

    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(issuerId);
    logoutReq.setIssuer(issuer);

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

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

    logoutReq.setReason(reason);

    return logoutReq;
}
 
Example #15
Source File: AuthReqBuilder.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Build the issuer object
 *
 * @return Issuer object
 */
private static Issuer buildIssuer(String issuerId) {
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(issuerId);
    return issuer;
}
 
Example #16
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 #17
Source File: SamlAssertionProducer.java    From saml-generator with Apache License 2.0 5 votes vote down vote up
private Issuer createIssuer(final String issuerName) {
	// create Issuer object
	IssuerBuilder issuerBuilder = new IssuerBuilder();
	Issuer issuer = issuerBuilder.buildObject();
	issuer.setValue(issuerName);	
	return issuer;
}
 
Example #18
Source File: SAML2LoginAPIAuthenticatorCmd.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
/**
 * If it fails to authenticate the user, the method gets the value from configuration
 * Saml2FailedLoginRedirectUrl; if the user configured an error URL then it redirects to that
 * URL, otherwise it throws the ServerApiException
 */
protected void whenFailToAuthenticateThrowExceptionOrRedirectToUrl(final Map<String, Object[]> params, final String responseType, final HttpServletResponse resp, Issuer issuer,
        UserAccount userAccount) throws IOException {
    if (userAccount == null || userAccount.getExternalEntity() == null || !samlAuthManager.isUserAuthorized(userAccount.getId(), issuer.getValue())) {
        String saml2RedirectUrl = saml2FailedLoginRedirectUrl.value();
        if (StringUtils.isBlank(saml2RedirectUrl)) {
            throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(),
                    "Your authenticated user is not authorized for SAML Single Sign-On, please contact your administrator", params, responseType));
        } else {
            resp.sendRedirect(saml2RedirectUrl);
        }
    }
}
 
Example #19
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 #20
Source File: BaseSAML2MessageDecoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extracts the entity ID from the SAML 2 Issuer.
 * 
 * @param issuer issuer to extract the entityID from
 * 
 * @return entity ID of the issuer
 * 
 * @throws MessageDecodingException thrown if the given issuer has a format other than {@link NameIDType#ENTITY}
 */
protected String extractEntityId(Issuer issuer) throws MessageDecodingException {
    if (issuer != null) {
        if (issuer.getFormat() == null || issuer.getFormat().equals(NameIDType.ENTITY)) {
            return issuer.getValue();
        } else {
            throw new MessageDecodingException("SAML 2 Issuer is not of ENTITY format type");
        }
    }

    return null;
}
 
Example #21
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 #22
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 #23
Source File: RequestUnmarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    Request request = (Request) parentSAMLObject;
    
    if (childSAMLObject instanceof Issuer) {
        request.setIssuer((Issuer) childSAMLObject);
    } else if (childSAMLObject instanceof IDPList) {
        request.setIDPList((IDPList) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #24
Source File: WSXACMLEntitlementServiceClient.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Create the issuer object to be added
 *
 * @return : the issuer of the statements
 */
private static Issuer createIssuer() {

    IssuerBuilder issuer = (IssuerBuilder) org.opensaml.xml.Configuration.getBuilderFactory().
            getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuerObject = issuer.buildObject();
    issuerObject.setValue(ISSUER_URL);
    issuerObject.setSPProvidedID("SPPProvierId");

    return issuerObject;
}
 
Example #25
Source File: WSXACMLEntitlementServiceClient.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Check for the validity of the issuer
 *
 * @param issuer :who makes the claims inside the Query
 * @return whether the issuer is valid
 */
private boolean validateIssuer(Issuer issuer) {

    boolean isValidated = false;
    if (ISSUER_URL.equals(issuer.getValue()) && "SPPProvider".equals(issuer.getSPProvidedID())) {
        isValidated = true;
    }
    return isValidated;
}
 
Example #26
Source File: SamlFederationResourceTest.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void init() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    MockitoAnnotations.initMocks(this);

    List<String> roles = new ArrayList<String>();
    roles.add("Educator");
    Entity entity = new MongoEntity("user", "My User", new HashMap<String, Object>(), new HashMap<String, Object>());
    principal = new SLIPrincipal();
    principal.setEntity(entity);
    principal.setRoles(roles);

    Mockito.when(transformer.apply(eq(realm), any(LinkedMultiValueMap.class)))
        .thenAnswer(new Answer<LinkedMultiValueMap<String, String>>() {
            @Override
            public LinkedMultiValueMap<String, String> answer(InvocationOnMock invocation) throws Throwable {
                return (LinkedMultiValueMap<String, String>) invocation.getArguments()[1];
            }
        });

    Map<String, List<String>> sliEdOrgRoleMap = new HashMap<String, List<String>>();
    sliEdOrgRoleMap.put("My EdOrg", roles);
    Mockito.when(edOrgRoleBuilder.buildValidStaffRoles(anyString(), anyString(), anyString(), eq(roles))).thenReturn(sliEdOrgRoleMap);


    ArtifactResolve artifactResolve = Mockito.mock(ArtifactResolve.class);
    Envelope envelope = Mockito.mock(Envelope.class);
    Mockito.when(artifactBindingHelper.generateArtifactResolveRequest(Mockito.anyString(), Mockito.any(KeyStore.PrivateKeyEntry.class), Mockito.anyString())).thenReturn(artifactResolve);

    Mockito.when(artifactBindingHelper.generateSOAPEnvelope(artifactResolve)).thenReturn(envelope);

    EnvelopeImpl response = Mockito.mock(EnvelopeImpl.class);
    Mockito.when(soapHelper.sendSOAPCommunication(Mockito.any(Envelope.class), Mockito.anyString(), Mockito.any(KeyStore.PrivateKeyEntry.class))).thenReturn(response);

    Mockito.when(samlHelper.parseToDoc(anyString())).thenReturn(doc);

    ArtifactResponse artifactResponse = Mockito.mock(ArtifactResponse.class);
    List<XMLObject> artifactResponses = new ArrayList<XMLObject>();
    artifactResponses.add(artifactResponse);
    Body body = Mockito.mock(Body.class);
    Mockito.when(response.getBody()).thenReturn(body);
    Mockito.when(body.getUnknownXMLObjects()).thenReturn(artifactResponses);

    samlResponse = Mockito.mock(org.opensaml.saml2.core.Response.class);

    issuer = Mockito.mock(Issuer.class);

    Mockito.when(artifactResponse.getMessage()).thenReturn(samlResponse);
    Mockito.when(samlResponse.hasChildren()).thenReturn(true);
    Mockito.when(samlResponse.getIssuer()).thenReturn(issuer);
    Mockito.when(issuer.getValue()).thenReturn(issuerString);

    Mockito.doNothing().when(samlHelper).validateSignature(Mockito.any(org.opensaml.saml2.core.Response.class), Mockito.any(Assertion.class));

    session = Mockito.mock(Entity.class);
    Mockito.when(sessionManager.getSessionForSamlId(Mockito.anyString())).thenReturn(session);


    Map<String, Object> sessionBody = new HashMap<String, Object>();
    sessionBody.put("requestedRealmId", "My Realm");
    sessionBody.put("edOrg", "My School");

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

    List<Map<String, Object>> appSessions = new ArrayList<Map<String, Object>>();

    appSessions.add(appSession);
    code.put("value", "testAuthorizationCode");
    sessionBody.put("appSession", appSessions);
    appSession.put("code", code);
    appSession.put("samlId", issuerString);

    Mockito.when(session.getBody()).thenReturn(sessionBody);
}
 
Example #27
Source File: SamlAssertionProducer.java    From saml-generator with Apache License 2.0 4 votes vote down vote up
public Response createSAMLResponse(final String subjectId, final DateTime authenticationTime,
		                           final String credentialType, final HashMap<String, List<String>> attributes, String issuer, Integer samlAssertionDays) {
	
	try {
		DefaultBootstrap.bootstrap();
		
		Signature signature = createSignature();
		Status status = createStatus();
		Issuer responseIssuer = null;
		Issuer assertionIssuer = null;
		Subject subject = null;
		AttributeStatement attributeStatement = null;
		
		if (issuer != null) {
			responseIssuer = createIssuer(issuer);
			assertionIssuer = createIssuer(issuer);
		}
		
		if (subjectId != null) {
			subject = createSubject(subjectId, samlAssertionDays);
		}
		
		if (attributes != null && attributes.size() != 0) {
			attributeStatement = createAttributeStatement(attributes);
		}
		
		AuthnStatement authnStatement = createAuthnStatement(authenticationTime);
		
		Assertion assertion = createAssertion(new DateTime(), subject, assertionIssuer, authnStatement, attributeStatement);
		
		Response response = createResponse(new DateTime(), responseIssuer, status, assertion);
		response.setSignature(signature);
		
		ResponseMarshaller marshaller = new ResponseMarshaller();
		Element element = marshaller.marshall(response);
		
		if (signature != null) {
			Signer.signObject(signature);
		}
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		XMLHelper.writeNode(element, baos);
	
		return response;
		
	} catch (Throwable t) {
		t.printStackTrace();
		return null;
	}
}
 
Example #28
Source File: SAMLClient.java    From saml-sdk-java with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private String createAuthnRequest(String requestId)
    throws SAMLException
{
    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    SAMLObjectBuilder<AuthnRequest> builder =
        (SAMLObjectBuilder<AuthnRequest>) builderFactory
        .getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);

    SAMLObjectBuilder<Issuer> issuerBuilder =
        (SAMLObjectBuilder<Issuer>) builderFactory
        .getBuilder(Issuer.DEFAULT_ELEMENT_NAME);

    AuthnRequest request = builder.buildObject();
    request.setAssertionConsumerServiceURL(spConfig.getAcs().toString());
    request.setDestination(idpConfig.getLoginUrl().toString());
    request.setIssueInstant(new DateTime());
    request.setID(requestId);

    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(spConfig.getEntityId());
    request.setIssuer(issuer);

    try {
        // samlobject to xml dom object
        Element elem = Configuration.getMarshallerFactory()
            .getMarshaller(request)
            .marshall(request);

        // and to a string...
        Document document = elem.getOwnerDocument();
        DOMImplementationLS domImplLS = (DOMImplementationLS) document
            .getImplementation();
        LSSerializer serializer = domImplLS.createLSSerializer();
        serializer.getDomConfig().setParameter("xml-declaration", false);
        return serializer.writeToString(elem);
    }
    catch (MarshallingException e) {
        throw new SAMLException(e);
    }
}
 
Example #29
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected AuthnRequest buildAuthnRequest(HttpServletRequest request) throws SSOAgentException {

        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer =
                issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion",
                        "Issuer", "samlp");
        issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId());

		/* NameIDPolicy */
        NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
        NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
        nameIdPolicy.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
        nameIdPolicy.setSPNameQualifier("Issuer");
        nameIdPolicy.setAllowCreate(true);

		/* AuthnContextClass */
        AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
        AuthnContextClassRef authnContextClassRef =
                authnContextClassRefBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion",
                        "AuthnContextClassRef",
                        "saml");
        authnContextClassRef.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

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

        DateTime issueInstant = new DateTime();

		/* Creation of AuthRequestObject */
        AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
        AuthnRequest authRequest =
                authRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol",
                        "AuthnRequest", "samlp");

        authRequest.setForceAuthn(ssoAgentConfig.getSAML2().isForceAuthn());
        authRequest.setIsPassive(ssoAgentConfig.getSAML2().isPassiveAuthn());
        authRequest.setIssueInstant(issueInstant);
        authRequest.setProtocolBinding(ssoAgentConfig.getSAML2().getHttpBinding());
        authRequest.setAssertionConsumerServiceURL(ssoAgentConfig.getSAML2().getACSURL());
        authRequest.setIssuer(issuer);
        authRequest.setNameIDPolicy(nameIdPolicy);
        authRequest.setRequestedAuthnContext(requestedAuthnContext);
        authRequest.setID(SSOAgentUtils.createID());
        authRequest.setVersion(SAMLVersion.VERSION_20);
        authRequest.setDestination(ssoAgentConfig.getSAML2().getIdPURL());
        if (request.getAttribute(Extensions.LOCAL_NAME) != null) {
            authRequest.setExtensions((Extensions) request.getAttribute(Extensions.LOCAL_NAME));
        }

		/* Requesting Attributes. This Index value is registered in the IDP */
        if (ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex() != null &&
                ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex().trim().length() > 0) {
            authRequest.setAttributeConsumingServiceIndex(Integer.parseInt(
                    ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex()));
        }

        return authRequest;
    }
 
Example #30
Source File: ErrorResponseBuilder.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private static Issuer getIssuer() {
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue("WSO2 Identity Server");
    issuer.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:entity");
    return issuer;
}