org.opensaml.saml.saml2.core.LogoutRequest Java Examples

The following examples show how to use org.opensaml.saml.saml2.core.LogoutRequest. 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: AuthnRequestBuilderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testCreateLogoutRequest() throws Exception {
    Document doc = DOMUtils.createDocument();

    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer("http://localhost:9001/app");

    NameIDBean nameIdBean = new NameIDBean();
    nameIdBean.setNameValue("uid=joe,ou=people,ou=saml-demo,o=example.com");
    nameIdBean.setNameQualifier("www.example.com");
    NameID nameID = SAML2ComponentBuilder.createNameID(nameIdBean);

    Date notOnOrAfter = new Date();
    notOnOrAfter.setTime(notOnOrAfter.getTime() + 60L * 1000L);
    LogoutRequest logoutRequest =
        SamlpRequestComponentBuilder.createLogoutRequest(SAMLVersion.VERSION_20, issuer, null, null,
                                                         notOnOrAfter, null, nameID);

    Element policyElement = OpenSAMLUtil.toDom(logoutRequest, doc);
    doc.appendChild(policyElement);
    // String outputString = DOM2Writer.nodeToString(policyElement);
    assertNotNull(policyElement);
}
 
Example #2
Source File: LogoutRequestBuilder.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Overload Logout request for sessionIndexId is not exist case
 *
 * @param subject Subject
 * @param reason Reason for logout
 * @param issuerId id of issuer
 * @return SAML logout request
 */
public LogoutRequest buildLogoutRequest(String subject, String reason,
                                        String issuerId, String nameIdFormat) {
    Util.doBootstrap();
    LogoutRequest logoutReq = new org.opensaml.saml.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);

    logoutReq.setNameID(Util.buildNameID(nameIdFormat, subject));

    logoutReq.setReason(reason);

    return logoutReq;
}
 
Example #3
Source File: LogoutRequestSchemaValidator.java    From saml-client with MIT License 6 votes vote down vote up
/**
 * Validate the Identifier child types (BaseID, NameID, EncryptedID).
 *
 * @param request the request being processed
 * @throws SamlException thrown if the identifiers present are not valid
 */
protected void validateIdentifiers(LogoutRequest request) throws SamlException {
  int idCount = 0;

  if (request.getBaseID() != null) {
    idCount++;
  }
  if (request.getNameID() != null) {
    idCount++;
  }
  if (request.getEncryptedID() != null) {
    idCount++;
  }

  if (idCount != 1) {
    throw new SamlException(
        "LogoutRequest must contain exactly one of: BaseID, NameID, EncryptedID");
  }
}
 
Example #4
Source File: LogoutRequestBuilder.java    From carbon-apimgt with Apache License 2.0 6 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, String nameIdFormat) {
    Util.doBootstrap();
    LogoutRequest logoutReq = new org.opensaml.saml.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);

    logoutReq.setNameID(Util.buildNameID(nameIdFormat, subject));

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

    logoutReq.setReason(reason);

    return logoutReq;
}
 
Example #5
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static LogoutRequest getLogoutRequest(String destination, String issuerId) {
    final LogoutRequest logoutRequest = build(LogoutRequest.DEFAULT_ELEMENT_NAME);

    logoutRequest.setID(requestIdManager.newId());
    logoutRequest.setDestination(destination);

    final Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME);
    issuer.setValue(issuerId);
    logoutRequest.setIssuer(issuer);
    logoutRequest.setIssueInstant(DateTime.now());

    final NameID nameID = build(NameID.DEFAULT_ELEMENT_NAME);
    nameID.setFormat(SamlNameIdFormat.EMAIL.urn());

    logoutRequest.setNameID(nameID);

    return logoutRequest;
}
 
Example #6
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConsumeLogoutRequest_HttpRedirect() throws Exception {
    final LogoutRequest logoutRequest =
            getLogoutRequest("http://" + spHostname + ':' + rule.httpPort() + "/saml/slo/redirect",
                             "http://idp.example.com/redirect");

    final AggregatedHttpResponse res =
            sendViaHttpRedirectBindingProtocol("/saml/slo/redirect", SAML_REQUEST, logoutRequest);

    assertThat(res.status()).isEqualTo(HttpStatus.FOUND);

    // Check the order of the parameters in the quest string.
    final String location = res.headers().get(HttpHeaderNames.LOCATION);
    final Pattern p = Pattern.compile(
            "http://idp\\.example\\.com/saml/slo/redirect\\?" +
            "SAMLResponse=([^&]+)&SigAlg=([^&]+)&Signature=(.+)$");
    assertThat(location).isNotNull();
    assertThat(p.matcher(location).matches()).isTrue();
}
 
Example #7
Source File: SamlSingleLogoutFunction.java    From armeria with Apache License 2.0 6 votes vote down vote up
private HttpResponse fail(ServiceRequestContext ctx,
                          LogoutRequest logoutRequest,
                          SamlEndpoint sloResEndpoint) {
    // Try to send a LogoutResponse with the following status code. It's one of the top-level status code
    // which is defined in SAML 2.0 specifications.
    //
    // "urn:oasis:names:tc:SAML:2.0:status:Responder"
    // - The request could not be performed due to an error on the part of the SAML responder
    //   or SAML authority.
    final LogoutResponse failureResponse = createLogoutResponse(logoutRequest, StatusCode.RESPONDER);
    try {
        return respond(failureResponse, sloResEndpoint);
    } catch (SamlException e) {
        return fail(ctx, e);
    }
}
 
Example #8
Source File: SamlSingleLogoutFunction.java    From armeria with Apache License 2.0 6 votes vote down vote up
private SamlIdentityProviderConfig validateAndGetIdPConfig(LogoutRequest logoutRequest,
                                                           String endpointUri) {
    final String issuer = logoutRequest.getIssuer().getValue();
    if (issuer == null) {
        throw new InvalidSamlRequestException("no issuer found from the logout request: " +
                                              logoutRequest.getID());
    }
    if (!endpointUri.equals(logoutRequest.getDestination())) {
        throw new InvalidSamlRequestException("unexpected destination: " + logoutRequest.getDestination());
    }
    final SamlIdentityProviderConfig config = idpConfigs.get(issuer);
    if (config == null) {
        throw new InvalidSamlRequestException("unexpected identity provider: " + issuer);
    }
    return config;
}
 
Example #9
Source File: SamlSingleLogoutFunction.java    From armeria with Apache License 2.0 6 votes vote down vote up
private LogoutResponse createLogoutResponse(LogoutRequest logoutRequest,
                                            String statusCode) {
    final StatusCode success = build(StatusCode.DEFAULT_ELEMENT_NAME);
    success.setValue(statusCode);

    final Status status = build(Status.DEFAULT_ELEMENT_NAME);
    status.setStatusCode(success);

    final Issuer me = build(Issuer.DEFAULT_ELEMENT_NAME);
    me.setValue(entityId);

    final LogoutResponse logoutResponse = build(LogoutResponse.DEFAULT_ELEMENT_NAME);
    logoutResponse.setIssuer(me);
    logoutResponse.setID(requestIdManager.newId());
    logoutResponse.setIssueInstant(DateTime.now());
    logoutResponse.setStatus(status);
    logoutResponse.setInResponseTo(logoutRequest.getID());

    return logoutResponse;
}
 
Example #10
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConsumeLogoutRequest_HttpPost() throws Exception {
    final LogoutRequest logoutRequest =
            getLogoutRequest("http://" + spHostname + ':' + rule.httpPort() + "/saml/slo/post",
                             "http://idp.example.com/post");

    final AggregatedHttpResponse res = sendViaHttpPostBindingProtocol("/saml/slo/post",
                                                                      SAML_REQUEST, logoutRequest);

    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.contentType()).isEqualTo(MediaType.HTML_UTF_8);

    final Document doc = Jsoup.parse(res.contentUtf8());
    assertThat(doc.body().attr("onLoad")).isEqualTo("document.forms[0].submit()");

    // SAMLResponse will be posted to the IdP's logout response URL.
    final Element form = doc.body().child(0);
    assertThat(form.attr("method")).isEqualTo("post");
    assertThat(form.attr("action")).isEqualTo("http://idp.example.com/saml/slo/post");
    assertThat(form.child(0).attr("name")).isEqualTo(SAML_RESPONSE);
}
 
Example #11
Source File: SAMLRequestTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void createSAMLLogoutRequest() throws Exception {
    // Mock up a Request
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL)).times(1, 2);
    EasyMock.expect(req.getContextPath()).andReturn(TEST_REQUEST_URI);
    EasyMock.expect(req.getRequestURI()).andReturn(TEST_REQUEST_URI).times(1, 2);
    EasyMock.replay(req);

    FedizProcessor wfProc = new SAMLProcessorImpl();
    RedirectionResponse response = wfProc.createSignOutRequest(req, null, config);

    String redirectionURL = response.getRedirectionURL();
    String samlRequest =
        redirectionURL.substring(redirectionURL.indexOf("SAMLRequest=") + "SAMLRequest=".length(),
                                 redirectionURL.indexOf("RelayState=") - 1);

    byte[] deflatedToken = Base64.getDecoder().decode(URLDecoder.decode(samlRequest, "UTF-8"));
    InputStream tokenStream = CompressionUtils.inflate(deflatedToken);

    Document requestDoc = DOMUtils.readXml(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    LogoutRequest request =
        (LogoutRequest)OpenSAMLUtil.fromDom(requestDoc.getDocumentElement());

    Assert.assertEquals(TEST_REQUEST_URL, request.getIssuer().getValue());
}
 
Example #12
Source File: SamlpRequestComponentBuilder.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static LogoutRequest createLogoutRequest(
    Issuer issuer,
    String reason,
    NameID nameId,
    List<String> sessionIndices
) {
    if (logoutRequestBuilder == null) {
        logoutRequestBuilder = (SAMLObjectBuilder<LogoutRequest>)
            builderFactory.getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME);
    }
    if (sessionIndexBuilder == null) {
        sessionIndexBuilder = (SAMLObjectBuilder<SessionIndex>)
            builderFactory.getBuilder(SessionIndex.DEFAULT_ELEMENT_NAME);
    }

    LogoutRequest logoutRequest = logoutRequestBuilder.buildObject();

    logoutRequest.setID("_" + UUID.randomUUID().toString());
    logoutRequest.setIssueInstant(new DateTime());

    if (reason != null) {
        logoutRequest.setReason(reason);
    }
    if (nameId != null) {
        logoutRequest.setNameID(nameId);
    }

    if (sessionIndices != null && !sessionIndices.isEmpty()) {
        for (String sessionIndex : sessionIndices) {
            SessionIndex sessionIndexObj = sessionIndexBuilder.buildObject();
            sessionIndexObj.setSessionIndex(sessionIndex);
            logoutRequest.getSessionIndexes().add(sessionIndexObj);
        }
    }

    logoutRequest.setIssuer(issuer);

    return logoutRequest;
}
 
Example #13
Source File: SAMLLogoutRequest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public SAMLLogoutRequest(LogoutRequest logoutRequest) {
    super(logoutRequest);
    if (logoutRequest.getNotOnOrAfter() != null) {
        notOnOrAfter = logoutRequest.getNotOnOrAfter().toDate();
    }

    if (logoutRequest.getNameID() != null) {
        subjectNameId = logoutRequest.getNameID().getValue();
    }
}
 
Example #14
Source File: SamlpRequestComponentBuilder.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static LogoutRequest createLogoutRequest(
    SAMLVersion version,
    Issuer issuer,
    String destination,
    String consent,
    Date notOnOrAfter,
    String reason,
    NameID nameID
) {
    if (logoutRequestBuilder == null) {
        logoutRequestBuilder = (SAMLObjectBuilder<LogoutRequest>)
            builderFactory.getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME);
    }
    LogoutRequest logoutRequest = logoutRequestBuilder.buildObject();
    logoutRequest.setID("_" + UUID.randomUUID());
    logoutRequest.setVersion(version);
    logoutRequest.setIssueInstant(new DateTime());
    logoutRequest.setDestination(destination);
    logoutRequest.setConsent(consent);
    logoutRequest.setIssuer(issuer);
    if (notOnOrAfter != null) {
        logoutRequest.setNotOnOrAfter(new DateTime(notOnOrAfter.getTime()));
    }
    logoutRequest.setReason(reason);
    logoutRequest.setNameID(nameID);

    return logoutRequest;
}
 
Example #15
Source File: LogoutRequestBuilder.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Overload Logout request for sessionIndexId is not exist case
 *
 * @param subject Subject
 * @param reason Reason for logout
 * @param issuerId id of issuer
 * @return Signed SAML logout request
 */
public LogoutRequest buildSignedLogoutRequest(String subject, String reason,
        String issuerId, int tenantId, String tenantDomain, String destination, String nameIdFormat)
        throws SSOHostObjectException {
    Util.doBootstrap();
    LogoutRequest logoutReq = new org.opensaml.saml.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);

    logoutReq.setNameID(Util.buildNameID(nameIdFormat, subject));

    logoutReq.setReason(reason);
    logoutReq.setDestination(destination);

    SSOAgentCarbonX509Credential ssoAgentCarbonX509Credential =
            new SSOAgentCarbonX509Credential(tenantId, tenantDomain);
    setSignature(logoutReq, SignatureConstants.ALGO_ID_SIGNATURE_RSA,
            new X509CredentialImpl(ssoAgentCarbonX509Credential));

    return logoutReq;
}
 
Example #16
Source File: LogoutRequestBuilder.java    From carbon-apimgt 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 buildSignedLogoutRequest(String subject,String sessionIndexId, String reason,
        String issuerId, int tenantId, String tenantDomain, String destination, String nameIdFormat)
        throws SSOHostObjectException {
    Util.doBootstrap();
    LogoutRequest logoutReq = new org.opensaml.saml.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);

    logoutReq.setNameID(Util.buildNameID(nameIdFormat, subject));

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

    logoutReq.setReason(reason);
    logoutReq.setDestination(destination);

    SSOAgentCarbonX509Credential ssoAgentCarbonX509Credential =
            new SSOAgentCarbonX509Credential(tenantId, tenantDomain);
    setSignature(logoutReq, SignatureConstants.ALGO_ID_SIGNATURE_RSA,
            new X509CredentialImpl(ssoAgentCarbonX509Credential));

    return logoutReq;
}
 
Example #17
Source File: ValidatorUtils.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Validate response.
 *
 * @param request       the request
 * @param requestIssuer the response issuer
 * @throws SamlException the saml exception
 */
private static void validateLogoutRequest(
    LogoutRequest request, String requestIssuer, String nameID) throws SamlException {
  try {
    new LogoutRequestSchemaValidator().validate(request);
  } catch (SamlException ex) {
    throw new SamlException("The request schema validation failed", ex);
  }
  validateIssuer(request, requestIssuer);
  validateNameId(request, nameID);
}
 
Example #18
Source File: ValidatorUtils.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Validate.
 *
 * @param logoutRequest       the response
 * @param responseIssuer the response issuer
 * @param credentials    the credentials
 * @throws SamlException the saml exception
 */
public static void validate(
    LogoutRequest logoutRequest,
    String responseIssuer,
    List<Credential> credentials,
    String nameID)
    throws SamlException {
  validateLogoutRequest(logoutRequest, responseIssuer, nameID);
  validateSignature(logoutRequest, credentials);
}
 
Example #19
Source File: LogoutRequestSchemaValidator.java    From saml-client with MIT License 5 votes vote down vote up
private void validateVersion(LogoutRequest request) throws SamlException {
  if (request.getVersion() == null) {
    throw new SamlException("Version attribute must not be null");
  }
  if (!Objects.equals(request.getVersion().toString(), SAMLVersion.VERSION_20.toString())) {
    throw new SamlException("Wrong SAML Version");
  }
}
 
Example #20
Source File: SamlClient.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Gets the encoded logout request.
 *
 * @param nameId the name id
 * @return the logout request
 * @throws SamlException the saml exception
 */
public String getLogoutRequest(String nameId) throws SamlException {
  LogoutRequest request = (LogoutRequest) getBasicSamlRequest(LogoutRequest.DEFAULT_ELEMENT_NAME);

  NameID nid = (NameID) buildSamlObject(NameID.DEFAULT_ELEMENT_NAME);
  nid.setValue(nameId);
  request.setNameID(nid);

  signSAMLObject(request);

  return marshallAndEncodeSamlObject(request);
}
 
Example #21
Source File: SAML2SPLogic.java    From syncope with Apache License 2.0 4 votes vote down vote up
@PreAuthorize("isAuthenticated() and not(hasRole('" + IdRepoEntitlement.ANONYMOUS + "'))")
public SAML2RequestTO createLogoutRequest(final String accessToken, final String spEntityID) {
    check();

    // 1. fetch the current JWT used for Syncope authentication
    JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(accessToken);
    if (!consumer.verifySignatureWith(jwsSignatureVerifier)) {
        throw new IllegalArgumentException("Invalid signature found in Access Token");
    }

    // 2. look for IdP
    String idpEntityID = (String) consumer.getJwtClaims().getClaim(JWT_CLAIM_IDP_ENTITYID);
    if (idpEntityID == null) {
        throw new NotFoundException("No SAML 2.0 IdP information found in the access token");
    }
    SAML2IdPEntity idp = cache.get(idpEntityID);
    if (idp == null) {
        throw new NotFoundException("SAML 2.0 IdP '" + idpEntityID + '\'');
    }
    if (idp.getSLOLocation(idp.getBindingType()) == null) {
        throw new IllegalArgumentException("No SingleLogoutService available for " + idp.getId());
    }

    // 3. create LogoutRequest
    LogoutRequest logoutRequest = new LogoutRequestBuilder().buildObject();
    logoutRequest.setID('_' + SecureRandomUtils.generateRandomUUID().toString());
    logoutRequest.setDestination(idp.getSLOLocation(idp.getBindingType()).getLocation());

    DateTime now = new DateTime();
    logoutRequest.setIssueInstant(now);
    logoutRequest.setNotOnOrAfter(now.plusMinutes(5));

    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(spEntityID);
    logoutRequest.setIssuer(issuer);

    NameID nameID = new NameIDBuilder().buildObject();
    nameID.setFormat((String) consumer.getJwtClaims().getClaim(JWT_CLAIM_NAMEID_FORMAT));
    nameID.setValue((String) consumer.getJwtClaims().getClaim(JWT_CLAIM_NAMEID_VALUE));
    logoutRequest.setNameID(nameID);

    SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
    sessionIndex.setSessionIndex((String) consumer.getJwtClaims().getClaim(JWT_CLAIM_SESSIONINDEX));
    logoutRequest.getSessionIndexes().add(sessionIndex);

    SAML2RequestTO requestTO = new SAML2RequestTO();
    requestTO.setIdpServiceAddress(logoutRequest.getDestination());
    requestTO.setBindingType(idp.getBindingType());
    try {
        // 3. generate relay state as JWT
        Map<String, Object> claims = new HashMap<>();
        claims.put(JWT_CLAIM_IDP_DEFLATE,
                idp.getBindingType() == SAML2BindingType.REDIRECT ? true : idp.isUseDeflateEncoding());
        Pair<String, Date> relayState = accessTokenDataBinder.generateJWT(
                SecureRandomUtils.generateRandomUUID().toString(),
                logoutRequest.getID(), JWT_RELAY_STATE_DURATION, claims);
        requestTO.setRelayState(relayState.getLeft());

        // 4. sign and encode AuthnRequest
        switch (idp.getBindingType()) {
            case REDIRECT:
                requestTO.setContent(SAML2ReaderWriter.encode(logoutRequest, true));
                requestTO.setSignAlg(saml2rw.getSigAlgo());
                requestTO.setSignature(saml2rw.sign(requestTO.getContent(), requestTO.getRelayState()));
                break;

            case POST:
            default:
                saml2rw.sign(logoutRequest);
                requestTO.setContent(SAML2ReaderWriter.encode(logoutRequest, idp.isUseDeflateEncoding()));
        }
    } catch (Exception e) {
        LOG.error("While generating LogoutRequest", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }

    return requestTO;
}
 
Example #22
Source File: LogoutRequestSchemaValidator.java    From saml-client with MIT License 4 votes vote down vote up
private void validateIssueInstant(LogoutRequest request) throws SamlException {
  if (request.getIssueInstant() == null) {
    throw new SamlException("IssueInstant attribute must not be null");
  }
}
 
Example #23
Source File: LogoutRequestSchemaValidator.java    From saml-client with MIT License 4 votes vote down vote up
private void validateID(LogoutRequest request) throws SamlException {
  if (StringUtils.isEmpty(request.getID())) {
    throw new SamlException("ID attribute must not be empty");
  }
}
 
Example #24
Source File: LogoutRequestSchemaValidator.java    From saml-client with MIT License 4 votes vote down vote up
public void validate(LogoutRequest request) throws SamlException {
  validateID(request);
  validateVersion(request);
  validateIssueInstant(request);
  validateIdentifiers(request);
}
 
Example #25
Source File: SAMLProcessorImpl.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Override
public RedirectionResponse createSignOutRequest(HttpServletRequest request,
                                                SamlAssertionWrapper token,
                                                FedizContext config)
    throws ProcessingException {

    String redirectURL = null;
    try {
        if (!(config.getProtocol() instanceof SAMLProtocol)) {
            LOG.error("Unsupported protocol");
            throw new IllegalStateException("Unsupported protocol");
        }

        redirectURL = ((SAMLProtocol)config.getProtocol()).getIssuerLogoutURL();
        if (redirectURL == null) {
            String issuerURL = resolveIssuer(request, config);
            LOG.info("Issuer url: " + issuerURL);
            if (issuerURL != null && issuerURL.length() > 0) {
                redirectURL = issuerURL;
            }
        }
        if (redirectURL == null) {
            LOG.debug("No issuerLogoutURL or issuer parameter specified for logout");
            throw new ProcessingException("Failed to create SignOutRequest");
        }

        SAMLPRequestBuilder samlpRequestBuilder =
            ((SAMLProtocol)config.getProtocol()).getSAMLPRequestBuilder();

        Document doc = DOMUtils.createDocument();
        doc.appendChild(doc.createElement("root"));

        // Create the LogoutRequest
        String realm = resolveWTRealm(request, config);
        String reason = "urn:oasis:names:tc:SAML:2.0:logout:user";
        LogoutRequest logoutRequest =
            samlpRequestBuilder.createLogoutRequest(realm, reason, token);

        if (((SAMLProtocol)config.getProtocol()).isSignRequest()) {
            logoutRequest.setDestination(redirectURL);
        }

        Element logoutRequestElement = OpenSAMLUtil.toDom(logoutRequest, doc);
        String logoutRequestEncoded = encodeAuthnRequest(logoutRequestElement);

        String relayState = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");

        String urlEncodedRequest =
            URLEncoder.encode(logoutRequestEncoded, "UTF-8");

        StringBuilder sb = new StringBuilder();
        sb.append(SAMLSSOConstants.SAML_REQUEST).append('=').append(urlEncodedRequest);
        sb.append('&').append(SAMLSSOConstants.RELAY_STATE).append('=').append(relayState);

        if (((SAMLProtocol)config.getProtocol()).isSignRequest()) {
            String signature = signRequest(config, sb);
            sb.append('&').append(SAMLSSOConstants.SIGNATURE).append('=').append(signature);
        }

        RedirectionResponse response = new RedirectionResponse();
        response.addHeader("Cache-Control", "no-cache, no-store");
        response.addHeader("Pragma", "no-cache");
        response.setState(relayState);

        redirectURL = redirectURL + "?" + sb.toString();
        response.setRedirectionURL(redirectURL);

        return response;
    } catch (Exception ex) {
        LOG.error("Failed to create SignOutRequest", ex);
        throw new ProcessingException("Failed to create SignOutRequest");
    }
}
 
Example #26
Source File: SAMLPRequestBuilder.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
/**
 * Create a SAML 2.0 Protocol LogoutRequest
 */
LogoutRequest createLogoutRequest(
    String issuerId,
    String reason,
    SamlAssertionWrapper authenticatedAssertion
) throws Exception;
 
Example #27
Source File: DefaultSAMLPRequestBuilder.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Override
public LogoutRequest createLogoutRequest(
    String issuerId,
    String reason,
    SamlAssertionWrapper authenticatedAssertion
) throws Exception {
    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer(issuerId);

    NameID nameID = null;
    List<String> sessionIndices = new ArrayList<>();

    if (authenticatedAssertion != null) {
        if (authenticatedAssertion.getSaml2() != null) {
            org.opensaml.saml.saml2.core.Subject subject =
                authenticatedAssertion.getSaml2().getSubject();
            if (subject != null && subject.getNameID() != null) {
                nameID = subject.getNameID();
            }
        }

        if (nameID != null) {
            nameID.detach();
        }

        List<AuthnStatement> authnStatements =
            authenticatedAssertion.getSaml2().getAuthnStatements();
        if (authnStatements != null && !authnStatements.isEmpty()) {
            for (AuthnStatement authnStatement : authnStatements) {
                if (authnStatement.getSessionIndex() != null) {
                    sessionIndices.add(authnStatement.getSessionIndex());
                }
            }
        }
    }

    //CHECKSTYLE:OFF
    return SamlpRequestComponentBuilder.createLogoutRequest(
        issuer,
        reason,
        nameID,
        sessionIndices
    );
}
 
Example #28
Source File: CustomSAMLPRequestBuilder.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Override
public LogoutRequest createLogoutRequest(
    String issuerId,
    String reason,
    SamlAssertionWrapper authenticatedAssertion
) throws Exception {
    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer(issuerId);

    NameID nameID = null;
    List<String> sessionIndices = new ArrayList<>();

    if (authenticatedAssertion != null) {
        if (authenticatedAssertion.getSaml2() != null) {
            org.opensaml.saml.saml2.core.Subject subject =
                authenticatedAssertion.getSaml2().getSubject();
            if (subject != null && subject.getNameID() != null) {
                nameID = subject.getNameID();
            }
        }

        if (nameID != null) {
            nameID.detach();
        }

        List<AuthnStatement> authnStatements =
            authenticatedAssertion.getSaml2().getAuthnStatements();
        if (authnStatements != null && !authnStatements.isEmpty()) {
            for (AuthnStatement authnStatement : authnStatements) {
                if (authnStatement.getSessionIndex() != null) {
                    sessionIndices.add(authnStatement.getSessionIndex());
                }
            }
        }
    }

    //CHECKSTYLE:OFF
    return SamlpRequestComponentBuilder.createLogoutRequest(
        issuer,
        reason,
        nameID,
        sessionIndices
    );
}
 
Example #29
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void handleSloGetRequestBase(HttpRequest request) {
    try {

        HttpServletRequest httpServletRequest = new FakeHttpServletRequest(request);

        HTTPRedirectDeflateDecoder decoder = new HTTPRedirectDeflateDecoder();
        decoder.setParserPool(XMLObjectProviderRegistrySupport.getParserPool());
        decoder.setHttpServletRequest(httpServletRequest);
        decoder.initialize();
        decoder.decode();

        MessageContext<SAMLObject> messageContext = decoder.getMessageContext();

        if (!(messageContext.getMessage() instanceof LogoutRequest)) {
            throw new RuntimeException("Expected LogoutRequest; received: " + messageContext.getMessage());
        }

        LogoutRequest logoutRequest = (LogoutRequest) messageContext.getMessage();

        SAML2HTTPRedirectDeflateSignatureSecurityHandler signatureSecurityHandler = new SAML2HTTPRedirectDeflateSignatureSecurityHandler();
        SignatureValidationParameters validationParams = new SignatureValidationParameters();
        SecurityParametersContext securityParametersContext = messageContext
                .getSubcontext(SecurityParametersContext.class, true);

        SAMLPeerEntityContext peerEntityContext = messageContext.getSubcontext(SAMLPeerEntityContext.class, true);
        peerEntityContext.setEntityId(idpEntityId);
        peerEntityContext.setRole(org.opensaml.saml.saml2.metadata.SPSSODescriptor.DEFAULT_ELEMENT_NAME);

        SAMLProtocolContext protocolContext = messageContext.getSubcontext(SAMLProtocolContext.class, true);
        protocolContext.setProtocol(SAMLConstants.SAML20P_NS);

        validationParams.setSignatureTrustEngine(buildSignatureTrustEngine(this.spSignatureCertificate));
        securityParametersContext.setSignatureValidationParameters(validationParams);
        signatureSecurityHandler.setHttpServletRequest(httpServletRequest);
        signatureSecurityHandler.initialize();
        signatureSecurityHandler.invoke(messageContext);

        if (!this.authenticateUser.equals(logoutRequest.getNameID().getValue())) {
            throw new RuntimeException("Unexpected NameID in LogoutRequest: " + logoutRequest);
        }

    } catch (URISyntaxException | ComponentInitializationException | MessageDecodingException
            | MessageHandlerException e) {
        throw new RuntimeException(e);
    }
}
 
Example #30
Source File: SamlClient.java    From saml-client with MIT License 3 votes vote down vote up
/**
 * Decodes and validates an SAML logout request send by an identity provider.
 *
 * @param encodedRequest the encoded request send by the identity provider.
 * @param nameID The user to logout
 * @param method The HTTP method used by the request
 * @throws SamlException if the signature is invalid, or if any other error occurs.
 */
public void decodeAndValidateSamlLogoutRequest(
    String encodedRequest, String nameID, String method) throws SamlException {
  LogoutRequest logoutRequest = (LogoutRequest) parseResponse(encodedRequest, method);

  ValidatorUtils.validate(logoutRequest, responseIssuer, credentials, nameID);
}