Example usage for org.springframework.security.oauth2.common.exceptions UserDeniedAuthorizationException UserDeniedAuthorizationException

List of usage examples for org.springframework.security.oauth2.common.exceptions UserDeniedAuthorizationException UserDeniedAuthorizationException

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.exceptions UserDeniedAuthorizationException UserDeniedAuthorizationException.

Prototype

public UserDeniedAuthorizationException(String msg, Throwable t) 

Source Link

Usage

From source file:org.energyos.espi.thirdparty.web.AuthorizationController.java

@RequestMapping(value = Routes.THIRD_PARTY_OAUTH_CODE_CALLBACK, method = RequestMethod.GET)
public String authorization(String code, String state, ModelMap model, Principal principal,
        @RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "error_description", required = false) String error_description,
        @RequestParam(value = "error_uri", required = false) String error_uri) {

    try {//www.j  av a  2 s  . c om

        // Is /oauth/authorization response valid (i.e. is the "state"
        // element correct)?
        Authorization authorization = authorizationService.findByState(state);

        // Process valid /oauth/authorization response
        ApplicationInformation applicationInformation = authorization.getApplicationInformation();

        // Verify /oauth/authorization Endpoint process completed
        // successfully
        if (code != null) {
            try {

                // Update Authorization record with returned authorization
                // code for audit purposes
                authorization.setCode(code);
                authorization.setGrantType("authorization_code");
                authorization.setUpdated(new GregorianCalendar());
                authorizationService.merge(authorization);

                // Format /oauth/token Endpoint request
                String url = String.format("%s?redirect_uri=%s&code=%s&grant_type=authorization_code",
                        applicationInformation.getAuthorizationServerTokenEndpoint(),
                        applicationInformation.getRedirectUri(), code);

                // Build /oauth/token Endpoint request
                ClientRestTemplate restTemplate = templateFactory.newClientRestTemplate(
                        applicationInformation.getClientId(), applicationInformation.getClientSecret());

                // Issue /oauth/token Endpoint request
                AccessToken token = restTemplate.getForObject(url, AccessToken.class);

                // Process /oauth/token Endpoint response

                if (token.getAccessToken() != null) {
                    authorization.setAccessToken(token.getAccessToken());
                    authorization.setTokenType(token.getTokenType());
                    authorization.setExpiresIn(token.getExpiresIn());
                    authorization.setRefreshToken(token.getRefreshToken());
                    authorization.setScope(token.getScope());
                    authorization.setAuthorizationURI(token.getAuthorizationURI());
                    authorization.setResourceURI(token.getResourceURI());
                    authorization.setUpdated(new GregorianCalendar());
                    authorization.setStatus("1"); // Set authorization
                    // record status as
                    // "Active"
                    authorization.setState(null); // Clear State as a
                    // security measure

                    // Update authorization record with /oauth/token
                    // response data
                    authorizationService.merge(authorization);

                    // now do the initial import of the Authorized Resource,
                    // if it is
                    // not ready, then we will wait till we receive a Notify
                    // or the UX call for it.
                    // TODO: create a Subscription to work with if needed

                    RetailCustomer currentCustomer = currentCustomer(principal);

                    try {
                        usagePointRESTRepository.findAllByRetailCustomerId(currentCustomer.getId());

                    } catch (JAXBException e) {
                        // nothing there, so log the fact and move on. It
                        // will get imported later.
                        System.out.printf("\nThirdParty Import Exception: %s\n", e.toString());
                        e.printStackTrace();
                    }
                } else {

                    System.out.printf("\n/oauth/token Request did not return an access token\n");
                }

            } catch (HttpClientErrorException x) {

                // TODO: Extract error, error_description and error_uri from
                // JSON response. Currently recording null for all three
                // fields.

                // Update authorization record
                System.out.printf("\nHTTPClientException: %s\n", x.toString());

                authorization.setError(error);
                authorization.setErrorDescription(error_description);
                authorization.setErrorUri(error_uri);
                authorization.setUpdated(new GregorianCalendar());
                authorization.setStatus("2"); // Set authorization record
                // status as "Denied"
                authorization.setState(null); // Clear State as a security
                // measure
                authorizationService.merge(authorization);

                // TODO: Should the "message" differ based on the exception?
                throw new UserDeniedAuthorizationException("Unable to retrieve OAuth token", x);
            }
        } else {

            System.out.printf("\nOAuth2 authorization_request returned an error:\n");
            System.out.printf("Error:             " + error + "\n");
            System.out.printf("Error_description: " + error_description + "\n");
            System.out.printf("Error_uri:         " + error_uri + "\n");

            // Update authorization record with error response
            authorization.setError(error);
            authorization.setErrorDescription(error_description);
            authorization.setErrorUri(error_uri);
            authorization.setUpdated(new GregorianCalendar());
            authorization.setStatus("2"); // Set authorization record status
            // as "Denied"
            authorization.setState(null); // Clear State as a security
            // measure
            authorizationService.merge(authorization);

            throw new UserDeniedAuthorizationException("Error: " + error_description);

        }

    } catch (NoResultException | EmptyResultDataAccessException e) {

        // We received an invalid /oauth/authorization response
        // TODO: Log receipt of an invalid /oauth/authorization response
        return "/home";

    }

    return "redirect:/RetailCustomer/" + currentCustomer(principal).getId() + "/AuthorizationList";
}