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

The following examples show how to use org.opensaml.saml.saml2.core.AuthnRequest. 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: SamlClient.java    From saml-client with MIT License 6 votes vote down vote up
/**
 * Builds an encoded SAML request.
 *
 * @return The base-64 encoded SAML request.
 * @throws SamlException thrown if an unexpected error occurs.
 */
public String getSamlRequest() throws SamlException {
  AuthnRequest request = (AuthnRequest) getBasicSamlRequest(AuthnRequest.DEFAULT_ELEMENT_NAME);

  request.setProtocolBinding(
      "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-" + this.samlBinding.toString());
  request.setDestination(identityProviderUrl);
  request.setAssertionConsumerServiceURL(assertionConsumerServiceUrl);

  NameIDPolicy nameIDPolicy = (NameIDPolicy) buildSamlObject(NameIDPolicy.DEFAULT_ELEMENT_NAME);
  nameIDPolicy.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
  request.setNameIDPolicy(nameIDPolicy);

  signSAMLObject(request);

  return marshallAndEncodeSamlObject(request);
}
 
Example #2
Source File: AuthnRequestBuilderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testAuthnRequestBuilder() throws Exception {
    Document doc = DOMUtils.createDocument();

    AuthnRequestBuilder authnRequestBuilder = new DefaultAuthnRequestBuilder();
    Message message = new MessageImpl();

    AuthnRequest authnRequest =
        authnRequestBuilder.createAuthnRequest(
            message, "http://localhost:9001/app", "http://localhost:9001/sso"
        );
    Element policyElement = OpenSAMLUtil.toDom(authnRequest, doc);
    doc.appendChild(policyElement);
    // String outputString = DOM2Writer.nodeToString(policyElement);
    assertNotNull(policyElement);
}
 
Example #3
Source File: SamlSso.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@GET
public javax.ws.rs.core.Response login(@QueryParam("SAMLRequest") String samlRequest,
        @QueryParam("RelayState") String relayState, @QueryParam("binding") String binding) throws Exception {

    AuthnRequest request = extractRequest(samlRequest);

    String racs = request.getAssertionConsumerServiceURL();
    String requestIssuer = request.getIssuer().getValue();

    // Create the response
    Element response = createResponse(request.getID(), racs, requestIssuer);
    boolean redirect = "REDIRECT".equals(binding);
    String responseStr = encodeResponse(response, redirect);

    if (redirect) {
        return redirectResponse(relayState, racs, responseStr);
    } else {
        return postBindingResponse(relayState, racs, responseStr);
    }
}
 
Example #4
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
public String handleSsoGetRequestBase(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 AuthnRequest)) {
            throw new RuntimeException("Expected AuthnRequest; received: " + messageContext.getMessage());
        }

        AuthnRequest authnRequest = (AuthnRequest) messageContext.getMessage();

        return createSamlAuthResponse(authnRequest);
    } catch (URISyntaxException | ComponentInitializationException | MessageDecodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: AuthReqBuilder.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Generate an Signed authentication request with a custom consumer url.
 *
 * @return AuthnRequest Object
 * @throws SSOHostObjectException error when bootstrapping
 */

public AuthnRequest buildSignedAuthRequest(String issuerId, String destination, String acsUrl, boolean isPassive,
        int tenantId, String tenantDomain, String nameIdPolicy) throws SSOHostObjectException {
    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(Util.buildNameIDPolicy(nameIdPolicy));
    if (!StringUtils.isEmpty(acsUrl)) {
        acsUrl = Util.processAcsUrl(acsUrl);
        authnRequest.setAssertionConsumerServiceURL(acsUrl);
    }
    if (isPassive){
        authnRequest.setIsPassive(true);
    }
    authnRequest.setDestination(destination);
    SSOAgentCarbonX509Credential ssoAgentCarbonX509Credential =
            new SSOAgentCarbonX509Credential(tenantId, tenantDomain);
    setSignature(authnRequest, SignatureConstants.ALGO_ID_SIGNATURE_RSA,
            new X509CredentialImpl(ssoAgentCarbonX509Credential));
    return authnRequest;
}
 
Example #6
Source File: AuthReqBuilder.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Generate an authentication request.
 *
 * @return AuthnRequest Object
 * @throws SSOHostObjectException error when bootstrapping
 */
public AuthnRequest buildAuthenticationRequest(String issuerId, String acsUrl, boolean isPassive,
        String nameIdPolicy) throws SSOHostObjectException {
    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(Util.buildNameIDPolicy(nameIdPolicy));
    if (isPassive){
        authnRequest.setIsPassive(true);
    }
    if (!StringUtils.isEmpty(acsUrl)) {
        acsUrl = Util.processAcsUrl(acsUrl);
        authnRequest.setAssertionConsumerServiceURL(acsUrl);
    }
    return authnRequest;
}
 
Example #7
Source File: AuthnRequestParser.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private void validateRequest(RequestAbstractType parsedRequest) throws ProcessingException {
    if (parsedRequest.getIssuer() == null) {
        LOG.debug("No Issuer is present in the AuthnRequest/LogoutRequest");
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }

    String format = parsedRequest.getIssuer().getFormat();
    if (format != null
        && !"urn:oasis:names:tc:SAML:2.0:nameid-format:entity".equals(format)) {
        LOG.debug("An invalid Format attribute was received: {}", format);
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }

    if (parsedRequest instanceof AuthnRequest) {
        // No SubjectConfirmation Elements are allowed
        AuthnRequest authnRequest = (AuthnRequest)parsedRequest;
        if (authnRequest.getSubject() != null
            && authnRequest.getSubject().getSubjectConfirmations() != null
            && !authnRequest.getSubject().getSubjectConfirmations().isEmpty()) {
            LOG.debug("An invalid SubjectConfirmation Element was received");
            throw new ProcessingException(TYPE.BAD_REQUEST);
        }
    }
}
 
Example #8
Source File: SamlAuthSsoHandler.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
public CompletionStage<Void> beforeInitiatingSso(ServiceRequestContext ctx, HttpRequest req,
                                                 MessageContext<AuthnRequest> message,
                                                 SamlIdentityProviderConfig idpConfig) {
    final QueryStringDecoder decoder = new QueryStringDecoder(req.path(), true);
    final List<String> ref = decoder.parameters().get("ref");
    if (ref == null || ref.isEmpty()) {
        return CompletableFuture.completedFuture(null);
    }

    final String relayState = ref.get(0);
    if (idpConfig.ssoEndpoint().bindingProtocol() == SamlBindingProtocol.HTTP_REDIRECT &&
        relayState.length() > 80) {
        return CompletableFuture.completedFuture(null);
    }

    final SAMLBindingContext sub = message.getSubcontext(SAMLBindingContext.class, true);
    assert sub != null : SAMLBindingContext.class.getName();
    sub.setRelayState(relayState);
    return CompletableFuture.completedFuture(null);
}
 
Example #9
Source File: AuthnRequestFactory.java    From verify-service-provider with MIT License 6 votes vote down vote up
public AuthnRequest build(String serviceEntityId) {
    AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject();
    authnRequest.setID(String.format("_%s", UUID.randomUUID()));
    authnRequest.setIssueInstant(DateTime.now());
    authnRequest.setForceAuthn(false);
    authnRequest.setDestination(destination.toString());
    authnRequest.setExtensions(createExtensions());

    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(serviceEntityId);
    authnRequest.setIssuer(issuer);

    authnRequest.setSignature(createSignature());

    try {
        XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(authnRequest).marshall(authnRequest);
        Signer.signObject(authnRequest.getSignature());
    } catch (SignatureException | MarshallingException e) {
        throw new SAMLRuntimeException("Unknown problem while signing SAML object", e);
    }

    return authnRequest;
}
 
Example #10
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testMissingDestination() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    signAuthnRequest(authnRequest);

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}
 
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 testCustomSAMLAuthnRequest() throws Exception {
    // Mock up a Request
    FedizContext config = getFederationConfigurator().getFedizContext("CUSTOM_REQUEST");

    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.createSignInRequest(req, 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));
    AuthnRequest request =
        (AuthnRequest)OpenSAMLUtil.fromDom(requestDoc.getDocumentElement());

    Assert.assertEquals(TEST_REQUEST_URL, request.getIssuer().getValue());
    Assert.assertEquals(TEST_REQUEST_URL, request.getAssertionConsumerServiceURL());
    Assert.assertEquals("1.1",  request.getVersion().toString());
}
 
Example #12
Source File: AuthnRequestBuilderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthnRequestID() throws Exception {
    AuthnRequestBuilder authnRequestBuilder = new DefaultAuthnRequestBuilder();
    AuthnRequest authnRequest =
        authnRequestBuilder.createAuthnRequest(
            new MessageImpl(), "http://localhost:9001/app", "http://localhost:9001/sso"
        );
    assertTrue("ID must start with a letter or underscore, and can only contain letters, digits, "
        + "underscores, hyphens, and periods.", authnRequest.getID().matches("^[_a-zA-Z][-_0-9a-zA-Z\\.]+$"));
}
 
Example #13
Source File: SAMLRequestTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSAMLAuthnRequest() 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.createSignInRequest(req, 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));
    AuthnRequest request =
        (AuthnRequest)OpenSAMLUtil.fromDom(requestDoc.getDocumentElement());

    Assert.assertEquals(TEST_REQUEST_URL, request.getIssuer().getValue());
    Assert.assertEquals(TEST_REQUEST_URL, request.getAssertionConsumerServiceURL());
    Assert.assertEquals("2.0",  request.getVersion().toString());
}
 
Example #14
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBadIssuer() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld-xyz", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
    signAuthnRequest(authnRequest);

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}
 
Example #15
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNoIssuer() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, null, consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
    signAuthnRequest(authnRequest);

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}
 
Example #16
Source File: CustomSAMLPRequestBuilder.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Create a SAML 2.0 Protocol AuthnRequest
 */
public AuthnRequest createAuthnRequest(
    String issuerId,
    String assertionConsumerServiceAddress
) throws Exception {
    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer(issuerId);

    NameIDPolicy nameIDPolicy =
        SamlpRequestComponentBuilder.createNameIDPolicy(
            true, "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent", issuerId
        );

    AuthnContextClassRef authnCtxClassRef =
        SamlpRequestComponentBuilder.createAuthnCtxClassRef(
            "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
        );
    RequestedAuthnContext authnCtx =
        SamlpRequestComponentBuilder.createRequestedAuthnCtxPolicy(
            AuthnContextComparisonTypeEnumeration.EXACT,
            Collections.singletonList(authnCtxClassRef), null
        );

    //CHECKSTYLE:OFF
    return SamlpRequestComponentBuilder.createAuthnRequest(
            assertionConsumerServiceAddress,
            forceAuthn,
            isPassive,
            protocolBinding,
            SAMLVersion.VERSION_11,
            issuer,
            nameIDPolicy,
            authnCtx
    );

}
 
Example #17
Source File: SamlpRequestComponentBuilder.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
//CHECKSTYLE:OFF
public static AuthnRequest createAuthnRequest(
    String serviceURL,
    boolean forceAuthn,
    boolean isPassive,
    String protocolBinding,
    SAMLVersion version,
    Issuer issuer,
    NameIDPolicy nameIDPolicy,
    RequestedAuthnContext requestedAuthnCtx
) {
//CHECKSTYLE:ON
    if (authnRequestBuilder == null) {
        authnRequestBuilder = (SAMLObjectBuilder<AuthnRequest>)
            builderFactory.getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
    }
    AuthnRequest authnRequest = authnRequestBuilder.buildObject();
    authnRequest.setAssertionConsumerServiceURL(serviceURL);
    authnRequest.setForceAuthn(forceAuthn);
    authnRequest.setID("_" + UUID.randomUUID().toString());
    authnRequest.setIsPassive(isPassive);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setProtocolBinding(protocolBinding);
    authnRequest.setVersion(version);

    authnRequest.setIssuer(issuer);
    authnRequest.setNameIDPolicy(nameIDPolicy);
    authnRequest.setRequestedAuthnContext(requestedAuthnCtx);

    return authnRequest;
}
 
Example #18
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testMissingRelayState() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
    signAuthnRequest(authnRequest);

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    try {
        webClient.getPage(url);
        Assert.fail("Failure expected on not sending the RelayState");
    }  catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 400);
    }

    webClient.close();
}
 
Example #19
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUnsignedRequest() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}
 
Example #20
Source File: SamlSso.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected AuthnRequest extractRequest(String samlRequest) throws Base64Exception,
    DataFormatException, XMLStreamException, IOException, WSSecurityException {
    byte[] deflatedToken = Base64Utility.decode(samlRequest);

    final Document responseDoc;
    try (InputStream tokenStream = new DeflateEncoderDecoder().inflateToken(deflatedToken)) {
        responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    }
    AuthnRequest request =
        (AuthnRequest)OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
    System.out.println(DOM2Writer.nodeToString(responseDoc));
    return request;
}
 
Example #21
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testEmptySeparateSignature() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();

    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name())
            + "&" + SSOConstants.SIGNATURE + "=";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}
 
Example #22
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUnknownRACS() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/insecure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
    signAuthnRequest(authnRequest);

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}
 
Example #23
Source File: DefaultSAMLPRequestBuilder.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Create a SAML 2.0 Protocol AuthnRequest
 */
public AuthnRequest createAuthnRequest(
    String issuerId,
    String assertionConsumerServiceAddress
) throws Exception {
    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer(issuerId);

    NameIDPolicy nameIDPolicy =
        SamlpRequestComponentBuilder.createNameIDPolicy(
            true, nameIDFormat, issuerId
        );

    AuthnContextClassRef authnCtxClassRef =
        SamlpRequestComponentBuilder.createAuthnCtxClassRef(
            "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
        );
    RequestedAuthnContext authnCtx =
        SamlpRequestComponentBuilder.createRequestedAuthnCtxPolicy(
            AuthnContextComparisonTypeEnumeration.EXACT,
            Collections.singletonList(authnCtxClassRef), null
        );

    //CHECKSTYLE:OFF
    return SamlpRequestComponentBuilder.createAuthnRequest(
            assertionConsumerServiceAddress,
            forceAuthn,
            isPassive,
            protocolBinding,
            SAMLVersion.VERSION_20,
            issuer,
            nameIDPolicy,
            authnCtx
    );

}
 
Example #24
Source File: SAMLAuthnRequest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public SAMLAuthnRequest(AuthnRequest authnRequest) {
    super(authnRequest);

    consumerServiceURL = authnRequest.getAssertionConsumerServiceURL();
    forceAuthn = authnRequest.isForceAuthn().booleanValue();
    if (authnRequest.getSubject() != null && authnRequest.getSubject().getNameID() != null) {
        subjectNameId = authnRequest.getSubject().getNameID().getValue();
    }
}
 
Example #25
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private String createSamlAuthResponse(AuthnRequest authnRequest) {
    try {
        Response response = createSamlElement(Response.class);
        response.setID(nextId());

        if (authnRequest != null) {
            response.setInResponseTo(authnRequest.getID());
        }

        response.setVersion(SAMLVersion.VERSION_20);
        response.setStatus(createStatus(StatusCode.SUCCESS));
        response.setIssueInstant(new DateTime());

        Assertion assertion = createSamlElement(Assertion.class);
        response.getAssertions().add(assertion);

        assertion.setID(nextId());
        assertion.setIssueInstant(new DateTime());
        assertion.setIssuer(createIssuer());

        AuthnStatement authnStatement = createSamlElement(AuthnStatement.class);
        assertion.getAuthnStatements().add(authnStatement);

        authnStatement.setAuthnInstant(new DateTime());
        authnStatement.setSessionIndex(nextId());
        authnStatement.setAuthnContext(createAuthnCotext());

        Subject subject = createSamlElement(Subject.class);
        assertion.setSubject(subject);

        subject.setNameID(createNameID(NameIDType.UNSPECIFIED, authenticateUser));

        if (authnRequest != null) {
            subject.getSubjectConfirmations()
                    .add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                            new DateTime().plusMinutes(1), authnRequest.getID(),
                            authnRequest.getAssertionConsumerServiceURL()));
        } else {
            subject.getSubjectConfirmations().add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                    new DateTime().plusMinutes(1), null, defaultAssertionConsumerService));
        }

        Conditions conditions = createSamlElement(Conditions.class);
        assertion.setConditions(conditions);

        conditions.setNotBefore(new DateTime());
        conditions.setNotOnOrAfter(new DateTime().plusMinutes(1));

        if (authenticateUserRoles != null) {
            AttributeStatement attributeStatement = createSamlElement(AttributeStatement.class);
            assertion.getAttributeStatements().add(attributeStatement);

            Attribute attribute = createSamlElement(Attribute.class);
            attributeStatement.getAttributes().add(attribute);

            attribute.setName("roles");
            attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:basic");

            for (String role : authenticateUserRoles) {
                attribute.getAttributeValues().add(createXSAny(AttributeValue.DEFAULT_ELEMENT_NAME, role));
            }
        }

        if (signResponses) {
            Signature signature = createSamlElement(Signature.class);
            assertion.setSignature(signature);

            signature.setSigningCredential(this.signingCredential);
            signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
            signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);

            Signer.signObject(signature);
        }

        String marshalledXml = marshallSamlXml(response);

        return Base64Support.encode(marshalledXml.getBytes("UTF-8"), Base64Support.UNCHUNKED);

    } catch (MarshallingException | SignatureException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #26
Source File: GenerateAuthnRequestResource.java    From verify-service-provider with MIT License 5 votes vote down vote up
@POST
public Response generateAuthnRequest(@Valid @Nullable RequestGenerationBody requestGenerationBody) {
    String entityId = entityIdService.getEntityId(requestGenerationBody);
    AuthnRequest authnRequest = this.authnRequestFactory.build(entityId);
    XmlObjectToBase64EncodedStringTransformer xmlToBase64Transformer = new XmlObjectToBase64EncodedStringTransformer();
    String samlRequest = xmlToBase64Transformer.apply(authnRequest);

    RequestResponseBody requestResponseBody = new RequestResponseBody(samlRequest, authnRequest.getID(), ssoLocation);

    LOG.info(String.format("AuthnRequest generated for entityId: %s with requestId: %s", entityId, requestResponseBody.getRequestId()));
    AuthnRequestAttributesHelper.logAuthnRequestAttributes(authnRequest);
    LOG.debug(String.format("AuthnRequest generated for entityId: %s with saml: %s", entityId, requestResponseBody.getSamlRequest()));

    return Response.ok(requestResponseBody).build();
}
 
Example #27
Source File: AuthnRequestAttributesHelper.java    From verify-service-provider with MIT License 5 votes vote down vote up
public static void logAuthnRequestAttributes(AuthnRequest authnRequest) {
    try {
        MDC.put(AuthnRequestAttibuteNames.REQUEST_ID, authnRequest.getID() != null ? authnRequest.getID() : "");
        MDC.put(AuthnRequestAttibuteNames.DESTINATION, authnRequest.getDestination() != null ? authnRequest.getDestination() : "");
        MDC.put(AuthnRequestAttibuteNames.ISSUE_INSTANT, authnRequest.getIssueInstant() != null ? authnRequest.getIssueInstant().toString() : "");
        MDC.put(AuthnRequestAttibuteNames.ISSUER, authnRequest.getIssuer() != null ? authnRequest.getIssuer().getValue() : "");
        log.info("AuthnRequest Attributes: ");
    } finally {
        MDC.remove(AuthnRequestAttibuteNames.REQUEST_ID);
        MDC.remove(AuthnRequestAttibuteNames.DESTINATION);
        MDC.remove(AuthnRequestAttibuteNames.ISSUE_INSTANT);
        MDC.remove(AuthnRequestAttibuteNames.ISSUER);
    }
}
 
Example #28
Source File: AuthnRequestFactoryTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void containsCorrectAttributes() throws KeyException {
    AuthnRequest authnRequest = factory.build(SERVICE_ENTITY_ID);

    assertThat(authnRequest.getID()).isNotEmpty();
    assertThat(authnRequest.getIssueInstant()).isNotNull();
    assertThat(authnRequest.getDestination()).isNotEmpty();
    assertThat(authnRequest.getIssuer()).isNotNull();
    assertThat(authnRequest.getSignature()).isNotNull();
}
 
Example #29
Source File: AuthnRequestFactoryTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldAddApplicationVersionInExtension() throws Exception {
    when(manifestReader.getAttributeValueFor(VerifyServiceProviderApplication.class, "Version")).thenReturn("some-version");

    AuthnRequest authnRequest = factory.build(SERVICE_ENTITY_ID);

    Extensions extensions = authnRequest.getExtensions();
    EncryptedAttribute encryptedAttribute = (EncryptedAttribute) extensions.getUnknownXMLObjects().get(0);

    Attribute attribute = decrypter.decrypt(encryptedAttribute);
    Version version = (Version) attribute.getAttributeValues().get(0);

    assertThat(attribute.getName()).isEqualTo("Versions");
    assertThat(version.getApplicationVersion().getValue()).isEqualTo("some-version");
}
 
Example #30
Source File: AuthnRequestBuilderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testCreateAuthnRequest() throws Exception {
    Document doc = DOMUtils.createDocument();

    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer("http://localhost:9001/app");
    NameIDPolicy nameIDPolicy =
        SamlpRequestComponentBuilder.createNameIDPolicy(
            true, "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent", "Issuer"
        );

    AuthnContextClassRef authnCtxClassRef =
        SamlpRequestComponentBuilder.createAuthnCtxClassRef(
            "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
        );
    RequestedAuthnContext authnCtx =
        SamlpRequestComponentBuilder.createRequestedAuthnCtxPolicy(
            AuthnContextComparisonTypeEnumeration.EXACT,
            Collections.singletonList(authnCtxClassRef), null
        );

    AuthnRequest authnRequest =
        SamlpRequestComponentBuilder.createAuthnRequest(
            "http://localhost:9001/sso", false, false,
            "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST", SAMLVersion.VERSION_20,
            issuer, nameIDPolicy, authnCtx
        );

    Element policyElement = OpenSAMLUtil.toDom(authnRequest, doc);
    doc.appendChild(policyElement);
    // String outputString = DOM2Writer.nodeToString(policyElement);
    assertNotNull(policyElement);
}