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

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

Introduction

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

Prototype

@org.codehaus.jackson.annotate.JsonIgnore
    @com.fasterxml.jackson.annotation.JsonIgnore
    public Set<String> getAutoApproveScopes() 

Source Link

Usage

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

@RequestMapping(value = "/approvals", method = RequestMethod.GET)
@ResponseBody//from   w  w  w .j a v  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.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  ww w  . ja  v a  2 s . co m*/
            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.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   ww w.  j a  v  a  2  s. com
        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.UaaTokenServices.java

private Set<String> getAutoApprovedScopes(Object grantType, Collection<String> tokenScopes,
        ClientDetails client) {/* w  ww  .j  a  v a2  s. co m*/
    // ALL requested scopes are considered auto-approved for password grant
    if (grantType != null && "password".equals(grantType.toString())) {
        return new HashSet<>(tokenScopes);
    }
    BaseClientDetails clientDetails = (BaseClientDetails) client;

    return UaaTokenUtils.retainAutoApprovedScopes(tokenScopes, clientDetails.getAutoApproveScopes());
}

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

@Override
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {

    String flag = authorizationRequest.getApprovalParameters().get(approvalParameter);
    boolean userApproval = flag != null && flag.toLowerCase().equals("true");

    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder("Looking up user approved authorizations for ");
        builder.append("client_id=").append(authorizationRequest.getClientId());
        builder.append(" and username=").append(userAuthentication.getName());
        logger.debug(builder.toString());
    }/*from  w  ww  .  j  a v a 2s  .c o m*/

    Collection<String> requestedScopes = authorizationRequest.getScope();

    // Factor in auto approved scopes
    Set<String> autoApprovedScopes = new HashSet<>();
    BaseClientDetails client = (BaseClientDetails) clientDetailsService
            .retrieve(authorizationRequest.getClientId());
    if (client != null && requestedScopes != null) {
        autoApprovedScopes.addAll(client.getAutoApproveScopes());
        autoApprovedScopes = UaaTokenUtils.retainAutoApprovedScopes(requestedScopes, autoApprovedScopes);
    }
    //translate scope to user scopes - including wild cards

    if (userApproval) {
        // Store the scopes that have been approved / denied
        Date expiry = computeExpiry();

        // Get the approved scopes, calculate the denied scope
        Map<String, String> approvalParameters = authorizationRequest.getApprovalParameters();
        Set<String> approvedScopes = new HashSet<>();
        approvedScopes.addAll(autoApprovedScopes);
        boolean foundUserApprovalParameter = false;
        for (String approvalParameter : approvalParameters.keySet()) {
            if (approvalParameter.startsWith(SCOPE_PREFIX)) {
                approvedScopes.add(approvalParameters.get(approvalParameter).substring(SCOPE_PREFIX.length()));
                foundUserApprovalParameter = true;
            }
        }

        if (foundUserApprovalParameter) {
            authorizationRequest.setScope(approvedScopes);

            for (String requestedScope : requestedScopes) {
                if (approvedScopes.contains(requestedScope)) {
                    Approval approval = new Approval().setUserId(getUserId(userAuthentication))
                            .setClientId(authorizationRequest.getClientId()).setScope(requestedScope)
                            .setExpiresAt(expiry).setStatus(APPROVED);
                    approvalStore.addApproval(approval);
                } else {
                    Approval approval = new Approval().setUserId(getUserId(userAuthentication))
                            .setClientId(authorizationRequest.getClientId()).setScope(requestedScope)
                            .setExpiresAt(expiry).setStatus(DENIED);
                    approvalStore.addApproval(approval);
                }
            }

        } else { // Deny all except auto approved scopes
            authorizationRequest.setScope(autoApprovedScopes);

            for (String requestedScope : requestedScopes) {
                if (!autoApprovedScopes.contains(requestedScope)) {
                    Approval approval = new Approval().setUserId(getUserId(userAuthentication))
                            .setClientId(authorizationRequest.getClientId()).setScope(requestedScope)
                            .setExpiresAt(expiry).setStatus(DENIED);
                    approvalStore.addApproval(approval);
                }
            }
        }

        if (userAuthentication.isAuthenticated()) {
            return true;
        }

    } else {
        // Find the stored approvals for that user and client
        List<Approval> userApprovals = approvalStore.getApprovals(getUserId(userAuthentication),
                authorizationRequest.getClientId());

        // Look at the scopes and see if they have expired
        Set<String> validUserApprovedScopes = new HashSet<>();
        Set<String> approvedScopes = new HashSet<>();
        approvedScopes.addAll(autoApprovedScopes);
        validUserApprovedScopes.addAll(autoApprovedScopes);
        Date today = new Date();
        for (Approval approval : userApprovals) {
            if (approval.getExpiresAt().after(today)) {
                validUserApprovedScopes.add(approval.getScope());
                if (approval.getStatus() == APPROVED) {
                    approvedScopes.add(approval.getScope());
                }
            }
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Valid user approved/denied scopes are " + validUserApprovedScopes);
        }

        // If the requested scopes have already been acted upon by the user,
        // this request is approved
        if (validUserApprovedScopes.containsAll(requestedScopes) && userAuthentication.isAuthenticated()) {
            approvedScopes = UaaTokenUtils.retainAutoApprovedScopes(requestedScopes, approvedScopes);
            // Set only the scopes that have been approved by the user
            authorizationRequest.setScope(approvedScopes);
            return true;
        }
    }

    return false;
}

From source file:org.cloudfoundry.identity.uaa.user.UaaUserApprovalHandler.java

private boolean isAutoApprove(ClientDetails client, Collection<String> scopes) {
    BaseClientDetails baseClient = (BaseClientDetails) client;
    if (baseClient.getAutoApproveScopes() != null) {
        if (baseClient.getAutoApproveScopes().contains("true")) {
            return true;
        }// w  w  w. jav  a2  s.c o  m
        if (baseClient.getAutoApproveScopes().containsAll(scopes)) {
            return true;
        }
    }
    return false;
}