Search in sources :

Example 21 with Response

use of org.opensaml.saml.saml2.ecp.Response in project ddf by codice.

the class IdpEndpoint method doSoapLogin.

@POST
@Path("/login")
@Consumes({ "text/xml", "application/soap+xml" })
public Response doSoapLogin(InputStream body, @Context HttpServletRequest request) {
    if (!request.isSecure()) {
        throw new IllegalArgumentException("Authn Request must use TLS.");
    }
    SoapBinding soapBinding = new SoapBinding(systemCrypto, serviceProviders);
    try {
        String bodyStr = IOUtils.toString(body);
        AuthnRequest authnRequest = soapBinding.decoder().decodeRequest(bodyStr);
        String relayState = ((SoapRequestDecoder) soapBinding.decoder()).decodeRelayState(bodyStr);
        soapBinding.validator().validateRelayState(relayState);
        soapBinding.validator().validateAuthnRequest(authnRequest, bodyStr, null, null, null, strictSignature);
        boolean hasCookie = hasValidCookie(request, authnRequest.isForceAuthn());
        AuthObj authObj = determineAuthMethod(bodyStr, authnRequest);
        org.opensaml.saml.saml2.core.Response response = handleLogin(authnRequest, authObj.method, request, authObj, authnRequest.isPassive(), hasCookie);
        Response samlpResponse = soapBinding.creator().getSamlpResponse(relayState, authnRequest, response, null, soapMessage);
        samlpResponse.getHeaders().put("SOAPAction", Collections.singletonList("http://www.oasis-open.org/committees/security"));
        return samlpResponse;
    } catch (IOException e) {
        LOGGER.debug("Unable to decode SOAP AuthN Request", e);
    } catch (SimpleSign.SignatureException e) {
        LOGGER.debug("Unable to validate signature.", e);
    } catch (ValidationException e) {
        LOGGER.debug("Unable to validate request.", e);
    } catch (SecurityServiceException e) {
        LOGGER.debug("Unable to authenticate user.", e);
    } catch (WSSecurityException | IllegalArgumentException e) {
        LOGGER.debug("Bad request.", e);
    }
    return null;
}
Also used : SecurityServiceException(ddf.security.service.SecurityServiceException) ValidationException(ddf.security.samlp.ValidationException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SoapRequestDecoder(org.codice.ddf.security.idp.binding.soap.SoapRequestDecoder) IOException(java.io.IOException) SoapBinding(org.codice.ddf.security.idp.binding.soap.SoapBinding) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) Response(javax.ws.rs.core.Response) SimpleSign(ddf.security.samlp.SimpleSign) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 22 with Response

use of org.opensaml.saml.saml2.ecp.Response in project ddf by codice.

the class IdpEndpoint method createCookie.

private NewCookie createCookie(HttpServletRequest request, org.opensaml.saml.saml2.core.Response response) {
    LOGGER.debug("Creating cookie for user.");
    if (response.getAssertions() != null && response.getAssertions().size() > 0) {
        Assertion assertion = response.getAssertions().get(0);
        if (assertion != null) {
            UUID uuid = UUID.randomUUID();
            cookieCache.cacheSamlAssertion(uuid.toString(), assertion.getDOM());
            URL url;
            try {
                url = new URL(request.getRequestURL().toString());
                LOGGER.debug("Returning new cookie for user.");
                return new NewCookie(COOKIE, uuid.toString(), SERVICES_IDP_PATH, url.getHost(), NewCookie.DEFAULT_VERSION, null, -1, null, true, true);
            } catch (MalformedURLException e) {
                LOGGER.info("Unable to create session cookie. Client will need to log in again.", e);
            }
        }
    }
    return null;
}
Also used : MalformedURLException(java.net.MalformedURLException) SecurityAssertion(ddf.security.assertion.SecurityAssertion) Assertion(org.opensaml.saml.saml2.core.Assertion) UUID(java.util.UUID) URL(java.net.URL) NewCookie(javax.ws.rs.core.NewCookie)

Example 23 with Response

use of org.opensaml.saml.saml2.ecp.Response in project ddf by codice.

the class IdpEndpoint method retrieveMetadata.

@GET
@Path("/login/metadata")
@Produces("application/xml")
public Response retrieveMetadata() throws WSSecurityException, CertificateEncodingException {
    List<String> nameIdFormats = new ArrayList<>();
    nameIdFormats.add(SAML2Constants.NAMEID_FORMAT_PERSISTENT);
    nameIdFormats.add(SAML2Constants.NAMEID_FORMAT_UNSPECIFIED);
    nameIdFormats.add(SAML2Constants.NAMEID_FORMAT_X509_SUBJECT_NAME);
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(systemCrypto.getSignatureCrypto().getDefaultX509Identifier());
    X509Certificate[] certs = systemCrypto.getSignatureCrypto().getX509Certificates(cryptoType);
    X509Certificate issuerCert = null;
    if (certs != null && certs.length > 0) {
        issuerCert = certs[0];
    }
    cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(systemCrypto.getEncryptionCrypto().getDefaultX509Identifier());
    certs = systemCrypto.getEncryptionCrypto().getX509Certificates(cryptoType);
    X509Certificate encryptionCert = null;
    if (certs != null && certs.length > 0) {
        encryptionCert = certs[0];
    }
    EntityDescriptor entityDescriptor = SamlProtocol.createIdpMetadata(SystemBaseUrl.constructUrl("/idp/login", true), Base64.getEncoder().encodeToString(issuerCert != null ? issuerCert.getEncoded() : new byte[0]), Base64.getEncoder().encodeToString(encryptionCert != null ? encryptionCert.getEncoded() : new byte[0]), nameIdFormats, SystemBaseUrl.constructUrl("/idp/login", true), SystemBaseUrl.constructUrl("/idp/login", true), SystemBaseUrl.constructUrl("/idp/logout", true));
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    return Response.ok(DOM2Writer.nodeToString(OpenSAMLUtil.toDom(entityDescriptor, doc, false))).build();
}
Also used : EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) ArrayList(java.util.ArrayList) CryptoType(org.apache.wss4j.common.crypto.CryptoType) Document(org.w3c.dom.Document) X509Certificate(java.security.cert.X509Certificate) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 24 with Response

use of org.opensaml.saml.saml2.ecp.Response in project ddf by codice.

the class LogoutRequestServiceTest method testGetLogoutRequestInvalidSignature.

@Test
public void testGetLogoutRequestInvalidSignature() throws Exception {
    String signature = "signature";
    String signatureAlgorithm = "sha1";
    String relayState = UUID.randomUUID().toString();
    String deflatedSamlRequest = RestSecurity.deflateAndBase64Encode("deflatedSamlRequest");
    LogoutRequest logoutRequest = mock(LogoutRequest.class);
    when(logoutMessage.extractSamlLogoutRequest(eq("deflatedSamlRequest"))).thenReturn(logoutRequest);
    LogoutRequestService lrs = new LogoutRequestService(simpleSign, idpMetadata, relayStates);
    lrs.setEncryptionService(encryptionService);
    lrs.setLogOutPageTimeOut(LOGOUT_PAGE_TIMEOUT);
    lrs.setLogoutMessage(logoutMessage);
    lrs.setRequest(request);
    lrs.setSessionFactory(sessionFactory);
    lrs.init();
    Response response = lrs.getLogoutRequest(deflatedSamlRequest, null, relayState, signatureAlgorithm, signature);
    assertEquals(Response.Status.SEE_OTHER.getStatusCode(), response.getStatus());
    String msg = "Unable to validate".replaceAll(" ", "+");
    assertTrue("Expected message containing " + msg, response.getLocation().getQuery().contains(msg));
}
Also used : LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) Response(javax.ws.rs.core.Response) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.junit.Test)

Example 25 with Response

use of org.opensaml.saml.saml2.ecp.Response in project ddf by codice.

the class LogoutRequestServiceTest method testSendLogoutRequestInvalidNumberOfParams.

@Test
public void testSendLogoutRequestInvalidNumberOfParams() throws Exception {
    String encryptedNameIdWithTime = nameId + "\n" + time;
    when(encryptionService.decrypt(any(String.class))).thenReturn(nameId);
    Response response = logoutRequestService.sendLogoutRequest(encryptedNameIdWithTime);
    assertEquals(Response.Status.SEE_OTHER.getStatusCode(), response.getStatus());
    String msg = "Failed to decrypt logout request params. Invalid number of params.".replaceAll(" ", "+");
    assertTrue("Expected message containing " + msg, response.getLocation().getQuery().contains(msg));
}
Also used : LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) Response(javax.ws.rs.core.Response) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.junit.Test)

Aggregations

Response (org.opensaml.saml.saml2.core.Response)82 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)41 Test (org.junit.Test)41 Element (org.w3c.dom.Element)35 Document (org.w3c.dom.Document)31 DateTime (org.joda.time.DateTime)30 Status (org.opensaml.saml.saml2.core.Status)30 Response (javax.ws.rs.core.Response)29 ResponseBuilder.aResponse (uk.gov.ida.saml.core.test.builders.ResponseBuilder.aResponse)27 LogoutResponse (org.opensaml.saml.saml2.core.LogoutResponse)25 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)23 SamlValidationResponse (uk.gov.ida.saml.core.validation.SamlValidationResponse)21 Matchers.anyString (org.mockito.Matchers.anyString)20 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)18 SubjectConfirmationDataBean (org.apache.wss4j.common.saml.bean.SubjectConfirmationDataBean)18 Assertion (org.opensaml.saml.saml2.core.Assertion)18 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)18 InputStream (java.io.InputStream)15 IOException (java.io.IOException)13 Crypto (org.apache.wss4j.common.crypto.Crypto)13