Example usage for org.springframework.security.oauth2.provider.client BaseClientDetails setClientSecret

List of usage examples for org.springframework.security.oauth2.provider.client BaseClientDetails setClientSecret

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.provider.client BaseClientDetails setClientSecret.

Prototype

public void setClientSecret(String clientSecret) 

Source Link

Usage

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginIT.java

@Test
public void testSamlLoginClientIDPAuthorizationAutomaticRedirectInZone1() throws Exception {
    //ensure we are able to resolve DNS for hostname testzone1.localhost
    assumeTrue("Expected testzone1/2.localhost to resolve to 127.0.0.1", doesSupportZoneDNS());
    String zoneId = "testzone1";

    //identity client token
    RestTemplate identityClient = IntegrationTestUtils
            .getClientCredentialsTempate(IntegrationTestUtils.getClientCredentialsResource(baseUrl,
                    new String[] { "zones.write", "zones.read", "scim.zones" }, "identity", "identitysecret"));
    //admin client token - to create users
    RestTemplate adminClient = IntegrationTestUtils.getClientCredentialsTempate(
            IntegrationTestUtils.getClientCredentialsResource(baseUrl, new String[0], "admin", "adminsecret"));
    //create the zone
    IntegrationTestUtils.createZoneOrUpdateSubdomain(identityClient, baseUrl, zoneId, zoneId);

    //create a zone admin user
    String email = new RandomValueStringGenerator().generate() + "@samltesting.org";
    ScimUser user = IntegrationTestUtils.createUser(adminClient, baseUrl, email, "firstname", "lastname", email,
            true);/*www.  j  a v  a  2  s . c o m*/
    IntegrationTestUtils.makeZoneAdmin(identityClient, baseUrl, user.getId(), zoneId);

    //get the zone admin token
    String zoneAdminToken = IntegrationTestUtils.getAuthorizationCodeToken(serverRunning,
            UaaTestAccounts.standard(serverRunning), "identity", "identitysecret", email, "secr3T");

    IdentityProviderDefinition identityProviderDefinition = createTestZone1IDP("simplesamlphp");
    IdentityProvider provider = new IdentityProvider();
    provider.setIdentityZoneId(zoneId);
    provider.setType(Origin.SAML);
    provider.setActive(true);
    provider.setConfig(JsonUtils.writeValueAsString(identityProviderDefinition));
    provider.setOriginKey(identityProviderDefinition.getIdpEntityAlias());
    provider.setName("simplesamlphp for testzone1");

    provider = IntegrationTestUtils.createOrUpdateProvider(zoneAdminToken, baseUrl, provider);
    assertEquals(provider.getOriginKey(),
            provider.getConfigValue(IdentityProviderDefinition.class).getIdpEntityAlias());

    List<String> idps = Arrays.asList(provider.getOriginKey());
    String clientId = UUID.randomUUID().toString();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "openid", "authorization_code",
            "uaa.none", baseUrl);
    clientDetails.setClientSecret("secret");
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, idps);
    clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, true);
    clientDetails = IntegrationTestUtils.createClientAsZoneAdmin(zoneAdminToken, baseUrl, zoneId,
            clientDetails);

    String zoneUrl = baseUrl.replace("localhost", "testzone1.localhost");

    webDriver.get(zoneUrl + "/logout.do");

    String authUrl = zoneUrl + "/oauth/authorize?client_id=" + clientId + "&redirect_uri="
            + URLEncoder.encode(zoneUrl) + "&response_type=code&state=8tp0tR";
    webDriver.get(authUrl);
    //we should now be in the Simple SAML PHP site
    webDriver.findElement(By.xpath("//h2[contains(text(), 'Enter your username and password')]"));
    webDriver.findElement(By.name("username")).clear();
    webDriver.findElement(By.name("username")).sendKeys(testAccounts.getUserName());
    webDriver.findElement(By.name("password")).sendKeys("koala");
    webDriver.findElement(By.xpath("//input[@value='Login']")).click();

    assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), Matchers.containsString("Where to?"));
    webDriver.get(baseUrl + "/logout.do");
    webDriver.get(zoneUrl + "/logout.do");
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginIT.java

@Test
public void testLoginPageShowsIDPsForAuthcodeClient() throws Exception {
    IdentityProvider provider = createIdentityProvider("simplesamlphp");
    IdentityProvider provider2 = createIdentityProvider("simplesamlphp2");
    List<String> idps = Arrays.asList(
            provider.getConfigValue(IdentityProviderDefinition.class).getIdpEntityAlias(),
            provider2.getConfigValue(IdentityProviderDefinition.class).getIdpEntityAlias());

    String adminAccessToken = testClient.getOAuthAccessToken("admin", "adminsecret", "client_credentials",
            "clients.read clients.write clients.secret");

    String clientId = UUID.randomUUID().toString();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "openid", "authorization_code",
            "uaa.none", "http://localhost:8080/login");
    clientDetails.setClientSecret("secret");
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, idps);

    testClient.createClient(adminAccessToken, clientDetails);

    webDriver.get(baseUrl + "/oauth/authorize?client_id=" + clientId
            + "&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Flogin&response_type=code&state=8tp0tR");
    webDriver.findElement(By.xpath(/*from   ww w. j a v a2  s  .  c om*/
            "//a[text()='" + provider.getConfigValue(IdentityProviderDefinition.class).getLinkText() + "']"));
    webDriver.findElement(By.xpath(
            "//a[text()='" + provider2.getConfigValue(IdentityProviderDefinition.class).getLinkText() + "']"));
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginIT.java

@Test
public void testLoginSamlOnlyProviderNoUsernamePassword() throws Exception {
    IdentityProvider provider = createIdentityProvider("simplesamlphp");
    IdentityProvider provider2 = createIdentityProvider("simplesamlphp2");
    List<String> idps = Arrays.asList(provider.getOriginKey(), provider2.getOriginKey());
    webDriver.get(baseUrl + "/logout.do");
    String adminAccessToken = testClient.getOAuthAccessToken("admin", "adminsecret", "client_credentials",
            "clients.read clients.write clients.secret");

    String clientId = UUID.randomUUID().toString();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "openid", "authorization_code",
            "uaa.none", "http://localhost:8080/uaa/login");
    clientDetails.setClientSecret("secret");
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, idps);
    testClient.createClient(adminAccessToken, clientDetails);
    webDriver.get(baseUrl + "/oauth/authorize?client_id=" + clientId
            + "&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fuaa%3Alogin&response_type=code&state=8tp0tR");
    try {/*from w  ww.ja va 2s . c o m*/
        webDriver.findElement(By.name("username"));
        fail("Element username should not be present");
    } catch (NoSuchElementException x) {
    }
    try {
        webDriver.findElement(By.name("password"));
        fail("Element username should not be present");
    } catch (NoSuchElementException x) {
    }
    webDriver.get(baseUrl + "/logout.do");
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginIT.java

@Test
public void testSamlLoginClientIDPAuthorizationAutomaticRedirect() throws Exception {
    IdentityProvider provider = createIdentityProvider("simplesamlphp");
    assertEquals(provider.getOriginKey(),
            provider.getConfigValue(IdentityProviderDefinition.class).getIdpEntityAlias());
    List<String> idps = Arrays.asList(provider.getOriginKey());
    webDriver.get(baseUrl + "/logout.do");
    String adminAccessToken = testClient.getOAuthAccessToken("admin", "adminsecret", "client_credentials",
            "clients.read clients.write clients.secret");

    String clientId = UUID.randomUUID().toString();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "openid", "authorization_code",
            "uaa.none", baseUrl);
    clientDetails.setClientSecret("secret");
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, idps);
    clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, true);

    testClient.createClient(adminAccessToken, clientDetails);

    webDriver.get(baseUrl + "/oauth/authorize?client_id=" + clientId + "&redirect_uri="
            + URLEncoder.encode(baseUrl) + "&response_type=code&state=8tp0tR");
    //we should now be in the Simple SAML PHP site
    webDriver.findElement(By.xpath("//h2[contains(text(), 'Enter your username and password')]"));
    webDriver.findElement(By.name("username")).clear();
    webDriver.findElement(By.name("username")).sendKeys(testAccounts.getUserName());
    webDriver.findElement(By.name("password")).sendKeys("koala");
    webDriver.findElement(By.xpath("//input[@value='Login']")).click();

    assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), Matchers.containsString("Where to?"));
    webDriver.get(baseUrl + "/logout.do");
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginIT.java

@Test
public void testLoginClientIDPAuthorizationAlreadyLoggedIn() throws Exception {
    webDriver.get(baseUrl + "/logout.do");
    String adminAccessToken = testClient.getOAuthAccessToken("admin", "adminsecret", "client_credentials",
            "clients.read clients.write clients.secret");

    String clientId = UUID.randomUUID().toString();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "openid", "authorization_code",
            "uaa.none", "http://localhost:8080/login");
    clientDetails.setClientSecret("secret");
    List<String> idps = Arrays.asList("okta-local"); //not authorized for the current IDP
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, idps);

    testClient.createClient(adminAccessToken, clientDetails);

    webDriver.findElement(By.name("username")).clear();
    webDriver.findElement(By.name("username")).sendKeys(testAccounts.getUserName());
    webDriver.findElement(By.name("password")).sendKeys("koala");
    webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();

    webDriver.get(baseUrl + "/oauth/authorize?client_id=" + clientId
            + "&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Flogin&response_type=code&state=8tp0tR");

    assertThat(webDriver.findElement(By.cssSelector("p")).getText(),
            Matchers.containsString("The application is not authorized for your account."));
    webDriver.get(baseUrl + "/logout.do");
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginWithLocalIdpIT.java

@SuppressWarnings("unchecked")
@Test/*from   w  ww  .j a v a2  s.c o m*/
public void testLocalSamlIdpLoginInTestZone1Works() throws Exception {
    assumeTrue("Expected testzone1/2.localhost to resolve to 127.0.0.1", doesSupportZoneDNS());
    String zoneId = "testzone1";

    RestTemplate identityClient = IntegrationTestUtils
            .getClientCredentialsTemplate(IntegrationTestUtils.getClientCredentialsResource(baseUrl,
                    new String[] { "zones.write", "zones.read", "scim.zones" }, "identity", "identitysecret"));
    RestTemplate adminClient = IntegrationTestUtils.getClientCredentialsTemplate(
            IntegrationTestUtils.getClientCredentialsResource(baseUrl, new String[0], "admin", "adminsecret"));
    IdentityZone zone = IntegrationTestUtils.createZoneOrUpdateSubdomain(identityClient, baseUrl, zoneId,
            zoneId);
    String email = new RandomValueStringGenerator().generate() + "@samltesting.org";
    ScimUser user = IntegrationTestUtils.createUser(adminClient, baseUrl, email, "firstname", "lastname", email,
            true);
    IntegrationTestUtils.makeZoneAdmin(identityClient, baseUrl, user.getId(), zoneId);

    String zoneAdminToken = IntegrationTestUtils.getAuthorizationCodeToken(serverRunning,
            UaaTestAccounts.standard(serverRunning), "identity", "identitysecret", email, "secr3T");

    String testZone1Url = baseUrl.replace("localhost", zoneId + ".localhost");
    String zoneAdminClientId = new RandomValueStringGenerator().generate() + "-" + zoneId + "-admin";
    BaseClientDetails clientDetails = new BaseClientDetails(zoneAdminClientId, null, "uaa.none",
            "client_credentials", "uaa.admin,scim.read,scim.write,uaa.resource", testZone1Url);
    clientDetails.setClientSecret("secret");
    IntegrationTestUtils.createClientAsZoneAdmin(zoneAdminToken, baseUrl, zoneId, clientDetails);

    RestTemplate zoneAdminClient = IntegrationTestUtils.getClientCredentialsTemplate(IntegrationTestUtils
            .getClientCredentialsResource(testZone1Url, new String[0], zoneAdminClientId, "secret"));
    String zoneUserEmail = new RandomValueStringGenerator().generate() + "@samltesting.org";
    IntegrationTestUtils.createUser(zoneAdminClient, testZone1Url, zoneUserEmail, "Dana", "Scully",
            zoneUserEmail, true);

    SamlIdentityProviderDefinition samlIdentityProviderDefinition = createZone1IdpDefinition(IDP_ENTITY_ID);
    IdentityProvider<SamlIdentityProviderDefinition> provider = new IdentityProvider<>();
    provider.setIdentityZoneId(zoneId);
    provider.setType(OriginKeys.SAML);
    provider.setActive(true);
    provider.setConfig(samlIdentityProviderDefinition);
    provider.setOriginKey(samlIdentityProviderDefinition.getIdpEntityAlias());
    provider.setName("Local SAML IdP for testzone1");
    provider = IntegrationTestUtils.createOrUpdateProvider(zoneAdminToken, baseUrl, provider);
    assertNotNull(provider.getId());

    SamlServiceProviderDefinition samlServiceProviderDefinition = createZone1SamlSpDefinition(
            "cloudfoundry-saml-login");
    SamlServiceProvider sp = new SamlServiceProvider();
    sp.setIdentityZoneId(zoneId);
    sp.setActive(true);
    sp.setConfig(samlServiceProviderDefinition);
    sp.setEntityId("testzone1.cloudfoundry-saml-login");
    sp.setName("Local SAML SP for testzone1");
    sp = createOrUpdateSamlServiceProvider(zoneAdminToken, baseUrl, sp);

    webDriver.get(baseUrl + "/logout.do");
    webDriver.get(testZone1Url + "/logout.do");
    webDriver.get(testZone1Url + "/login");
    Assert.assertEquals(zone.getName(), webDriver.getTitle());

    List<WebElement> elements = webDriver
            .findElements(By.xpath("//a[text()='" + samlIdentityProviderDefinition.getLinkText() + "']"));
    assertNotNull(elements);
    assertEquals(1, elements.size());

    WebElement element = elements.get(0);
    assertNotNull(element);
    element.click();
    webDriver.findElement(By.xpath("//h1[contains(text(), 'Welcome to The Twiglet Zone[" + zoneId + "]!')]"));
    webDriver.findElement(By.name("username")).clear();
    webDriver.findElement(By.name("username")).sendKeys(zoneUserEmail);
    webDriver.findElement(By.name("password")).sendKeys("secr3T");
    webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();
    assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), Matchers.containsString("Where to?"));

    webDriver.get(baseUrl + "/logout.do");
    webDriver.get(testZone1Url + "/logout.do");

    // disable the provider
    provider.setActive(false);
    provider = IntegrationTestUtils.createOrUpdateProvider(zoneAdminToken, baseUrl, provider);
    assertNotNull(provider.getId());
    webDriver.get(testZone1Url + "/login");
    Assert.assertEquals(zone.getName(), webDriver.getTitle());
    elements = webDriver
            .findElements(By.xpath("//a[text()='" + samlIdentityProviderDefinition.getLinkText() + "']"));
    assertNotNull(elements);
    assertEquals(0, elements.size());

    // enable the provider
    provider.setActive(true);
    provider = IntegrationTestUtils.createOrUpdateProvider(zoneAdminToken, baseUrl, provider);
    assertNotNull(provider.getId());
    webDriver.get(testZone1Url + "/login");
    Assert.assertEquals(zone.getName(), webDriver.getTitle());
    elements = webDriver
            .findElements(By.xpath("//a[text()='" + samlIdentityProviderDefinition.getLinkText() + "']"));
    assertNotNull(elements);
    assertEquals(1, elements.size());
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginWithLocalIdpIT.java

private void createZoneUser(String idpZoneId, String zoneAdminToken, String zoneUserEmail, String zoneUrl)
        throws Exception {
    String zoneAdminClientId = new RandomValueStringGenerator().generate() + "-" + idpZoneId + "-admin";
    BaseClientDetails clientDetails = new BaseClientDetails(zoneAdminClientId, null, "uaa.none",
            "client_credentials", "uaa.admin,scim.read,scim.write,uaa.resource", zoneUrl);
    clientDetails.setClientSecret("secret");
    IntegrationTestUtils.createClientAsZoneAdmin(zoneAdminToken, baseUrl, idpZoneId, clientDetails);

    RestTemplate zoneAdminClient = IntegrationTestUtils.getClientCredentialsTemplate(IntegrationTestUtils
            .getClientCredentialsResource(zoneUrl, new String[0], zoneAdminClientId, "secret"));
    IntegrationTestUtils.createUser(zoneAdminClient, zoneUrl, zoneUserEmail, "Dana", "Scully", zoneUserEmail,
            true);/*  w w  w  .  j a  v  a 2  s  .  c  o m*/
}

From source file:org.cloudfoundry.identity.uaa.integration.ScimGroupEndpointsIntegrationTests.java

private void createTestClient(String name, String secret, String scope) throws Exception {
    OAuth2AccessToken token = getClientCredentialsAccessToken("clients.read,clients.write,clients.admin");
    HttpHeaders headers = getAuthenticatedHeaders(token);
    BaseClientDetails client = new BaseClientDetails(name, "", scope, "authorization_code,password",
            "scim.read,scim.write");
    client.setClientSecret(secret);
    ResponseEntity<Void> result = serverRunning.getRestTemplate().exchange(
            serverRunning.getUrl("/oauth/clients"), HttpMethod.POST,
            new HttpEntity<BaseClientDetails>(client, headers), Void.class);
    assertEquals(HttpStatus.CREATED, result.getStatusCode());
}

From source file:org.cloudfoundry.identity.uaa.mock.providers.IdentityProviderEndpointDocs.java

void createLDAPProvider(IdentityProvider<LdapIdentityProviderDefinition> identityProvider,
        FieldDescriptor[] fields, String name) throws Exception {
    Map<String, Object> attributeMappings = new HashedMap(identityProvider.getConfig().getAttributeMappings());
    attributeMappings.put(EMAIL_VERIFIED_ATTRIBUTE_NAME, "emailVerified");
    identityProvider.getConfig().setAttributeMappings(attributeMappings);
    BaseClientDetails admin = new BaseClientDetails("admin", null, "", "client_credentials", "uaa.admin",
            "http://redirect.url");
    admin.setClientSecret("adminsecret");

    IdentityZoneCreationResult zone = MockMvcUtils.createOtherIdentityZoneAndReturnResult(
            new RandomValueStringGenerator(8).generate().toLowerCase(), mockMvc, webApplicationContext, admin,
            IdentityZoneHolder.getCurrentZoneId());

    Snippet requestFields = requestFields(fields);

    Snippet responseFields = responseFields(
            (FieldDescriptor[]) ArrayUtils.addAll(ldapAllFields, new FieldDescriptor[] { VERSION, ID,
                    ADDITIONAL_CONFIGURATION, IDENTITY_ZONE_ID, CREATED, LAST_MODIFIED }));

    ResultActions resultActions = mockMvc
            .perform(post("/identity-providers")
                    .header(IdentityZoneSwitchingFilter.SUBDOMAIN_HEADER, zone.getIdentityZone().getSubdomain())
                    .param("rawConfig", "true").header("Authorization", "Bearer " + zone.getZoneAdminToken())
                    .contentType(APPLICATION_JSON)
                    .content(serializeExcludingProperties(identityProvider, "id", "version", "created",
                            "last_modified", "identityZoneId", "config.additionalConfiguration")))
            .andExpect(status().isCreated());

    resultActions.andDo(document("{ClassName}/" + name, preprocessRequest(prettyPrint()),
            preprocessResponse(prettyPrint()),
            requestHeaders(headerWithName("Authorization").description(
                    "Bearer token containing `zones.<zone id>.admin` or `uaa.admin` or `idps.write` (only in the same zone that you are a user of)"),
                    IDENTITY_ZONE_ID_HEADER, IDENTITY_ZONE_SUBDOMAIN_HEADER),
            commonRequestParams, requestFields, responseFields));

    mockMvc.perform(post("/login.do").header("Host", zone.getIdentityZone().getSubdomain() + ".localhost")
            .with(cookieCsrf()).param("username", "marissa4").param("password", "ldap4"))
            .andExpect(status().isFound()).andExpect(redirectedUrl("/"));

}

From source file:org.cloudfoundry.identity.uaa.mock.providers.IdentityProviderEndpointsDocs.java

public void createLDAPProvider(IdentityProvider<LdapIdentityProviderDefinition> identityProvider,
        FieldDescriptor[] fields, String name) throws Exception {
    BaseClientDetails admin = new BaseClientDetails("admin", null, "", "client_credentials", "uaa.admin");
    admin.setClientSecret("adminsecret");

    IdentityZoneCreationResult zone = MockMvcUtils.createOtherIdentityZoneAndReturnResult(
            new RandomValueStringGenerator(8).generate().toLowerCase(), getMockMvc(),
            getWebApplicationContext(), admin);

    Snippet requestFields = requestFields(fields);

    Snippet responseFields = responseFields(
            (FieldDescriptor[]) ArrayUtils.addAll(ldapAllFields, new FieldDescriptor[] { VERSION, ID,
                    ADDITIONAL_CONFIGURATION, IDENTITY_ZONE_ID, CREATED, LAST_MODIFIED }));

    ResultActions resultActions = getMockMvc()
            .perform(post("/identity-providers")
                    .header(IdentityZoneSwitchingFilter.SUBDOMAIN_HEADER, zone.getIdentityZone().getSubdomain())
                    .param("rawConfig", "true").header("Authorization", "Bearer " + zone.getZoneAdminToken())
                    .contentType(APPLICATION_JSON)
                    .content(serializeExcludingProperties(identityProvider, "id", "version", "created",
                            "last_modified", "identityZoneId", "config.additionalConfiguration")))
            .andExpect(status().isCreated());

    resultActions.andDo(document("{ClassName}/" + name, preprocessRequest(prettyPrint()),
            preprocessResponse(prettyPrint()),
            requestHeaders(headerWithName("Authorization").description(
                    "Bearer token containing `zones.<zone id>.admin` or `uaa.admin` or `idps.write` (only in the same zone that you are a user of)"),
                    headerWithName("X-Identity-Zone-Id").description(
                            "May include this header to administer another zone if using `zones.<zone id>.admin` or `uaa.admin` scope against the default UAA zone.")
                            .optional()),
            commonRequestParams, requestFields, responseFields));

    getMockMvc()//from   w w  w  .  ja v  a  2  s .  c o  m
            .perform(post("/login.do").header("Host", zone.getIdentityZone().getSubdomain() + ".localhost")
                    .with(cookieCsrf()).param("username", "marissa4").param("password", "ldap4"))
            .andExpect(status().isFound()).andExpect(redirectedUrl("/"));

}