Search in sources :

Example 6 with SAML2

use of org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.StandardInboundProtocols.SAML2 in project msf4j by wso2.

the class SSOAgentSampleFilter method doFilter.

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    String httpBinding = servletRequest.getParameter(SSOAgentConstants.SSOAgentConfig.SAML2.HTTP_BINDING);
    if (httpBinding != null && !httpBinding.isEmpty()) {
        if ("HTTP-POST".equals(httpBinding)) {
            httpBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
        } else if ("HTTP-Redirect".equals(httpBinding)) {
            httpBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect";
        } else {
            LOGGER.log(Level.INFO, "Unknown SAML2 HTTP Binding. Defaulting to HTTP-POST");
            httpBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
        }
    } else {
        LOGGER.log(Level.INFO, "SAML2 HTTP Binding not found in request. Defaulting to HTTP-POST");
        httpBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
    }
    SSOAgentConfig config = (SSOAgentConfig) filterConfig.getServletContext().getAttribute(SSOAgentConstants.CONFIG_BEAN_NAME);
    config.getSAML2().setHttpBinding(httpBinding);
    config.getOpenId().setClaimedId(servletRequest.getParameter(SSOAgentConstants.SSOAgentConfig.OpenID.CLAIMED_ID));
    config.getOpenId().setMode(servletRequest.getParameter(SSOAgentConstants.OpenID.OPENID_MODE));
    if (StringUtils.isNotEmpty(servletRequest.getParameter(USERNAME)) && StringUtils.isNotEmpty(servletRequest.getParameter(PASSWORD))) {
        String authorization = servletRequest.getParameter(USERNAME) + ":" + servletRequest.getParameter(PASSWORD);
        // Base64 encoded username:password value
        authorization = Base64.encode(authorization.getBytes(CHARACTER_ENCODING));
        String htmlPayload = "<html>\n" + "<body>\n" + "<p>You are now redirected back to " + properties.getProperty("SAML2.IdPURL") + " \n" + "If the redirection fails, please click the post button.</p>\n" + "<form method='post' action='" + properties.getProperty("SAML2.IdPURL") + "'>\n" + "<input type='hidden' name='sectoken' value='" + authorization + "'/>\n" + "<p>\n" + "<!--$saml_params-->\n" + "<button type='submit'>POST</button>\n" + "</p>\n" + "</form>\n" + "<script type='text/javascript'>\n" + "document.forms[0].submit();\n" + "</script>\n" + "</body>\n" + "</html>";
        config.getSAML2().setPostBindingRequestHTMLPayload(htmlPayload);
    } else {
        // Reset previously sent HTML payload
        config.getSAML2().setPostBindingRequestHTMLPayload(null);
    }
    servletRequest.setAttribute(SSOAgentConstants.CONFIG_BEAN_NAME, config);
    super.doFilter(servletRequest, servletResponse, filterChain);
}
Also used : SSOAgentConfig(org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig)

Example 7 with SAML2

use of org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.StandardInboundProtocols.SAML2 in project product-is by wso2.

the class OAuth2ServiceSAML2BearerGrantTestCase method testSAML2BearerInvalidAudience.

@Test
public void testSAML2BearerInvalidAudience() throws RemoteException, IdentitySAMLSSOConfigServiceIdentityException {
    try {
        client = HttpClientBuilder.create().build();
        // Set some invalid audience.
        ServiceProvider application = appMgtclient.getApplication(SERVICE_PROVIDER_NAME);
        SAMLSSOServiceProviderDTO[] serviceProviders = ssoConfigServiceClient.getServiceProviders().getServiceProviders();
        SAMLSSOServiceProviderDTO serviceProvider = null;
        for (SAMLSSOServiceProviderDTO serviceProviderDTO : serviceProviders) {
            if ("travelocity.com".equals(serviceProviderDTO.getIssuer())) {
                serviceProvider = serviceProviderDTO;
                break;
            }
        }
        Assert.assertNotNull(serviceProvider, "No service provider exists for issuer travelocity.com");
        serviceProvider.setRequestedAudiences(new String[] {});
        ssoConfigServiceClient.removeServiceProvider("travelocity.com");
        ssoConfigServiceClient.addServiceProvider(serviceProvider);
        appMgtclient.updateApplicationData(application);
        // Get a SAML response.
        String samlResponse = getSAMLResponse();
        // Extract the assertion from SAML response.
        String samlAssersion = getSAMLAssersion(samlResponse);
        // Send the extracted SAML assertion to token endpoint in SAML2 bearer grant.
        HttpResponse httpResponse = sendSAMLAssertion(samlAssersion);
        // We should get an http 400 error code.
        Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), 400);
        // We should get a non empty error message.
        Assert.assertTrue(StringUtils.isNotBlank(IOUtils.toString(httpResponse.getEntity().getContent())));
    } catch (Exception e) {
        Assert.fail("SAML Bearer Grant test failed with an exception.", e);
    } finally {
        // Restore the default service provider.
        ssoConfigServiceClient.removeServiceProvider("travelocity.com");
        ssoConfigServiceClient.addServiceProvider(createDefaultSSOServiceProviderDTO());
        // We have to initiate the http client again or other tests will fail.
        client = HttpClientBuilder.create().build();
    }
}
Also used : SAMLSSOServiceProviderDTO(org.wso2.carbon.identity.sso.saml.stub.types.SAMLSSOServiceProviderDTO) ServiceProvider(org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider) HttpResponse(org.apache.http.HttpResponse) TransformerException(javax.xml.transform.TransformerException) IdentitySAMLSSOConfigServiceIdentityException(org.wso2.carbon.identity.sso.saml.stub.IdentitySAMLSSOConfigServiceIdentityException) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) Test(org.testng.annotations.Test)

Example 8 with SAML2

use of org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.StandardInboundProtocols.SAML2 in project product-is by wso2.

the class RequestPathBasicAuthenticationSSOTest method testLoginSuccessRequestPath.

@Test(alwaysRun = true, description = "Request path authenticator login success")
public void testLoginSuccessRequestPath() throws Exception {
    HttpPost request = new HttpPost(String.format(SAMPLE_APP_URL, ISSUER_TRAVELOCITY_COM) + "/samlsso" + "?SAML2.HTTPBinding=HTTP-POST");
    List<NameValuePair> urlParameters = new ArrayList<>();
    urlParameters.add(new BasicNameValuePair("username", adminUsername));
    urlParameters.add(new BasicNameValuePair("password", adminPassword));
    request.setEntity(new UrlEncodedFormEntity(urlParameters));
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line;
    String samlRequest = "";
    String secToken = "";
    while ((line = rd.readLine()) != null) {
        if (line.contains("name='SAMLRequest'")) {
            String[] tokens = line.split("'");
            samlRequest = tokens[5];
        }
        if (line.contains("name='sectoken'")) {
            String[] tokens = line.split("'");
            secToken = tokens[5];
        }
    }
    EntityUtils.consume(response.getEntity());
    request = new HttpPost(isURL + "samlsso");
    urlParameters = new ArrayList<>();
    urlParameters.add(new BasicNameValuePair("sectoken", secToken));
    urlParameters.add(new BasicNameValuePair("SAMLRequest", samlRequest));
    request.setEntity(new UrlEncodedFormEntity(urlParameters));
    response = client.execute(request);
    if (Utils.requestMissingClaims(response)) {
        String pastrCookie = Utils.getPastreCookie(response);
        Assert.assertNotNull(pastrCookie, "pastr cookie not found in response.");
        EntityUtils.consume(response.getEntity());
        response = Utils.sendPOSTConsentMessage(response, isURL + "commonauth", USER_AGENT, String.format(ACS_URL, ISSUER_TRAVELOCITY_COM), client, pastrCookie);
        EntityUtils.consume(response.getEntity());
    }
    int responseCode = response.getStatusLine().getStatusCode();
    Assert.assertEquals(responseCode, 200, "Successful login response returned code " + responseCode);
    String samlResponse = "";
    rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    while ((line = rd.readLine()) != null) {
        if (line.contains("name='SAMLResponse'")) {
            String[] tokens = line.split("'");
            samlResponse = tokens[5];
        }
    }
    Base64 base64Decoder = new Base64();
    samlResponse = new String(base64Decoder.decode(samlResponse));
    Assert.assertTrue(samlResponse.contains(SAML_SUCCESS_TAG), "SAML response did not contained success state");
    EntityUtils.consume(response.getEntity());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) Base64(org.apache.commons.codec.binary.Base64) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BufferedReader(java.io.BufferedReader) Test(org.testng.annotations.Test) ISIntegrationTest(org.wso2.identity.integration.common.utils.ISIntegrationTest)

Example 9 with SAML2

use of org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.StandardInboundProtocols.SAML2 in project product-is by wso2.

the class SAMLWithRequestPathAuthenticationTest method testSMALRedirectBinding.

@Test(alwaysRun = true, description = "Test SAML Redirect Binding with BasicAuth request path authentication", dependsOnMethods = { "testLoginSuccess" })
public void testSMALRedirectBinding() throws Exception {
    HttpGet request = new HttpGet(TRAVELOCITY_SAMPLE_APP_URL + "/samlsso?SAML2.HTTPBinding=HTTP-Redirect");
    CloseableHttpClient client = HttpClientBuilder.create().disableRedirectHandling().build();
    // Do a redirect to travelocity app.
    HttpResponse response = client.execute(request);
    EntityUtils.consume(response.getEntity());
    // Modify the location header to included the secToken.
    String location = Utils.getRedirectUrl(response) + "&" + "sectoken=" + getSecToken(adminUsername, adminPassword);
    // Do a GET manually to send the SAML Request to IS.
    HttpGet requestToIS = new HttpGet(location);
    HttpResponse samlResponseFromIS = client.execute(requestToIS);
    String samlResponse = extractDataFromResponse(samlResponseFromIS, "SAMLResponse", 5);
    EntityUtils.consume(samlResponseFromIS.getEntity());
    // Send the SAMLResponse to ACS.
    HttpResponse finalSAMLResponse = sendSAMLMessage(client, ACS_URL, samlResponse);
    String resultPage = extractDataFromResponse(finalSAMLResponse);
    Assert.assertTrue(resultPage.contains("You are logged in as " + adminUsername), "SAML SSO Login failed " + "with BasicAuthRequestPath authentication failed.");
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) Test(org.testng.annotations.Test) ISIntegrationTest(org.wso2.identity.integration.common.utils.ISIntegrationTest)

Example 10 with SAML2

use of org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.StandardInboundProtocols.SAML2 in project product-is by wso2.

the class OIDCFederatedIdpInitLogoutTest method updateServiceProviderWithSAMLConfigs.

private void updateServiceProviderWithSAMLConfigs(int portOffset, String issuerName, String acsUrl, ServiceProvider serviceProvider) throws Exception {
    String attributeConsumingServiceIndex = super.createSAML2WebSSOConfiguration(portOffset, getSAMLSSOServiceProviderDTO(issuerName, acsUrl));
    Assert.assertNotNull(attributeConsumingServiceIndex, "Failed to create SAML2 Web SSO configuration for" + " issuer '" + issuerName + "'");
    InboundAuthenticationRequestConfig samlAuthenticationRequestConfig = new InboundAuthenticationRequestConfig();
    samlAuthenticationRequestConfig.setInboundAuthKey(issuerName);
    samlAuthenticationRequestConfig.setInboundAuthType(FEDERATED_IS_SP_INBOUND_AUTH_TYPE_SAMLSSO);
    org.wso2.carbon.identity.application.common.model.xsd.Property property = new org.wso2.carbon.identity.application.common.model.xsd.Property();
    property.setName("attrConsumServiceIndex");
    property.setValue(attributeConsumingServiceIndex);
    samlAuthenticationRequestConfig.setProperties(new org.wso2.carbon.identity.application.common.model.xsd.Property[] { property });
    serviceProvider.getInboundAuthenticationConfig().setInboundAuthenticationRequestConfigs(new InboundAuthenticationRequestConfig[] { samlAuthenticationRequestConfig });
}
Also used : InboundAuthenticationRequestConfig(org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig) IdentityProviderProperty(org.wso2.carbon.identity.application.common.model.idp.xsd.IdentityProviderProperty) Property(org.wso2.carbon.identity.application.common.model.idp.xsd.Property)

Aggregations

Test (org.testng.annotations.Test)16 InboundAuthenticationRequestConfig (org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig)14 HttpResponse (org.apache.http.HttpResponse)11 IOException (java.io.IOException)10 RemoteException (java.rmi.RemoteException)9 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)9 ServiceProvider (org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider)9 IdentitySAMLSSOConfigServiceIdentityException (org.wso2.carbon.identity.sso.saml.stub.IdentitySAMLSSOConfigServiceIdentityException)9 SAXException (org.xml.sax.SAXException)9 UnsupportedEncodingException (java.io.UnsupportedEncodingException)8 ArrayList (java.util.ArrayList)7 XPathExpressionException (javax.xml.xpath.XPathExpressionException)7 ConfigurationException (org.opensaml.xml.ConfigurationException)7 ValidationException (org.opensaml.xml.validation.ValidationException)7 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)7 ISIntegrationTest (org.wso2.identity.integration.common.utils.ISIntegrationTest)7 Property (org.wso2.carbon.identity.application.common.model.idp.xsd.Property)5 BufferedReader (java.io.BufferedReader)4 InputStreamReader (java.io.InputStreamReader)4 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)4