Example usage for org.springframework.security.oauth2.client OAuth2RestOperations getAccessToken

List of usage examples for org.springframework.security.oauth2.client OAuth2RestOperations getAccessToken

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.client OAuth2RestOperations getAccessToken.

Prototype

OAuth2AccessToken getAccessToken() throws UserRedirectRequiredException;

Source Link

Usage

From source file:org.openmhealth.shim.OAuth2ShimBase.java

@Override
public AuthorizationResponse handleAuthorizationResponse(HttpServletRequest servletRequest)
        throws ShimException {

    String state = servletRequest.getParameter("state");
    String code = servletRequest.getParameter("code");

    AuthorizationRequestParameters authorizationRequestParameters = authorizationRequestParametersRepo
            .findByStateKey(state);//from ww w.  j  av a2 s.c o  m

    if (authorizationRequestParameters == null) {
        throw new IllegalStateException(
                "Could not find corresponding authorization " + "request parameters, cannot continue.");
    }

    OAuth2RestOperations restTemplate = restTemplate(state, code);
    try {
        /**
         * Create a persistable access parameters entity so that
         * spring oauth2's client token services can relate
         * the serialized OAuth2AccessToken to it.
         */
        AccessParameters accessParameters = new AccessParameters();
        accessParameters.setUsername(authorizationRequestParameters.getUsername());
        accessParameters.setShimKey(getShimKey());
        accessParameters.setStateKey(state);
        accessParametersRepo.save(accessParameters);

        trigger(restTemplate, getTriggerDataRequest());

        /**
         * By this line we will have an approved access token or
         * not, if we do not then we delete the access parameters entity.
         */
        if (restTemplate.getAccessToken() == null) {
            accessParametersRepo.delete(accessParameters);
            return AuthorizationResponse.error("Did not receive approval");
        } else {
            accessParameters = accessParametersRepo.findByUsernameAndShimKey(
                    authorizationRequestParameters.getUsername(), getShimKey(),
                    new Sort(Sort.Direction.DESC, "dateCreated"));
        }
        return AuthorizationResponse.authorized(accessParameters);
    } catch (OAuth2Exception e) {
        //TODO: OAuth2Exception may include other stuff
        System.out.println("Problem trying out the token!");
        e.printStackTrace();
        return AuthorizationResponse.error(e.getMessage());
    }
}