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

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

Introduction

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

Prototype

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

Source Link

Usage

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

@Test
public void testUpdateClientSecret() {

    BaseClientDetails clientDetails = new BaseClientDetails();
    clientDetails.setClientId("newClientIdWithNoDetails");

    fixture.setPasswordEncoder(new PasswordEncoder() {

        public boolean matches(CharSequence rawPassword, String encodedPassword) {
            return true;
        }/*from w ww.  jav  a 2 s  .  c o m*/

        public String encode(CharSequence rawPassword) {
            return "BAR";
        }
    });
    fixture.addClientDetails(clientDetails);
    fixture.updateClientSecret(clientDetails.getClientId(), "foo");

    DBObject map = collection.findOne(new BasicDBObject("clientId", "newClientIdWithNoDetails"));

    assertEquals("newClientIdWithNoDetails", map.get("clientId"));
    assertTrue(map.containsField("clientSecret"));
    assertEquals("BAR", map.get("clientSecret"));
}

From source file:com.ge.predix.test.utils.UaaTestUtil.java

private BaseClientDetails createOrUpdateClient(final BaseClientDetails client) {

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
    headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
    if (StringUtils.isNotEmpty(this.zone)) {
        headers.add("X-Identity-Zone-Id", "uaa");
    }//from  w  w  w. ja v a  2  s  .  c o  m

    HttpEntity<String> postEntity = new HttpEntity<String>(JSON_UTILS.serialize(client), headers);

    ResponseEntity<String> clientCreate = null;
    try {
        clientCreate = this.adminRestTemplate.exchange(this.uaaUrl + "/oauth/clients", HttpMethod.POST,
                postEntity, String.class);
        if (clientCreate.getStatusCode() == HttpStatus.CREATED) {
            return JSON_UTILS.deserialize(clientCreate.getBody(), BaseClientDetails.class);
        } else {
            throw new RuntimeException(
                    "Unexpected return code for client create: " + clientCreate.getStatusCode());
        }
    } catch (InvalidClientException ex) {
        if (ex.getMessage().equals("Client already exists: " + client.getClientId())) {
            HttpEntity<String> putEntity = new HttpEntity<String>(JSON_UTILS.serialize(client), headers);
            ResponseEntity<String> clientUpdate = this.adminRestTemplate.exchange(
                    this.uaaUrl + "/oauth/clients/" + client.getClientId(), HttpMethod.PUT, putEntity,
                    String.class);
            if (clientUpdate.getStatusCode() == HttpStatus.OK) {
                return JSON_UTILS.deserialize(clientUpdate.getBody(), BaseClientDetails.class);
            } else {
                throw new RuntimeException(
                        "Unexpected return code for client update: " + clientUpdate.getStatusCode());
            }
        }
    }
    throw new RuntimeException("Unexpected return code for client creation: " + clientCreate.getStatusCode());
}

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>>() {
            });//  ww w. j  a va2s .  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.audit.event.SystemDeletableTest.java

@Test
public void client_event_received() throws Exception {
    BaseClientDetails client = new BaseClientDetails("clientId", "", "", "client_credentials", "uaa.none");
    EntityDeletedEvent<ClientDetails> event = new EntityDeletedEvent(client, authentication);
    for (IdentityZone zone : Arrays.asList(this.zone, IdentityZone.getUaa())) {
        resetDeletable();/*  w  w  w .j a va  2s .  com*/
        IdentityZoneHolder.set(zone);
        deletable.onApplicationEvent(event);
        verify(deletable, never()).deleteByIdentityZone(any());
        verify(deletable, never()).deleteByOrigin(any(), any());
        verify(deletable, times(1)).deleteByClient(client.getClientId(), zone.getId());
        verify(deletable, never()).deleteByUser(any(), any());
    }
}

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

@RequestMapping(value = "/oauth/clients/{client}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)/*from ww  w  .j a v a  2s.c  o  m*/
@ResponseBody
public ClientDetails updateClientDetails(@RequestBody BaseClientDetails client,
        @PathVariable("client") String clientId) throws Exception {
    Assert.state(clientId.equals(client.getClientId()),
            String.format("The client id (%s) does not match the URL (%s)", client.getClientId(), clientId));
    ClientDetails details = client;
    try {
        ClientDetails existing = getClientDetails(clientId);
        if (existing == null) {
            //TODO - should we proceed? Previous code did by throwing a NPE and logging a warning
            logger.warn("Couldn't fetch client config, null, for client_id: " + clientId);
        } else {
            details = syncWithExisting(existing, client);
        }
    } catch (Exception e) {
        logger.warn("Couldn't fetch client config for client_id: " + clientId, e);
    }
    details = clientDetailsValidator.validate(details, Mode.MODIFY);
    clientRegistrationService.updateClientDetails(details);
    clientUpdates.incrementAndGet();
    return removeSecret(clientDetailsService.retrieve(clientId));
}

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 w  ww  . ja  v a2s  .  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.integration.util.IntegrationTestUtils.java

public static BaseClientDetails createOrUpdateClient(String adminToken, String url, String switchToZoneId,
        BaseClientDetails client) throws Exception {

    RestTemplate template = new RestTemplate();
    template.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override//from   w w  w .jav a2  s. c om
        protected boolean hasError(HttpStatus statusCode) {
            return statusCode.is5xxServerError();
        }
    });
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Accept", APPLICATION_JSON_VALUE);
    headers.add("Authorization", "bearer " + adminToken);
    headers.add("Content-Type", APPLICATION_JSON_VALUE);
    if (StringUtils.hasText(switchToZoneId)) {
        headers.add(IdentityZoneSwitchingFilter.HEADER, switchToZoneId);
    }
    HttpEntity getHeaders = new HttpEntity(JsonUtils.writeValueAsBytes(client), headers);
    ResponseEntity<String> clientCreate = template.exchange(url + "/oauth/clients", HttpMethod.POST, getHeaders,
            String.class);
    if (clientCreate.getStatusCode() == HttpStatus.CREATED) {
        return JsonUtils.readValue(clientCreate.getBody(), BaseClientDetails.class);
    } else if (clientCreate.getStatusCode() == HttpStatus.CONFLICT) {
        HttpEntity putHeaders = new HttpEntity(JsonUtils.writeValueAsBytes(client), headers);
        ResponseEntity<String> clientUpdate = template.exchange(url + "/oauth/clients/" + client.getClientId(),
                HttpMethod.PUT, putHeaders, String.class);
        if (clientUpdate.getStatusCode() == HttpStatus.OK) {
            return JsonUtils.readValue(clientCreate.getBody(), BaseClientDetails.class);
        } else {
            throw new RuntimeException("Invalid update return code:" + clientUpdate.getStatusCode());
        }
    }
    throw new RuntimeException("Invalid crete return code:" + clientCreate.getStatusCode());
}

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 ww  w .  j  av  a  2  s.c om

    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>>() {
            });//from w w  w  .j  a  v  a 2 s .  c o  m
    assertEquals(numberOfIdps + 1, identityProviderList.size());
    assertTrue(identityProviderList.contains(newIdp));
}