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:org.cloudfoundry.identity.uaa.mock.util.MockMvcUtils.java

public static BaseClientDetails updateClient(MockMvc mockMvc, String accessToken,
        BaseClientDetails clientDetails, IdentityZone zone) throws Exception {
    MockHttpServletRequestBuilder updateClientPut = put("/oauth/clients/" + clientDetails.getClientId())
            .header("Authorization", "Bearer " + accessToken).accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(clientDetails));
    if (!zone.equals(IdentityZone.getUaa())) {
        updateClientPut = updateClientPut.header(IdentityZoneSwitchingFilter.HEADER, zone.getId());
    }//from ww  w. j a  va2s.co m

    return JsonUtils.readValue(mockMvc.perform(updateClientPut).andExpect(status().isOk()).andReturn()
            .getResponse().getContentAsString(), BaseClientDetails.class);
}

From source file:org.cloudfoundry.identity.uaa.mock.zones.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" + adminToken).contentType(APPLICATION_JSON);

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

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

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

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

From source file:org.cloudfoundry.identity.uaa.mock.zones.IdentityZoneSwitchingFilterMockMvcTest.java

@Test
public void testNoSwitching() throws Exception {

    final String clientId = UUID.randomUUID().toString();
    BaseClientDetails client = new BaseClientDetails(clientId, null, null, "client_credentials", null);
    client.setClientSecret("secret");

    getMockMvc().perform(//  w ww  .  ja  va2  s.c  o m
            post("/oauth/clients").header("Authorization", "Bearer " + adminToken).accept(APPLICATION_JSON)
                    .contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(client)))
            .andExpect(status().isCreated());

    getMockMvc()
            .perform(get("/oauth/token?grant_type=client_credentials").header("Authorization",
                    "Basic " + new String(Base64
                            .encodeBase64((client.getClientId() + ":" + client.getClientSecret()).getBytes()))))
            .andExpect(status().isOk());
}

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

@RequestMapping(value = "/oauth/clients/{client}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)/*w w  w . j  a v  a2s  . co  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 = validateClient(details, false);
    clientRegistrationService.updateClientDetails(details);
    clientUpdates.incrementAndGet();
    return removeSecret(client);
}

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

private ClientDetails validateClient(ClientDetails prototype, boolean create) {

    BaseClientDetails client = new BaseClientDetails(prototype);

    client.setAdditionalInformation(prototype.getAdditionalInformation());

    String clientId = client.getClientId();
    if (create && reservedClientIds.contains(clientId)) {
        throw new InvalidClientDetailsException("Not allowed: " + clientId + " is a reserved client_id");
    }//from www .  ja v a  2  s.  c  o m

    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());
    }
    for (String grant : requestedGrantTypes) {
        if (!VALID_GRANTS.contains(grant)) {
            throw new InvalidClientDetailsException(
                    grant + " is not an allowed grant type. Must be one of: " + VALID_GRANTS.toString());
        }
    }

    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 (!securityContextAccessor.isAdmin()) {

        // 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();
        if (callerId != null) {

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

            ClientDetails caller = clientDetailsService.retrieve(callerId);
            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 { // No client caller. Shouldn't happen in practice, but let's
                 // be defensive

            // 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.oauth.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());
        }//w  w  w . ja v  a  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());
    }
    for (String grant : requestedGrantTypes) {
        if (!VALID_GRANTS.contains(grant)) {
            throw new InvalidClientDetailsException(
                    grant + " is not an allowed grant type. Must be one of: " + VALID_GRANTS.toString());
        }
    }

    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() || UaaStringUtils
            .getStringsFromAuthorities(securityContextAccessor.getAuthorities()).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.test.UaaTestAccounts.java

public ClientDetails getClientDetails(String prefix, BaseClientDetails defaults) {
    String clientId = environment.getProperty(prefix + ".id", defaults.getClientId());
    String clientSecret = environment.getProperty(prefix + ".secret", defaults.getClientSecret());
    String resourceIds = environment.getProperty(prefix + ".resource-ids",
            StringUtils.collectionToCommaDelimitedString(defaults.getResourceIds()));
    String scopes = environment.getProperty(prefix + ".scope",
            StringUtils.collectionToCommaDelimitedString(defaults.getScope()));
    String grantTypes = environment.getProperty(prefix + ".authorized-grant-types",
            StringUtils.collectionToCommaDelimitedString(defaults.getAuthorizedGrantTypes()));
    String authorities = environment.getProperty(prefix + ".authorities",
            StringUtils.collectionToCommaDelimitedString(defaults.getAuthorities()));
    String redirectUris = environment.getProperty(prefix + ".redirect-uri",
            StringUtils.collectionToCommaDelimitedString(defaults.getRegisteredRedirectUri()));
    BaseClientDetails result = new BaseClientDetails(clientId, resourceIds, scopes, grantTypes, authorities,
            redirectUris);/*from   w w w .j  av a 2s .  c om*/
    result.setClientSecret(clientSecret);
    return result;
}