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

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

Introduction

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

Prototype

public Set<String> getScope() 

Source Link

Usage

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

@Test
public void testUpdate() throws Exception {
    ignoreIfUaaNotRunning();/*from  ww w  . j  ava2s . c om*/

    BaseClientDetails toUpdate = createClient();

    try {
        BaseClientDetails client = operations.findById(toUpdate.getClientId());

        toUpdate.setScope(Arrays.asList("foo"));
        BaseClientDetails updated = operations.update(toUpdate);
        assertNotEquals(client.getScope(), updated.getScope());
        assertEquals("foo", updated.getScope().iterator().next());
    } finally {
        operations.delete(toUpdate.getClientId());
    }
}

From source file:org.cloudfoundry.identity.uaa.approval.ApprovalsAdminEndpoints.java

@RequestMapping(value = "/approvals", method = RequestMethod.GET)
@ResponseBody/*w w  w. j  av a  2  s.  c o m*/
@Override
public List<Approval> getApprovals(@RequestParam(required = false, defaultValue = "user_id pr") String filter,
        @RequestParam(required = false, defaultValue = "1") int startIndex,
        @RequestParam(required = false, defaultValue = "100") int count) {
    String userId = getCurrentUserId();
    logger.debug("Fetching all approvals for user: " + userId);
    List<Approval> input = approvalStore
            .getApprovals(String.format("%s and " + USER_FILTER_TEMPLATE, filter, userId));
    List<Approval> approvals = UaaPagingUtils.subList(input, startIndex, count);

    // Find the clients for these approvals
    Set<String> clientIds = new HashSet<String>();
    for (Approval approval : approvals) {
        clientIds.add(approval.getClientId());
    }

    // Find the auto approved scopes for these clients
    Map<String, Set<String>> clientAutoApprovedScopes = new HashMap<String, Set<String>>();
    for (String clientId : clientIds) {
        BaseClientDetails client = (BaseClientDetails) clientDetailsService.loadClientByClientId(clientId);

        Set<String> autoApproved = client.getAutoApproveScopes();
        Set<String> autoApprovedScopes = new HashSet<String>();
        if (autoApproved != null) {
            if (autoApproved.contains("true")) {
                autoApprovedScopes.addAll(client.getScope());
            } else {
                autoApprovedScopes.addAll(autoApproved);
            }
        }

        clientAutoApprovedScopes.put(clientId, autoApprovedScopes);
    }

    List<Approval> filteredApprovals = new ArrayList<Approval>();
    // Remove auto approved scopes
    for (Approval approval : approvals) {
        if (!(clientAutoApprovedScopes.containsKey(approval.getClientId())
                && clientAutoApprovedScopes.get(approval.getClientId()).contains(approval.getScope()))) {
            filteredApprovals.add(approval);
        }
    }

    return filteredApprovals;
}

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;// ww w .  j a  v a 2s . co 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.ClientAdminEndpoints.java

private ClientDetails syncWithExisting(ClientDetails existing, ClientDetails input) {
    BaseClientDetails details = new BaseClientDetails(input);
    if (input instanceof BaseClientDetails) {
        BaseClientDetails baseInput = (BaseClientDetails) input;
        if (baseInput.getAutoApproveScopes() != null) {
            details.setAutoApproveScopes(baseInput.getAutoApproveScopes());
        } else {/*from w w w  . j a v a2  s .c om*/
            details.setAutoApproveScopes(new HashSet<String>());
            if (existing instanceof BaseClientDetails) {
                BaseClientDetails existingDetails = (BaseClientDetails) existing;
                if (existingDetails.getAutoApproveScopes() != null) {
                    for (String scope : existingDetails.getAutoApproveScopes()) {
                        details.getAutoApproveScopes().add(scope);
                    }
                }
            }
        }

    }

    if (details.getAccessTokenValiditySeconds() == null) {
        details.setAccessTokenValiditySeconds(existing.getAccessTokenValiditySeconds());
    }
    if (details.getRefreshTokenValiditySeconds() == null) {
        details.setRefreshTokenValiditySeconds(existing.getRefreshTokenValiditySeconds());
    }
    if (details.getAuthorities() == null || details.getAuthorities().isEmpty()) {
        details.setAuthorities(existing.getAuthorities());
    }
    if (details.getAuthorizedGrantTypes() == null || details.getAuthorizedGrantTypes().isEmpty()) {
        details.setAuthorizedGrantTypes(existing.getAuthorizedGrantTypes());
    }
    if (details.getRegisteredRedirectUri() == null || details.getRegisteredRedirectUri().isEmpty()) {
        details.setRegisteredRedirectUri(existing.getRegisteredRedirectUri());
    }
    if (details.getResourceIds() == null || details.getResourceIds().isEmpty()) {
        details.setResourceIds(existing.getResourceIds());
    }
    if (details.getScope() == null || details.getScope().isEmpty()) {
        details.setScope(existing.getScope());
    }

    Map<String, Object> additionalInformation = new HashMap<String, Object>(
            existing.getAdditionalInformation());
    additionalInformation.putAll(input.getAdditionalInformation());
    for (String key : Collections.unmodifiableSet(additionalInformation.keySet())) {
        if (additionalInformation.get(key) == null) {
            additionalInformation.remove(key);
        }
    }
    details.setAdditionalInformation(additionalInformation);

    return details;
}

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  www  . ja v a  2s. c om
    }

    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.oauth.AccessController.java

@RequestMapping("/oauth/confirm_access")
public String confirm(Map<String, Object> model, final HttpServletRequest request, Principal principal,
        SessionStatus sessionStatus) throws Exception {

    if (!(principal instanceof Authentication)) {
        sessionStatus.setComplete();/*from w w w . ja  va  2  s  . co  m*/
        throw new InsufficientAuthenticationException(
                "User must be authenticated with before authorizing access.");
    }

    AuthorizationRequest clientAuthRequest = (AuthorizationRequest) model.remove("authorizationRequest");
    if (clientAuthRequest == null) {
        model.put("error",
                "No authorization request is present, so we cannot confirm access (we don't know what you are asking for).");
        // response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } else {
        String clientId = clientAuthRequest.getClientId();
        BaseClientDetails client = (BaseClientDetails) clientDetailsService.loadClientByClientId(clientId);
        // TODO: Need to fix the copy constructor to copy additionalInfo
        BaseClientDetails modifiableClient = new BaseClientDetails(client);
        modifiableClient.setClientSecret(null);
        model.put("auth_request", clientAuthRequest);
        model.put("redirect_uri", getRedirectUri(modifiableClient, clientAuthRequest));

        Map<String, Object> additionalInfo = client.getAdditionalInformation();
        String clientDisplayName = (String) additionalInfo.get(ClientConstants.CLIENT_NAME);
        model.put("client_display_name", (clientDisplayName != null) ? clientDisplayName : clientId);

        // Find the auto approved scopes for this clients
        Set<String> autoApproved = client.getAutoApproveScopes();
        Set<String> autoApprovedScopes = new HashSet<>();
        if (autoApproved != null) {
            if (autoApproved.contains("true")) {
                autoApprovedScopes.addAll(client.getScope());
            } else {
                autoApprovedScopes.addAll(autoApproved);
            }
        }

        List<Approval> filteredApprovals = new ArrayList<Approval>();
        // Remove auto approved scopes
        List<Approval> approvals = approvalStore.getApprovals(Origin.getUserId((Authentication) principal),
                clientId);
        for (Approval approval : approvals) {
            if (!(autoApprovedScopes.contains(approval.getScope()))) {
                filteredApprovals.add(approval);
            }
        }

        ArrayList<String> approvedScopes = new ArrayList<String>();
        ArrayList<String> deniedScopes = new ArrayList<String>();

        for (Approval approval : filteredApprovals) {
            switch (approval.getStatus()) {
            case APPROVED:
                approvedScopes.add(approval.getScope());
                break;
            case DENIED:
                deniedScopes.add(approval.getScope());
                break;
            default:
                logger.error("Encountered an unknown scope. This is not supposed to happen");
                break;
            }
        }

        ArrayList<String> undecidedScopes = new ArrayList<String>();

        // Filter the scopes approved/denied from the ones requested
        for (String scope : clientAuthRequest.getScope()) {
            if (!approvedScopes.contains(scope) && !deniedScopes.contains(scope)
                    && !autoApprovedScopes.contains(scope)) {
                undecidedScopes.add(scope);
            }
        }

        List<Map<String, String>> approvedScopeDetails = getScopes(approvedScopes);
        model.put("approved_scopes", approvedScopeDetails);
        List<Map<String, String>> undecidedScopeDetails = getScopes(undecidedScopes);
        model.put("undecided_scopes", undecidedScopeDetails);
        List<Map<String, String>> deniedScopeDetails = getScopes(deniedScopes);
        model.put("denied_scopes", deniedScopeDetails);

        List<Map<String, String>> allScopes = new ArrayList<>();
        allScopes.addAll(approvedScopeDetails);
        allScopes.addAll(undecidedScopeDetails);
        allScopes.addAll(deniedScopeDetails);

        model.put("scopes", allScopes);

        model.put("message",
                "To confirm or deny access POST to the following locations with the parameters requested.");
        Map<String, Object> options = new HashMap<String, Object>() {
            {
                put("confirm", new HashMap<String, String>() {
                    {
                        put("location", getLocation(request, "oauth/authorize"));
                        put("path", getPath(request, "oauth/authorize"));
                        put("key", OAuth2Utils.USER_OAUTH_APPROVAL);
                        put("value", "true");
                    }

                });
                put("deny", new HashMap<String, String>() {
                    {
                        put("location", getLocation(request, "oauth/authorize"));
                        put("path", getPath(request, "oauth/authorize"));
                        put("key", OAuth2Utils.USER_OAUTH_APPROVAL);
                        put("value", "false");
                    }

                });
            }
        };
        model.put("options", options);
    }

    return "access_confirmation";

}

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

private void addNewClients() throws Exception {
    for (String clientId : clients.keySet()) {
        Map<String, Object> map = clients.get(clientId);
        BaseClientDetails client = new BaseClientDetails(clientId, (String) map.get("resource-ids"),
                (String) map.get("scope"), (String) map.get("authorized-grant-types"),
                (String) map.get("authorities"), (String) map.get("redirect-uri"));
        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 a 2s  . c om
        }
        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")) {
            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())) {
                    clientRegistrationService.updateClientSecret(clientId, client.getClientSecret());
                }
            } else {
                // ignore it
                logger.debug(e.getMessage());
            }
        }
    }
}

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");
    }/*w ww .  j  av a2  s.  co 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.ClientAdminEndpoints.java

private ClientDetails syncWithExisting(ClientDetails existing, ClientDetails input) {
    BaseClientDetails details = new BaseClientDetails(input);
    if (details.getAccessTokenValiditySeconds() == null) {
        details.setAccessTokenValiditySeconds(existing.getAccessTokenValiditySeconds());
    }// ww w . j  av a  2s .  co  m
    if (details.getRefreshTokenValiditySeconds() == null) {
        details.setRefreshTokenValiditySeconds(existing.getRefreshTokenValiditySeconds());
    }
    if (details.getAuthorities() == null || details.getAuthorities().isEmpty()) {
        details.setAuthorities(existing.getAuthorities());
    }
    if (details.getAuthorizedGrantTypes() == null || details.getAuthorizedGrantTypes().isEmpty()) {
        details.setAuthorizedGrantTypes(existing.getAuthorizedGrantTypes());
    }
    if (details.getRegisteredRedirectUri() == null || details.getRegisteredRedirectUri().isEmpty()) {
        details.setRegisteredRedirectUri(existing.getRegisteredRedirectUri());
    }
    if (details.getResourceIds() == null || details.getResourceIds().isEmpty()) {
        details.setResourceIds(existing.getResourceIds());
    }
    if (details.getScope() == null || details.getScope().isEmpty()) {
        details.setScope(existing.getScope());
    }

    Map<String, Object> additionalInformation = new HashMap<String, Object>(
            existing.getAdditionalInformation());
    additionalInformation.putAll(input.getAdditionalInformation());
    for (String key : Collections.unmodifiableSet(additionalInformation.keySet())) {
        if (additionalInformation.get(key) == null) {
            additionalInformation.remove(key);
        }
    }
    details.setAdditionalInformation(additionalInformation);

    return details;
}

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());
        }/*from  w  ww .  j a va2 s.co 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;

}