Search in sources :

Example 11 with LogoutRequest

use of org.opensaml.saml.saml2.core.LogoutRequest in project cloudstack by apache.

the class SAMLUtils method buildLogoutRequest.

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;
}
Also used : NameIDBuilder(org.opensaml.saml2.core.impl.NameIDBuilder) LogoutRequestBuilder(org.opensaml.saml2.core.impl.LogoutRequestBuilder) Issuer(org.opensaml.saml2.core.Issuer) NameID(org.opensaml.saml2.core.NameID) LogoutRequest(org.opensaml.saml2.core.LogoutRequest) IssuerBuilder(org.opensaml.saml2.core.impl.IssuerBuilder) DateTime(org.joda.time.DateTime)

Example 12 with LogoutRequest

use of org.opensaml.saml.saml2.core.LogoutRequest in project cloudstack by apache.

the class SAML2LogoutAPIAuthenticatorCmd method authenticate.

@Override
public String authenticate(String command, Map<String, Object[]> params, HttpSession session, InetAddress remoteAddress, String responseType, StringBuilder auditTrailSb, final HttpServletRequest req, final HttpServletResponse resp) throws ServerApiException {
    auditTrailSb.append("=== SAML SLO Logging out ===");
    LogoutCmdResponse response = new LogoutCmdResponse();
    response.setDescription("success");
    response.setResponseName(getCommandName());
    String responseString = ApiResponseSerializer.toSerializedString(response, responseType);
    if (session == null) {
        try {
            resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
        } catch (IOException ignored) {
            s_logger.info("[ignored] sending redirected failed.", ignored);
        }
        return responseString;
    }
    try {
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException | FactoryConfigurationError e) {
        s_logger.error("OpenSAML Bootstrapping error: " + e.getMessage());
        throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "OpenSAML Bootstrapping error while creating SP MetaData", params, responseType));
    }
    if (params != null && params.containsKey("SAMLResponse")) {
        try {
            final String samlResponse = ((String[]) params.get(SAMLPluginConstants.SAML_RESPONSE))[0];
            Response processedSAMLResponse = SAMLUtils.decodeSAMLResponse(samlResponse);
            String statusCode = processedSAMLResponse.getStatus().getStatusCode().getValue();
            if (!statusCode.equals(StatusCode.SUCCESS_URI)) {
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.INTERNAL_ERROR.getHttpCode(), "SAML SLO LogoutResponse status is not Success", params, responseType));
            }
        } catch (ConfigurationException | FactoryConfigurationError | ParserConfigurationException | SAXException | IOException | UnmarshallingException e) {
            s_logger.error("SAMLResponse processing error: " + e.getMessage());
        }
        try {
            resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
        } catch (IOException ignored) {
            s_logger.info("[ignored] second redirected sending failed.", ignored);
        }
        return responseString;
    }
    String idpId = (String) session.getAttribute(SAMLPluginConstants.SAML_IDPID);
    SAMLProviderMetadata idpMetadata = _samlAuthManager.getIdPMetadata(idpId);
    String nameId = (String) session.getAttribute(SAMLPluginConstants.SAML_NAMEID);
    if (idpMetadata == null || nameId == null || nameId.isEmpty()) {
        try {
            resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
        } catch (IOException ignored) {
            s_logger.info("[ignored] final redirected failed.", ignored);
        }
        return responseString;
    }
    LogoutRequest logoutRequest = SAMLUtils.buildLogoutRequest(idpMetadata.getSloUrl(), _samlAuthManager.getSPMetadata().getEntityId(), nameId);
    try {
        String redirectUrl = idpMetadata.getSloUrl() + "?SAMLRequest=" + SAMLUtils.encodeSAMLRequest(logoutRequest);
        resp.sendRedirect(redirectUrl);
    } catch (MarshallingException | IOException e) {
        s_logger.error("SAML SLO error: " + e.getMessage());
        throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "SAML Single Logout Error", params, responseType));
    }
    return responseString;
}
Also used : IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) Response(org.opensaml.saml2.core.Response) LogoutCmdResponse(org.apache.cloudstack.api.response.LogoutCmdResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServerApiException(org.apache.cloudstack.api.ServerApiException) MarshallingException(org.opensaml.xml.io.MarshallingException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ConfigurationException(org.opensaml.xml.ConfigurationException) LogoutRequest(org.opensaml.saml2.core.LogoutRequest) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAMLProviderMetadata(org.apache.cloudstack.saml.SAMLProviderMetadata) LogoutCmdResponse(org.apache.cloudstack.api.response.LogoutCmdResponse) FactoryConfigurationError(javax.xml.stream.FactoryConfigurationError) UnmarshallingException(org.opensaml.xml.io.UnmarshallingException)

Example 13 with LogoutRequest

use of org.opensaml.saml.saml2.core.LogoutRequest in project ddf by codice.

the class SamlProtocol method createLogoutRequest.

public static LogoutRequest createLogoutRequest(Issuer issuer, NameID nameId, String id) {
    LogoutRequest logoutRequest = logoutRequestBuilder.buildObject();
    logoutRequest.setID(id);
    logoutRequest.setIssuer(issuer);
    logoutRequest.setNameID(nameId);
    logoutRequest.setIssueInstant(DateTime.now());
    logoutRequest.setVersion(SAMLVersion.VERSION_20);
    return logoutRequest;
}
Also used : LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest)

Example 14 with LogoutRequest

use of org.opensaml.saml.saml2.core.LogoutRequest in project ddf by codice.

the class IdpEndpoint method processRedirectLogout.

/**
     * aka HTTP-Redirect
     *
     * @param samlRequest        the base64 encoded saml request
     * @param samlResponse       the base64 encoded saml response
     * @param relayState         the UUID that references the logout state
     * @param signatureAlgorithm this signing algorithm
     * @param signature          the signature of the url
     * @param request            the http servlet request
     * @return Response redirecting to an service provider
     * @throws WSSecurityException
     * @throws IdpException
     */
@Override
@GET
@Path("/logout")
public Response processRedirectLogout(@QueryParam(SAML_REQ) final String samlRequest, @QueryParam(SAML_RESPONSE) final String samlResponse, @QueryParam(RELAY_STATE) final String relayState, @QueryParam(SSOConstants.SIG_ALG) final String signatureAlgorithm, @QueryParam(SSOConstants.SIGNATURE) final String signature, @Context final HttpServletRequest request) throws WSSecurityException, IdpException {
    LogoutState logoutState = getLogoutState(request);
    Cookie cookie = getCookie(request);
    try {
        if (samlRequest != null) {
            LogoutRequest logoutRequest = logoutMessage.extractSamlLogoutRequest(RestSecurity.inflateBase64(samlRequest));
            validateRedirect(relayState, signatureAlgorithm, signature, request, samlRequest, logoutRequest, logoutRequest.getIssuer().getValue());
            return handleLogoutRequest(cookie, logoutState, logoutRequest, SamlProtocol.Binding.HTTP_REDIRECT, relayState);
        } else if (samlResponse != null) {
            LogoutResponse logoutResponse = logoutMessage.extractSamlLogoutResponse(RestSecurity.inflateBase64(samlResponse));
            String requestId = logoutState != null ? logoutState.getCurrentRequestId() : null;
            validateRedirect(relayState, signatureAlgorithm, signature, request, samlResponse, logoutResponse, logoutResponse.getIssuer().getValue(), requestId);
            return handleLogoutResponse(cookie, logoutState, logoutResponse, SamlProtocol.Binding.HTTP_REDIRECT);
        }
    } catch (XMLStreamException e) {
        throw new IdpException("Unable to parse Saml Object.", e);
    } catch (ValidationException e) {
        throw new IdpException("Unable to validate Saml Object", e);
    } catch (IOException e) {
        throw new IdpException("Unable to deflate Saml Object", e);
    }
    throw new IdpException("Could not process logout");
}
Also used : NewCookie(javax.ws.rs.core.NewCookie) Cookie(javax.servlet.http.Cookie) ValidationException(ddf.security.samlp.ValidationException) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) XMLStreamException(javax.xml.stream.XMLStreamException) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) IOException(java.io.IOException) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 15 with LogoutRequest

use of org.opensaml.saml.saml2.core.LogoutRequest in project ddf by codice.

the class LogoutRequestService method getLogoutRequest.

@GET
public Response getLogoutRequest(@QueryParam(SAML_REQUEST) String deflatedSamlRequest, @QueryParam(SAML_RESPONSE) String deflatedSamlResponse, @QueryParam(RELAY_STATE) String relayState, @QueryParam(SIG_ALG) String signatureAlgorithm, @QueryParam(SIGNATURE) String signature) {
    if (deflatedSamlRequest != null) {
        try {
            LogoutRequest logoutRequest = logoutMessage.extractSamlLogoutRequest(RestSecurity.inflateBase64(deflatedSamlRequest));
            if (logoutRequest == null) {
                String msg = "Unable to parse logout request.";
                return buildLogoutResponse(msg);
            }
            buildAndValidateSaml(deflatedSamlRequest, relayState, signatureAlgorithm, signature, logoutRequest);
            logout();
            String entityId = getEntityId();
            LogoutResponse logoutResponse = logoutMessage.buildLogoutResponse(entityId, StatusCode.SUCCESS, logoutRequest.getID());
            return getLogoutResponse(relayState, logoutResponse);
        } catch (IOException e) {
            String msg = "Unable to decode and inflate logout request.";
            LOGGER.info(msg, e);
            return buildLogoutResponse(msg);
        } catch (ValidationException e) {
            String msg = "Unable to validate";
            LOGGER.info(msg, e);
            return buildLogoutResponse(msg);
        } catch (WSSecurityException | XMLStreamException e) {
            String msg = "Unable to parse logout request.";
            LOGGER.info(msg, e);
            return buildLogoutResponse(msg);
        }
    } else {
        try {
            LogoutResponse logoutResponse = logoutMessage.extractSamlLogoutResponse(RestSecurity.inflateBase64(deflatedSamlResponse));
            if (logoutResponse == null) {
                String msg = "Unable to parse logout response.";
                LOGGER.debug(msg);
                return buildLogoutResponse(msg);
            }
            buildAndValidateSaml(deflatedSamlResponse, relayState, signatureAlgorithm, signature, logoutResponse);
            String nameId = "You";
            String decodedValue;
            if (relayState != null && (decodedValue = relayStates.decode(relayState)) != null) {
                nameId = decodedValue;
            }
            return buildLogoutResponse(nameId + " logged out successfully.");
        } catch (IOException e) {
            String msg = "Unable to decode and inflate logout response.";
            LOGGER.info(msg, e);
            return buildLogoutResponse(msg);
        } catch (ValidationException e) {
            String msg = "Unable to validate";
            LOGGER.info(msg, e);
            return buildLogoutResponse(msg);
        } catch (WSSecurityException | XMLStreamException e) {
            String msg = "Unable to parse logout response.";
            LOGGER.info(msg, e);
            return buildLogoutResponse(msg);
        }
    }
}
Also used : ValidationException(ddf.security.samlp.ValidationException) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) XMLStreamException(javax.xml.stream.XMLStreamException) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) GET(javax.ws.rs.GET)

Aggregations

LogoutRequest (org.opensaml.saml.saml2.core.LogoutRequest)13 LogoutResponse (org.opensaml.saml.saml2.core.LogoutResponse)10 IOException (java.io.IOException)6 Response (javax.ws.rs.core.Response)6 Test (org.junit.Test)6 ValidationException (ddf.security.samlp.ValidationException)5 XMLStreamException (javax.xml.stream.XMLStreamException)5 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)4 Matchers.anyString (org.mockito.Matchers.anyString)4 GET (javax.ws.rs.GET)3 Path (javax.ws.rs.Path)3 LogoutRequest (org.opensaml.saml2.core.LogoutRequest)3 URI (java.net.URI)2 Cookie (javax.servlet.http.Cookie)2 POST (javax.ws.rs.POST)2 NewCookie (javax.ws.rs.core.NewCookie)2 DateTime (org.joda.time.DateTime)2 Document (org.w3c.dom.Document)2 SamlProtocol (ddf.security.samlp.SamlProtocol)1 EntityInformation (ddf.security.samlp.impl.EntityInformation)1