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

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

Introduction

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

Prototype

@org.codehaus.jackson.annotate.JsonIgnore
    @com.fasterxml.jackson.annotation.JsonIgnore
    public String getClientSecret() 

Source Link

Usage

From source file:org.cloudfoundry.identity.uaa.api.client.test.UaaClientOperationTest.java

@Test
public void testGetClient() throws Exception {
    ignoreIfUaaNotRunning();//from  ww w. j  a v a 2 s. co  m

    BaseClientDetails client = operations.findById("app");

    assertEquals("ID wrong", "app", client.getClientId());
    assertNull("Secret should not be returned", client.getClientSecret());
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimUserEndpointsMockMvcTests.java

@Test
public void verification_link_in_non_default_zone() throws Exception {
    String subdomain = generator.generate().toLowerCase();
    MockMvcUtils.IdentityZoneCreationResult zoneResult = utils()
            .createOtherIdentityZoneAndReturnResult(subdomain, getMockMvc(), getWebApplicationContext(), null);
    String zonedClientId = "zonedClientId";
    String zonedClientSecret = "zonedClientSecret";
    BaseClientDetails zonedClientDetails = (BaseClientDetails) utils().createClient(this.getMockMvc(),
            zoneResult.getZoneAdminToken(), zonedClientId, zonedClientSecret, Collections.singleton("oauth"),
            null, Arrays.asList(new String[] { "client_credentials" }), "scim.create", null,
            zoneResult.getIdentityZone());
    zonedClientDetails.setClientSecret(zonedClientSecret);
    String zonedScimCreateToken = utils().getClientCredentialsOAuthAccessToken(getMockMvc(),
            zonedClientDetails.getClientId(), zonedClientDetails.getClientSecret(), "scim.create", subdomain);

    ScimUser joel = setUpScimUser(zoneResult.getIdentityZone());

    MockHttpServletRequestBuilder get = MockMvcRequestBuilders.get("/Users/" + joel.getId() + "/verify-link")
            .header("Host", subdomain + ".localhost").header("Authorization", "Bearer " + zonedScimCreateToken)
            .param("redirect_uri", HTTP_REDIRECT_EXAMPLE_COM).accept(APPLICATION_JSON);

    MvcResult result = getMockMvc().perform(get).andExpect(status().isOk()).andReturn();
    VerificationResponse verificationResponse = JsonUtils.readValue(result.getResponse().getContentAsString(),
            VerificationResponse.class);
    assertThat(verificationResponse.getVerifyLink().toString(),
            startsWith("http://" + subdomain + ".localhost/verify_user"));

    String query = verificationResponse.getVerifyLink().getQuery();

    String code = getQueryStringParam(query, "code");
    assertThat(code, is(notNullValue()));

    ExpiringCode expiringCode = codeStore.retrieveCode(code);
    assertThat(expiringCode.getExpiresAt().getTime(), is(greaterThan(System.currentTimeMillis())));
    assertThat(expiringCode.getIntent(), is(REGISTRATION.name()));
    Map<String, String> data = JsonUtils.readValue(expiringCode.getData(),
            new TypeReference<Map<String, String>>() {
            });/*w  w  w  . ja  v  a  2s  . c o  m*/
    assertThat(data.get(InvitationConstants.USER_ID), is(notNullValue()));
    assertThat(data.get(CLIENT_ID), is(zonedClientDetails.getClientId()));
    assertThat(data.get(REDIRECT_URI), is(HTTP_REDIRECT_EXAMPLE_COM));
}

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

private void addNewClients() throws Exception {
    for (Map.Entry<String, Map<String, Object>> entry : clients.entrySet()) {
        String clientId = entry.getKey();
        Map<String, Object> map = entry.getValue();
        BaseClientDetails client = new BaseClientDetails(clientId, (String) map.get("resource-ids"),
                (String) map.get("scope"), (String) map.get("authorized-grant-types"),
                (String) map.get("authorities"), getRedirectUris(map));
        client.setClientSecret((String) map.get("secret"));
        Integer validity = (Integer) map.get("access-token-validity");
        Boolean override = (Boolean) map.get("override");
        if (override == null) {
            override = defaultOverride;//from  ww  w .  j  a v a2 s . c  o  m
        }
        Map<String, Object> info = new HashMap<String, Object>(map);
        if (validity != null) {
            client.setAccessTokenValiditySeconds(validity);
        }
        validity = (Integer) map.get("refresh-token-validity");
        if (validity != null) {
            client.setRefreshTokenValiditySeconds(validity);
        }
        // UAA does not use the resource ids in client registrations
        client.setResourceIds(Collections.singleton("none"));
        if (client.getScope().isEmpty()) {
            client.setScope(Collections.singleton("uaa.none"));
        }
        if (client.getAuthorities().isEmpty()) {
            client.setAuthorities(Collections.singleton(UaaAuthority.UAA_NONE));
        }
        if (client.getAuthorizedGrantTypes().contains("authorization_code")) {
            client.getAuthorizedGrantTypes().add("refresh_token");
        }
        for (String key : Arrays.asList("resource-ids", "scope", "authorized-grant-types", "authorities",
                "redirect-uri", "secret", "id", "override", "access-token-validity", "refresh-token-validity",
                "show-on-homepage", "app-launch-url", "app-icon")) {
            info.remove(key);
        }

        client.setAdditionalInformation(info);
        try {
            clientRegistrationService.addClientDetails(client);
        } catch (ClientAlreadyExistsException e) {
            if (override == null || override) {
                logger.debug("Overriding client details for " + clientId);
                clientRegistrationService.updateClientDetails(client);
                if (StringUtils.hasText(client.getClientSecret())
                        && didPasswordChange(clientId, client.getClientSecret())) {
                    clientRegistrationService.updateClientSecret(clientId, client.getClientSecret());
                }
            } else {
                // ignore it
                logger.debug(e.getMessage());
            }
        }
        ClientMetadata clientMetadata = buildClientMetadata(map, clientId);
        clientMetadataProvisioning.update(clientMetadata);
    }
}

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

public ClientDetails validate(ClientDetails prototype, boolean create, boolean checkAdmin)
        throws InvalidClientDetailsException {

    BaseClientDetails client = new BaseClientDetails(prototype);
    if (prototype instanceof BaseClientDetails) {
        Set<String> scopes = ((BaseClientDetails) prototype).getAutoApproveScopes();
        if (scopes != null) {
            client.setAutoApproveScopes(((BaseClientDetails) prototype).getAutoApproveScopes());
        }/*from  ww  w  .j  a  va  2  s  .  c  o  m*/
    }

    client.setAdditionalInformation(prototype.getAdditionalInformation());

    String clientId = client.getClientId();
    if (create && reservedClientIds.contains(clientId)) {
        throw new InvalidClientDetailsException("Not allowed: " + clientId + " is a reserved client_id");
    }

    Set<String> requestedGrantTypes = client.getAuthorizedGrantTypes();

    if (requestedGrantTypes.isEmpty()) {
        throw new InvalidClientDetailsException(
                "An authorized grant type must be provided. Must be one of: " + VALID_GRANTS.toString());
    }
    checkRequestedGrantTypes(requestedGrantTypes);

    if ((requestedGrantTypes.contains("authorization_code") || requestedGrantTypes.contains("password"))
            && !requestedGrantTypes.contains("refresh_token")) {
        logger.debug("requested grant type missing refresh_token: " + clientId);

        requestedGrantTypes.add("refresh_token");
    }

    if (checkAdmin && !(securityContextAccessor.isAdmin()
            || securityContextAccessor.getScopes().contains("clients.admin"))) {

        // Not admin, so be strict with grant types and scopes
        for (String grant : requestedGrantTypes) {
            if (NON_ADMIN_INVALID_GRANTS.contains(grant)) {
                throw new InvalidClientDetailsException(
                        grant + " is not an allowed grant type for non-admin caller.");
            }
        }

        if (requestedGrantTypes.contains("implicit") && requestedGrantTypes.contains("authorization_code")) {
            throw new InvalidClientDetailsException(
                    "Not allowed: implicit grant type is not allowed together with authorization_code");
        }

        String callerId = securityContextAccessor.getClientId();
        ClientDetails caller = null;
        try {
            caller = clientDetailsService.retrieve(callerId);
        } catch (Exception e) {
            // best effort to get the caller, but the caller might not belong to this zone.
        }
        if (callerId != null && caller != null) {

            // New scopes are allowed if they are for the caller or the new
            // client.
            String callerPrefix = callerId + ".";
            String clientPrefix = clientId + ".";

            Set<String> validScope = caller.getScope();
            for (String scope : client.getScope()) {
                if (scope.startsWith(callerPrefix) || scope.startsWith(clientPrefix)) {
                    // Allowed
                    continue;
                }
                if (!validScope.contains(scope)) {
                    throw new InvalidClientDetailsException(scope + " is not an allowed scope for caller="
                            + callerId + ". Must have prefix in [" + callerPrefix + "," + clientPrefix
                            + "] or be one of: " + validScope.toString());
                }
            }

        } else {
            // New scopes are allowed if they are for the caller or the new
            // client.
            String clientPrefix = clientId + ".";

            for (String scope : client.getScope()) {
                if (!scope.startsWith(clientPrefix)) {
                    throw new InvalidClientDetailsException(
                            scope + " is not an allowed scope for null caller and client_id=" + clientId
                                    + ". Must start with '" + clientPrefix + "'");
                }
            }
        }

        Set<String> validAuthorities = new HashSet<String>(NON_ADMIN_VALID_AUTHORITIES);
        if (requestedGrantTypes.contains("client_credentials")) {
            // If client_credentials is used then the client might be a
            // resource server
            validAuthorities.add("uaa.resource");
        }

        for (String authority : AuthorityUtils.authorityListToSet(client.getAuthorities())) {
            if (!validAuthorities.contains(authority)) {
                throw new InvalidClientDetailsException(authority + " is not an allowed authority for caller="
                        + callerId + ". Must be one of: " + validAuthorities.toString());
            }
        }

    }

    if (client.getAuthorities().isEmpty()) {
        client.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("uaa.none"));
    }

    // The UAA does not allow or require resource ids to be registered
    // because they are determined dynamically
    client.setResourceIds(Collections.singleton("none"));

    if (client.getScope().isEmpty()) {
        client.setScope(Collections.singleton("uaa.none"));
    }

    if (requestedGrantTypes.contains("implicit")) {
        if (StringUtils.hasText(client.getClientSecret())) {
            throw new InvalidClientDetailsException("Implicit grant should not have a client_secret");
        }
    }
    if (create) {
        // Only check for missing secret if client is being created.
        if ((requestedGrantTypes.contains("client_credentials")
                || requestedGrantTypes.contains("authorization_code"))
                && !StringUtils.hasText(client.getClientSecret())) {
            throw new InvalidClientDetailsException(
                    "Client secret is required for client_credentials and authorization_code grant types");
        }
    }

    return client;

}

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

private void testRetrieveIdps(boolean retrieveActive) throws Exception {
    String clientId = RandomStringUtils.randomAlphabetic(6);
    BaseClientDetails client = new BaseClientDetails(clientId, null, "idps.write,idps.read", "password", null);
    client.setClientSecret("test-client-secret");
    mockMvcUtils.createClient(getMockMvc(), adminToken, client);

    ScimUser user = mockMvcUtils.createAdminForZone(getMockMvc(), adminToken, "idps.read,idps.write");
    String accessToken = mockMvcUtils.getUserOAuthAccessToken(getMockMvc(), client.getClientId(),
            client.getClientSecret(), user.getUserName(), "secr3T", "idps.read,idps.write");
    String randomOriginKey = new RandomValueStringGenerator().generate();
    IdentityProvider identityProvider = MultitenancyFixture.identityProvider(randomOriginKey,
            IdentityZone.getUaa().getId());
    IdentityProvider createdIDP = createIdentityProvider(null, identityProvider, accessToken,
            status().isCreated());//from  www .  j a v a2 s . co m

    String retrieveActiveParam = retrieveActive ? "?active_only=true" : "";
    MockHttpServletRequestBuilder requestBuilder = get("/identity-providers" + retrieveActiveParam)
            .header("Authorization", "Bearer" + accessToken).contentType(APPLICATION_JSON);

    int numberOfIdps = identityProviderProvisioning.retrieveAll(retrieveActive, IdentityZone.getUaa().getId())
            .size();

    MvcResult result = getMockMvc().perform(requestBuilder).andExpect(status().isOk()).andReturn();
    List<IdentityProvider> identityProviderList = JsonUtils.readValue(result.getResponse().getContentAsString(),
            new TypeReference<List<IdentityProvider>>() {
            });
    assertEquals(numberOfIdps, identityProviderList.size());
    assertTrue(identityProviderList.contains(createdIDP));

    createdIDP.setActive(false);
    createdIDP = JsonUtils.readValue(updateIdentityProvider(null, createdIDP, accessToken, status().isOk())
            .getResponse().getContentAsString(), IdentityProvider.class);

    result = getMockMvc().perform(requestBuilder).andExpect(status().isOk()).andReturn();
    identityProviderList = JsonUtils.readValue(result.getResponse().getContentAsString(),
            new TypeReference<List<IdentityProvider>>() {
            });
    if (!retrieveActive) {
        assertEquals(numberOfIdps, identityProviderList.size());
        assertTrue(identityProviderList.contains(createdIDP));
    } else {
        assertEquals(numberOfIdps - 1, identityProviderList.size());
        assertFalse(identityProviderList.contains(createdIDP));
    }
}

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

@Test
public void testListIdpsInZone() throws Exception {
    BaseClientDetails client = getBaseClientDetails();

    ScimUser user = mockMvcUtils.createAdminForZone(getMockMvc(), adminToken, "idps.read,idps.write");
    String accessToken = mockMvcUtils.getUserOAuthAccessToken(getMockMvc(), client.getClientId(),
            client.getClientSecret(), user.getUserName(), "secr3T", "idps.read,idps.write");

    int numberOfIdps = identityProviderProvisioning.retrieveAll(false, IdentityZone.getUaa().getId()).size();

    String originKey = RandomStringUtils.randomAlphabetic(6);
    IdentityProvider newIdp = MultitenancyFixture.identityProvider(originKey, IdentityZone.getUaa().getId());
    newIdp = createIdentityProvider(null, newIdp, accessToken, status().isCreated());

    MockHttpServletRequestBuilder requestBuilder = get("/identity-providers/")
            .header("Authorization", "Bearer" + accessToken).contentType(APPLICATION_JSON);

    MvcResult result = getMockMvc().perform(requestBuilder).andExpect(status().isOk()).andReturn();
    List<IdentityProvider> identityProviderList = JsonUtils.readValue(result.getResponse().getContentAsString(),
            new TypeReference<List<IdentityProvider>>() {
            });/* w  ww. j a  va  2s  . c o m*/
    assertEquals(numberOfIdps + 1, identityProviderList.size());
    assertTrue(identityProviderList.contains(newIdp));
}

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

@Test
public void testRetrieveIdpInZone() throws Exception {
    BaseClientDetails client = getBaseClientDetails();

    ScimUser user = mockMvcUtils.createAdminForZone(getMockMvc(), adminToken, "idps.read,idps.write");
    String accessToken = mockMvcUtils.getUserOAuthAccessToken(getMockMvc(), client.getClientId(),
            client.getClientSecret(), user.getUserName(), "secr3T", "idps.read,idps.write");

    String originKey = RandomStringUtils.randomAlphabetic(6);
    IdentityProvider newIdp = MultitenancyFixture.identityProvider(originKey, IdentityZone.getUaa().getId());
    newIdp = createIdentityProvider(null, newIdp, accessToken, status().isCreated());

    MockHttpServletRequestBuilder requestBuilder = get("/identity-providers/" + newIdp.getId())
            .header("Authorization", "Bearer" + accessToken).contentType(APPLICATION_JSON);

    MvcResult result = getMockMvc().perform(requestBuilder).andExpect(status().isOk()).andReturn();
    IdentityProvider retrieved = JsonUtils.readValue(result.getResponse().getContentAsString(),
            IdentityProvider.class);
    assertEquals(newIdp, retrieved);/*from ww  w  .  j ava 2  s.c om*/
}

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

@Test
public void testRetrieveIdpInZoneWithInsufficientScopes() throws Exception {
    BaseClientDetails client = getBaseClientDetails();

    ScimUser user = mockMvcUtils.createAdminForZone(getMockMvc(), adminToken, "idps.write");
    String accessToken = mockMvcUtils.getUserOAuthAccessToken(getMockMvc(), client.getClientId(),
            client.getClientSecret(), user.getUserName(), "secr3T", "idps.write");

    String originKey = RandomStringUtils.randomAlphabetic(6);
    IdentityProvider newIdp = MultitenancyFixture.identityProvider(originKey, IdentityZone.getUaa().getId());
    newIdp = createIdentityProvider(null, newIdp, accessToken, status().isCreated());

    MockHttpServletRequestBuilder requestBuilder = get("/identity-providers/" + newIdp.getId())
            .header("Authorization", "Bearer" + lowPriviledgeToken).contentType(APPLICATION_JSON);

    getMockMvc().perform(requestBuilder).andExpect(status().isForbidden());
}

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

public String setUpAccessToken() throws Exception {
    String clientId = RandomStringUtils.randomAlphabetic(6);
    BaseClientDetails client = new BaseClientDetails(clientId, null, "idps.read,idps.write", "password", null);
    client.setClientSecret("test-client-secret");
    mockMvcUtils.createClient(getMockMvc(), adminToken, client);

    ScimUser user = mockMvcUtils.createAdminForZone(getMockMvc(), adminToken, "idps.write,idps.read");
    return mockMvcUtils.getUserOAuthAccessToken(getMockMvc(), client.getClientId(), client.getClientSecret(),
            user.getUserName(), "secr3T", "idps.read idps.write");
}

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

@Test
public void revokeOwnJWToken() throws Exception {
    IdentityZone defaultZone = identityZoneProvisioning.retrieve(IdentityZone.getUaa().getId());
    defaultZone.getConfig().getTokenPolicy().setJwtRevocable(true);
    identityZoneProvisioning.update(defaultZone);

    try {//from  w w  w.j a v a  2  s  . c o  m
        BaseClientDetails client = new BaseClientDetails(generator.generate(), "", "openid",
                "client_credentials,password", "clients.write");
        client.setClientSecret("secret");
        createClient(getMockMvc(), adminToken, client);

        //this is the token we will revoke
        String clientToken = getClientCredentialsOAuthAccessToken(getMockMvc(), client.getClientId(),
                client.getClientSecret(), null, null);

        Jwt jwt = JwtHelper.decode(clientToken);
        Map<String, Object> claims = JsonUtils.readValue(jwt.getClaims(),
                new TypeReference<Map<String, Object>>() {
                });
        String jti = (String) claims.get("jti");

        getMockMvc()
                .perform(delete("/oauth/token/revoke/" + jti).header("Authorization", "Bearer " + clientToken))
                .andExpect(status().isOk());

        tokenProvisioning.retrieve(jti);
    } catch (EmptyResultDataAccessException e) {
    } finally {
        defaultZone.getConfig().getTokenPolicy().setJwtRevocable(false);
        identityZoneProvisioning.update(defaultZone);
    }
}