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

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

Introduction

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

Prototype

@org.codehaus.jackson.annotate.JsonAnySetter
    @com.fasterxml.jackson.annotation.JsonAnySetter
    public void addAdditionalInformation(String key, Object value) 

Source Link

Usage

From source file:com.cedac.security.oauth2.provider.client.MongoClientDetailsService.java

@SuppressWarnings("unchecked")
private ClientDetails toClientDetails(DBObject dbo) {
    final String clientId = (String) dbo.get(clientIdFieldName);
    final String resourceIds = collectionToCommaDelimitedString((Collection) dbo.get(resourceIdsFieldName));
    final String scopes = collectionToCommaDelimitedString((Collection) dbo.get(scopeFieldName));
    final String grantTypes = collectionToCommaDelimitedString(
            (Collection) dbo.get(authorizedGrantTypesFieldName));
    final String authorities = collectionToCommaDelimitedString((Collection) dbo.get(authoritiesFieldName));
    final String redirectUris = collectionToCommaDelimitedString(
            (Collection) dbo.get(registeredRedirectUrisFieldName));
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, resourceIds, scopes, grantTypes,
            authorities, redirectUris);/* ww w  . j  a  v  a 2  s . co  m*/
    clientDetails.setClientSecret((String) dbo.get(clientSecretFieldName));
    clientDetails.setAccessTokenValiditySeconds((Integer) dbo.get(accessTokenValidityFieldName));
    clientDetails.setRefreshTokenValiditySeconds((Integer) dbo.get(refreshTokenValidityFieldName));
    Object autoApprove = dbo.get(autoApproveFieldName);
    if (autoApprove != null) {
        if (autoApprove instanceof String) {
            clientDetails.setAutoApproveScopes(Collections.singleton((String) autoApprove));
        } else {
            clientDetails.setAutoApproveScopes((Collection<String>) dbo.get(autoApproveFieldName));
        }
    }
    DBObject additionalInfo = (DBObject) dbo.get(additionalInformationFieldName);
    if (additionalInfo != null) {
        for (String key : additionalInfo.keySet()) {
            clientDetails.addAdditionalInformation(key, additionalInfo.get(key));
        }
    }
    return clientDetails;
}

From source file:org.cloudfoundry.identity.uaa.client.JdbcClientMetadataProvisioning.java

protected void updateClientNameIfNotEmpty(ClientMetadata resource) {
    //we don't remove it, only set values
    if (hasText(resource.getClientName())) {
        BaseClientDetails client = (BaseClientDetails) clientDetailsService
                .loadClientByClientId(resource.getClientId());
        client.addAdditionalInformation(CLIENT_NAME, resource.getClientName());
        clientRegistrationService.updateClientDetails(client);
    }//  ww  w .  ja  v a2s .  c  om
}

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

protected BaseClientDetails createClientAndSpecifyProvider(String clientId, IdentityProvider provider,
        String redirectUri) throws Exception {

    RestTemplate identityClient = IntegrationTestUtils.getClientCredentialsTempate(IntegrationTestUtils
            .getClientCredentialsResource(baseUrl, new String[0], "identity", "identitysecret"));
    RestTemplate adminClient = IntegrationTestUtils.getClientCredentialsTempate(
            IntegrationTestUtils.getClientCredentialsResource(baseUrl, new String[0], "admin", "adminsecret"));
    String email = new RandomValueStringGenerator().generate() + "@samltesting.org";
    ScimUser user = IntegrationTestUtils.createUser(adminClient, baseUrl, email, "firstname", "lastname", email,
            true);/*from   w w w .  j  ava2  s.  c  o m*/
    IntegrationTestUtils.makeZoneAdmin(identityClient, baseUrl, user.getId(), Origin.UAA);

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

    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "openid", "authorization_code",
            "uaa.resource", redirectUri);
    clientDetails.setClientSecret("secret");
    List<String> idps = Arrays.asList(provider.getOriginKey());
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, idps);
    clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, true);
    IntegrationTestUtils.createClient(zoneAdminToken, baseUrl, clientDetails);

    return clientDetails;
}

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);//  w w w. j  av  a2s  .  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 a 2s.  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  .  j  av a 2  s.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.login.EmailChangeEmailServiceTest.java

private Map<String, String> setUpCompleteActivation(String username, String clientId, String redirectUri) {
    Map<String, String> codeData = new HashMap<>();
    codeData.put("user_id", "user-001");
    codeData.put("client_id", clientId);
    codeData.put("redirect_uri", redirectUri);
    codeData.put("email", "new@example.com");
    BaseClientDetails clientDetails = new BaseClientDetails("client-id", null, null, "authorization_grant",
            null, "http://app.com/*");
    clientDetails.addAdditionalInformation(CHANGE_EMAIL_REDIRECT_URL, "http://fallback.url/redirect");

    when(codeStore.retrieveCode("the_secret_code", IdentityZoneHolder.get().getId()))
            .thenReturn(new ExpiringCode("the_secret_code", new Timestamp(System.currentTimeMillis()),
                    JsonUtils.writeValueAsString(codeData), null));
    ScimUser user = new ScimUser("user-001", username, "", "");
    user.setPrimaryEmail("user@example.com");
    when(scimUserProvisioning.retrieve("user-001", IdentityZoneHolder.get().getId())).thenReturn(user);

    when(clientDetailsService.loadClientByClientId(clientId, "uaa")).thenReturn(clientDetails);

    Map<String, String> response = emailChangeEmailService.completeVerification("the_secret_code");

    ScimUser updatedUser = new ScimUser("user-001", "new@example.com", "", "");
    user.setPrimaryEmail("new@example.com");

    verify(scimUserProvisioning).update("user-001", updatedUser, IdentityZoneHolder.get().getId());
    return response;
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void refreshAccessToken_withClient_withAutoApproveField() throws Exception {
    String clientId = "testclient" + generator.generate();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "uaa.user,other.scope",
            "authorization_code,refresh_token", "uaa.resource", TEST_REDIRECT_URI);
    clientDetails.setAutoApproveScopes(Arrays.asList("uaa.user"));
    clientDetails.setClientSecret("secret");
    clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, Arrays.asList("other.scope"));
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Arrays.asList("uaa"));
    clientDetailsService.addClientDetails(clientDetails);

    String username = "testuser" + generator.generate();
    String userScopes = "uaa.user,other.scope";
    ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZone.getUaa().getId());

    MockHttpSession session = getAuthenticatedSession(developer);

    String state = generator.generate();

    MvcResult result = getMockMvc()/*from   www  .j  a  va 2s .  com*/
            .perform(get("/oauth/authorize").session(session).param(OAuth2Utils.RESPONSE_TYPE, "code")
                    .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId))
            .andExpect(status().isFound()).andReturn();

    URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?"));
    Map query = splitQuery(url);
    String code = ((List<String>) query.get("code")).get(0);
    state = ((List<String>) query.get("state")).get(0);

    MockHttpServletRequestBuilder oauthTokenPost = post("/oauth/token")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE).accept(MediaType.APPLICATION_JSON_VALUE)
            .param(OAuth2Utils.RESPONSE_TYPE, "token").param(OAuth2Utils.GRANT_TYPE, "authorization_code")
            .param(OAuth2Utils.CLIENT_ID, clientId).param("client_secret", "secret").param("code", code)
            .param("state", state);

    MvcResult mvcResult = getMockMvc().perform(oauthTokenPost).andReturn();
    OAuth2RefreshToken refreshToken = JsonUtils
            .readValue(mvcResult.getResponse().getContentAsString(), CompositeAccessToken.class)
            .getRefreshToken();

    MockHttpServletRequestBuilder postForRefreshToken = post("/oauth/token")
            .header("Authorization", "Basic " + new String(Base64.encode((clientId + ":" + SECRET).getBytes())))
            .param(GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, refreshToken.getValue());
    getMockMvc().perform(postForRefreshToken).andExpect(status().isOk());
}