Example usage for org.springframework.security.oauth2.provider AuthorizationRequest isApproved

List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest isApproved

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.provider AuthorizationRequest isApproved.

Prototype

public boolean isApproved() 

Source Link

Usage

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

private boolean isAuthorizationRequestModified(AuthorizationRequest authorizationRequest,
        Map<String, Object> originalAuthorizationRequest) {
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getClientId(),
            originalAuthorizationRequest.get(OAuth2Utils.CLIENT_ID))) {
        return true;
    }/* w w w  . j a  v a2  s .  co m*/
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getState(),
            originalAuthorizationRequest.get(OAuth2Utils.STATE))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getRedirectUri(),
            originalAuthorizationRequest.get(OAuth2Utils.REDIRECT_URI))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getResponseTypes(),
            originalAuthorizationRequest.get(OAuth2Utils.RESPONSE_TYPE))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.isApproved(),
            originalAuthorizationRequest.get("approved"))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getResourceIds(),
            originalAuthorizationRequest.get("resourceIds"))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getAuthorities(),
            originalAuthorizationRequest.get("authorities"))) {
        return true;
    }

    return !ObjectUtils.nullSafeEquals(authorizationRequest.getScope(),
            originalAuthorizationRequest.get(OAuth2Utils.SCOPE));
}

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

Map<String, Object> unmodifiableMap(AuthorizationRequest authorizationRequest) {
    Map<String, Object> authorizationRequestMap = new HashMap<>();

    authorizationRequestMap.put(OAuth2Utils.CLIENT_ID, authorizationRequest.getClientId());
    authorizationRequestMap.put(OAuth2Utils.STATE, authorizationRequest.getState());
    authorizationRequestMap.put(OAuth2Utils.REDIRECT_URI, authorizationRequest.getRedirectUri());

    if (authorizationRequest.getResponseTypes() != null) {
        authorizationRequestMap.put(OAuth2Utils.RESPONSE_TYPE,
                Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getResponseTypes())));
    }//  www  .ja  v  a 2  s.  com
    if (authorizationRequest.getScope() != null) {
        authorizationRequestMap.put(OAuth2Utils.SCOPE,
                Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getScope())));
    }

    authorizationRequestMap.put("approved", authorizationRequest.isApproved());

    if (authorizationRequest.getResourceIds() != null) {
        authorizationRequestMap.put("resourceIds",
                Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getResourceIds())));
    }
    if (authorizationRequest.getAuthorities() != null) {
        authorizationRequestMap.put("authorities", Collections
                .unmodifiableSet(new HashSet<GrantedAuthority>(authorizationRequest.getAuthorities())));
    }

    return authorizationRequestMap;
}

From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java

@Override
protected void configure() {
    setControllerPath("oauth");

    get("authorize", (req, resp) -> {
        Map<String, String> parameters = MapUtils.createOneDimMap(req.getQueryParams());
        AuthorizationRequest authorizationRequest = requestFactory.createAuthorizationRequest(parameters);

        Set<String> responseTypes = authorizationRequest.getResponseTypes();
        if (!responseTypes.contains("token") && !responseTypes.contains("code")) {
            throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
        }/*  ww w.j  a  va2 s  .c  o m*/

        if (isNull(authorizationRequest.getClientId())) {
            throw new InvalidClientException("A client id must be provided");
        }

        ClientDetails client = clientDetailsService.loadClientByClientId(authorizationRequest.getClientId());

        String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
        String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
        if (isEmpty(resolvedRedirect)) {
            throw new RedirectMismatchException(
                    "A redirectUri must be either supplied or preconfigured in the ClientDetails");
        }
        authorizationRequest.setRedirectUri(resolvedRedirect);

        requestValidator.validateScope(authorizationRequest, client);

        authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, null);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, null);
        authorizationRequest.setApproved(approved);

        if (authorizationRequest.isApproved()) {
            if (responseTypes.contains("token")) {
                resp.status(HttpStatus.FOUND);
                resp.header(HeaderName.LOCATION, getImplicitGrantResponse(authorizationRequest));
            }
            if (responseTypes.contains("code")) {
                resp.status(HttpStatus.FOUND);
                resp.header(HeaderName.LOCATION, getAuthorizationCodeResponse(authorizationRequest));
            }
        }
    });
}

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

@RequestMapping(value = "/oauth/authorize", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
public View approveOrDeny(@RequestParam Map<String, String> approvalParameters, Map<String, ?> model,
        SessionStatus sessionStatus, Principal principal) {

    if (!(principal instanceof Authentication)) {
        sessionStatus.setComplete();// ww w.jav  a2s.  co m
        throw new InsufficientAuthenticationException(
                "User must be authenticated with Spring Security before authorizing an access token.");
    }

    AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get(AUTHORIZATION_REQUEST);

    if (authorizationRequest == null) {
        sessionStatus.setComplete();
        throw new InvalidRequestException("Cannot approve uninitialized authorization request.");
    }

    // Check to ensure the Authorization Request was not modified during the user approval step
    @SuppressWarnings("unchecked")
    Map<String, Object> originalAuthorizationRequest = (Map<String, Object>) model
            .get(ORIGINAL_AUTHORIZATION_REQUEST);
    if (isAuthorizationRequestModified(authorizationRequest, originalAuthorizationRequest)) {
        logger.warn("The requested scopes are invalid");
        throw new InvalidRequestException("Changes were detected from the original authorization request.");
    }

    for (String approvalParameter : approvalParameters.keySet()) {
        if (approvalParameter.startsWith(SCOPE_PREFIX)) {
            String scope = approvalParameters.get(approvalParameter).substring(SCOPE_PREFIX.length());
            Set<String> originalScopes = (Set<String>) originalAuthorizationRequest.get("scope");
            if (!originalScopes.contains(scope)) {
                sessionStatus.setComplete();

                logger.warn("The requested scopes are invalid");
                return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, new InvalidScopeException(
                        "The requested scopes are invalid. Please use valid scope names in the request."),
                        false), false, true, false);
            }
        }
    }

    try {
        Set<String> responseTypes = authorizationRequest.getResponseTypes();
        String grantType = deriveGrantTypeFromResponseType(responseTypes);

        authorizationRequest.setApprovalParameters(approvalParameters);
        authorizationRequest = userApprovalHandler.updateAfterApproval(authorizationRequest,
                (Authentication) principal);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);

        if (authorizationRequest.getRedirectUri() == null) {
            sessionStatus.setComplete();
            throw new InvalidRequestException("Cannot approve request when no redirect URI is provided.");
        }

        if (!authorizationRequest.isApproved()) {
            return new RedirectView(getUnsuccessfulRedirect(authorizationRequest,
                    new UserDeniedAuthorizationException("User denied access"),
                    responseTypes.contains("token")), false, true, false);
        }

        if (responseTypes.contains("token") || responseTypes.contains("id_token")) {
            return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal, grantType)
                    .getView();
        }

        return getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal);
    } finally {
        sessionStatus.setComplete();
    }

}

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

@RequestMapping(value = "/oauth/authorize")
public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,
        SessionStatus sessionStatus, Principal principal, HttpServletRequest request) {

    ClientDetails client;// w w  w  .  j av a  2s. c  om
    String clientId;
    try {
        clientId = parameters.get("client_id");
        client = getClientServiceExtention().loadClientByClientId(clientId, IdentityZoneHolder.get().getId());
    } catch (NoSuchClientException x) {
        throw new InvalidClientException(x.getMessage());
    }

    // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
    // query off of the authorization request instead of referring back to the parameters map. The contents of the
    // parameters map will be stored without change in the AuthorizationRequest object once it is created.
    AuthorizationRequest authorizationRequest;
    try {
        authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);
    } catch (DisallowedIdpException x) {
        return switchIdp(model, client, clientId, request);
    }

    Set<String> responseTypes = authorizationRequest.getResponseTypes();
    String grantType = deriveGrantTypeFromResponseType(responseTypes);

    if (!supported_response_types.containsAll(responseTypes)) {
        throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
    }

    if (authorizationRequest.getClientId() == null) {
        throw new InvalidClientException("A client id must be provided");
    }

    String resolvedRedirect = "";
    try {
        String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
        try {
            resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
        } catch (RedirectMismatchException rme) {
            throw new RedirectMismatchException(
                    "Invalid redirect " + redirectUriParameter + " did not match one of the registered values");
        }
        if (!StringUtils.hasText(resolvedRedirect)) {
            throw new RedirectMismatchException(
                    "A redirectUri must be either supplied or preconfigured in the ClientDetails");
        }

        boolean isAuthenticated = (principal instanceof Authentication)
                && ((Authentication) principal).isAuthenticated();

        if (!isAuthenticated) {
            throw new InsufficientAuthenticationException(
                    "User must be authenticated with Spring Security before authorization can be completed.");
        }

        if (!(responseTypes.size() > 0)) {
            return new ModelAndView(new RedirectView(
                    addQueryParameter(addQueryParameter(resolvedRedirect, "error", "invalid_request"),
                            "error_description", "Missing response_type in authorization request")));
        }

        authorizationRequest.setRedirectUri(resolvedRedirect);
        // We intentionally only validate the parameters requested by the client (ignoring any data that may have
        // been added to the request by the manager).
        oauth2RequestValidator.validateScope(authorizationRequest, client);

        // Some systems may allow for approval decisions to be remembered or approved by default. Check for
        // such logic here, and set the approved flag on the authorization request accordingly.
        authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest,
                (Authentication) principal);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);

        // Validation is all done, so we can check for auto approval...
        if (authorizationRequest.isApproved()) {
            if (responseTypes.contains("token") || responseTypes.contains("id_token")) {
                return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal,
                        grantType);
            }
            if (responseTypes.contains("code")) {
                return new ModelAndView(
                        getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal));
            }
        }

        if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
            return new ModelAndView(
                    new RedirectView(addFragmentComponent(resolvedRedirect, "error=interaction_required")));
        } else {
            // Place auth request into the model so that it is stored in the session
            // for approveOrDeny to use. That way we make sure that auth request comes from the session,
            // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.
            model.put(AUTHORIZATION_REQUEST, authorizationRequest);
            model.put("original_uri", UrlUtils.buildFullRequestUrl(request));
            model.put(ORIGINAL_AUTHORIZATION_REQUEST, unmodifiableMap(authorizationRequest));

            return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);
        }
    } catch (RedirectMismatchException e) {
        sessionStatus.setComplete();
        throw e;
    } catch (Exception e) {
        sessionStatus.setComplete();
        logger.debug("Unable to handle /oauth/authorize, internal error", e);
        if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
            return new ModelAndView(
                    new RedirectView(addFragmentComponent(resolvedRedirect, "error=internal_server_error")));
        }

        throw e;
    }

}

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

/**
 * Allows automatic approval for a white list of clients in the implicit
 * grant case.//  w w  w  .  j a v a2  s  .  com
 * 
 * @param authorizationRequest The authorization request.
 * @param userAuthentication the current user authentication
 * 
 * @return Whether the specified request has been approved by the current
 *         user.
 */
@Override
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
    //        if (useTokenServices && super.isApproved(authorizationRequest, userAuthentication)) {
    //            return true;
    //        }
    if (!userAuthentication.isAuthenticated()) {
        return false;
    }
    if (authorizationRequest.isApproved()) {
        return true;
    }
    String clientId = authorizationRequest.getClientId();
    boolean approved = false;
    if (clientDetailsService != null) {
        ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
        Collection<String> requestedScopes = authorizationRequest.getScope();
        if (isAutoApprove(client, requestedScopes)) {
            approved = true;
        }
    }
    return approved;
}

From source file:org.springframework.security.oauth2.provider.approval.ApprovalStoreUserApprovalHandler.java

public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
    return authorizationRequest.isApproved();
}

From source file:org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler.java

/**
 * Basic implementation just requires the authorization request to be explicitly approved and the user to be
 * authenticated./*from   w  ww  .j  a  va  2  s  .com*/
 * 
 * @param authorizationRequest The authorization request.
 * @param userAuthentication the current user authentication
 * 
 * @return Whether the specified request has been approved by the current user.
 */
@Override
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
    return authorizationRequest.isApproved();
}

From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java

@RequestMapping(value = "/oauth/authorize")
public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,
        SessionStatus sessionStatus, Principal principal) {

    logger.info("paramters:" + parameters.toString());
    logger.info("model:" + model.toString());
    // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
    // query off of the authorization request instead of referring back to the parameters map. The contents of the
    // parameters map will be stored without change in the AuthorizationRequest object once it is created.
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory()
            .createAuthorizationRequest(parameters);

    Set<String> responseTypes = authorizationRequest.getResponseTypes();

    if (!responseTypes.contains("token") && !responseTypes.contains("code")) {
        throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
    }/*from   w ww.  ja v  a2  s. c  o m*/

    if (authorizationRequest.getClientId() == null) {
        throw new InvalidClientException("A client id must be provided");
    }

    try {

        if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) {
            throw new InsufficientAuthenticationException(
                    "User must be authenticated with Spring Security before authorization can be completed.");
        }

        ClientDetails client = getClientDetailsService()
                .loadClientByClientId(authorizationRequest.getClientId());

        // The resolved redirect URI is either the redirect_uri from the parameters or the one from
        // clientDetails. Either way we need to store it on the AuthorizationRequest.
        String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
        String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
        if (!StringUtils.hasText(resolvedRedirect)) {
            throw new RedirectMismatchException(
                    "A redirectUri must be either supplied or preconfigured in the ClientDetails");
        }
        authorizationRequest.setRedirectUri(resolvedRedirect);

        // We intentionally only validate the parameters requested by the client (ignoring any data that may have
        // been added to the request by the manager).
        oauth2RequestValidator.validateScope(authorizationRequest, client);

        // Some systems may allow for approval decisions to be remembered or approved by default. Check for
        // such logic here, and set the approved flag on the authorization request accordingly.
        authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest,
                (Authentication) principal);
        // TODO: is this call necessary?
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);

        // Validation is all done, so we can check for auto approval...
        if (authorizationRequest.isApproved()) {
            if (responseTypes.contains("token")) {
                return getImplicitGrantResponse(authorizationRequest);
            }
            if (responseTypes.contains("code")) {
                return new ModelAndView(
                        getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal));
            }
        }

        // Place auth request into the model so that it is stored in the session
        // for approveOrDeny to use. That way we make sure that auth request comes from the session,
        // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.
        model.put("authorizationRequest", authorizationRequest);

        return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);

    } catch (RuntimeException e) {
        sessionStatus.setComplete();
        throw e;
    }

}

From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java

@RequestMapping(value = "/oauth/authorize", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
public View approveOrDeny(@RequestParam Map<String, String> approvalParameters, Map<String, ?> model,
        SessionStatus sessionStatus, Principal principal) {
    logger.info("paramters2:" + approvalParameters.toString());
    logger.info("model:" + model.toString());
    logger.info("PID:" + approvalParameters.get("PID"));
    String PID = (String) approvalParameters.get("PID");
    httpSession.setAttribute("PID", PID);
    logger.info("session PID:" + httpSession.getAttribute("PID"));

    if (!(principal instanceof Authentication)) {
        sessionStatus.setComplete();/*from w w w. j  a  v  a  2 s.  co  m*/
        throw new InsufficientAuthenticationException(
                "User must be authenticated with Spring Security before authorizing an access token.");
    }

    AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");

    if (authorizationRequest == null) {
        sessionStatus.setComplete();
        throw new InvalidRequestException("Cannot approve uninitialized authorization request.");
    }

    try {
        Set<String> responseTypes = authorizationRequest.getResponseTypes();

        authorizationRequest.setApprovalParameters(approvalParameters);
        authorizationRequest = userApprovalHandler.updateAfterApproval(authorizationRequest,
                (Authentication) principal);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);

        if (authorizationRequest.getRedirectUri() == null) {
            sessionStatus.setComplete();
            throw new InvalidRequestException("Cannot approve request when no redirect URI is provided.");
        }

        if (!authorizationRequest.isApproved()) {
            return new RedirectView(getUnsuccessfulRedirect(authorizationRequest,
                    new UserDeniedAuthorizationException("User denied access"),
                    responseTypes.contains("token")), false, true, false);
        }

        if (responseTypes.contains("token")) {
            return getImplicitGrantResponse(authorizationRequest).getView();
        }

        return getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal);
    } finally {
        sessionStatus.setComplete();
    }

}