Example usage for org.springframework.security.oauth.consumer OAuthSecurityContextImpl setAccessTokens

List of usage examples for org.springframework.security.oauth.consumer OAuthSecurityContextImpl setAccessTokens

Introduction

In this page you can find the example usage for org.springframework.security.oauth.consumer OAuthSecurityContextImpl setAccessTokens.

Prototype

public void setAccessTokens(Map<String, OAuthConsumerToken> accessTokens) 

Source Link

Usage

From source file:info.raack.appliancelabeler.datacollector.StepgreenTED5000ConfigurationLoader.java

private Map<String, List<Ted5000>> reloadConfigurations() {
    // get url for all configurations

    String response = "";
    try {/*w  w w  .  jav  a2  s .co  m*/
        logger.debug("Requesting user TEDs");
        synchronized (this) {

            Map<String, List<Ted5000>> allTeds = new HashMap<String, List<Ted5000>>();

            // construct oauth access tokens
            Map<String, Map<String, OAuthConsumerToken>> userContexts = database.getOAuthTokensForAllUsers();

            for (String userId : userContexts.keySet()) {
                logger.debug("Request TEDs for " + userId);
                Map<String, OAuthConsumerToken> tokenMap = userContexts.get(userId);

                if (tokenMap.isEmpty()) {
                    // don't request anything with no tokens
                    continue;
                }

                OAuthSecurityContextImpl oAuthContext = new OAuthSecurityContextImpl();
                oAuthContext.setAccessTokens(tokenMap);

                String requestURI = String.format(tedDataPath, stepgreenBasehost, userId);

                try {
                    allTeds.put(userId, oAuthRequestProcessor.processRequest(requestURI, oAuthContext,
                            new ResponseHandler<AggregatedTeds, List<Ted5000>>() {
                                public List<Ted5000> extractValue(AggregatedTeds ted) {
                                    return ted.getTed5000();
                                }
                            }));
                } catch (OAuthUnauthorizedException e2) {
                    String email = database.getUserEmailForUserId(userId);
                    logger.warn("Could not get list of TEDS for user " + userId
                            + " - request through oauth is unauthorized");
                    emailSender.sendGeneralEmail(email,
                            "Your Stepgreen energy consumption authorization is no longer valid",
                            "At some point in the past, you used the Stepgreen Appliance Energy Visualization tool to see detailed usage of your appliance energy use.\n\n"
                                    + "We have become unable to access your Stepgreen energy data. If you wish to continue using the tool, please visit "
                                    + energylabelerUrl + " now. "
                                    + "We will be unable to collect and provide any more energy predictions until you do so.\n\n"
                                    + "Thanks,\n" + "The Stepgreen Appliance Energy Team");

                    // now invalidate the tokens
                    tokenMap.clear();
                    dataService.saveOAuthTokensForUserId(userId, email, tokenMap);
                }
            }

            return allTeds;
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not get list of TEDs from StepGreen: received " + response, e);
    }
}

From source file:org.cloudfoundry.identity.uaa.client.OAuthClientAuthenticationFilterTests.java

private void setUpContext(String tokenName, String secretName, String keyName, String sharedName) {
    resource.setId("foo");
    String consumerKey = System.getProperty(keyName);
    Assume.assumeNotNull(consumerKey);// w ww.jav  a  2 s  .  com
    String sharedSecret = System.getProperty(sharedName);
    Assume.assumeNotNull(sharedSecret);
    String accessToken = System.getProperty(tokenName);
    Assume.assumeNotNull(accessToken);
    String secret = System.getProperty(secretName);
    Assume.assumeNotNull(accessToken);
    OAuthSecurityContextImpl context = new OAuthSecurityContextImpl();
    OAuthConsumerToken token = new OAuthConsumerToken();
    resource.setConsumerKey(consumerKey);
    resource.setSharedSecret(new SharedConsumerSecretImpl(sharedSecret));
    token.setValue(accessToken);
    token.setSecret(secret);
    context.setAccessTokens(Collections.singletonMap("foo", token));
    OAuthSecurityContextHolder.setContext(context);
}

From source file:info.raack.appliancelabeler.service.DefaultDataService.java

public OAuthData getOAuthDataForUserId(String userId) {
    OAuthSecurityContextImpl oAuthContext = new OAuthSecurityContextImpl();
    oAuthContext.setAccessTokens(getOAuthTokensForUserId(userId));

    OAuthData oAuthData = new OAuthData(oAuthRequestProcessor, oAuthContext);
    return oAuthData;
}

From source file:org.springframework.security.oauth.consumer.filter.OAuthConsumerContextFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    OAuthSecurityContextImpl context = new OAuthSecurityContextImpl();
    context.setDetails(request);/*from   w  w w.  ja v a 2  s. c  o  m*/

    Map<String, OAuthConsumerToken> rememberedTokens = getRememberMeServices().loadRememberedTokens(request,
            response);
    Map<String, OAuthConsumerToken> accessTokens = new TreeMap<String, OAuthConsumerToken>();
    Map<String, OAuthConsumerToken> requestTokens = new TreeMap<String, OAuthConsumerToken>();
    if (rememberedTokens != null) {
        for (Map.Entry<String, OAuthConsumerToken> tokenEntry : rememberedTokens.entrySet()) {
            OAuthConsumerToken token = tokenEntry.getValue();
            if (token != null) {
                if (token.isAccessToken()) {
                    accessTokens.put(tokenEntry.getKey(), token);
                } else {
                    requestTokens.put(tokenEntry.getKey(), token);
                }
            }
        }
    }

    context.setAccessTokens(accessTokens);
    OAuthSecurityContextHolder.setContext(context);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Storing access tokens in request attribute '" + getAccessTokensRequestAttribute() + "'.");
    }

    try {
        try {
            request.setAttribute(getAccessTokensRequestAttribute(),
                    new ArrayList<OAuthConsumerToken>(accessTokens.values()));
            chain.doFilter(request, response);
        } catch (Exception e) {
            try {
                ProtectedResourceDetails resourceThatNeedsAuthorization = checkForResourceThatNeedsAuthorization(
                        e);
                String neededResourceId = resourceThatNeedsAuthorization.getId();
                while (!accessTokens.containsKey(neededResourceId)) {
                    OAuthConsumerToken token = requestTokens.remove(neededResourceId);
                    if (token == null) {
                        token = getTokenServices().getToken(neededResourceId);
                    }

                    String verifier = request.getParameter(OAuthProviderParameter.oauth_verifier.toString());
                    // if the token is null OR
                    // if there is NO access token and (we're not using 1.0a or the verifier is not null)
                    if (token == null || (!token.isAccessToken()
                            && (!resourceThatNeedsAuthorization.isUse10a() || verifier == null))) {
                        //no token associated with the resource, start the oauth flow.
                        //if there's a request token, but no verifier, we'll assume that a previous oauth request failed and we need to get a new request token.
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Obtaining request token for resource: " + neededResourceId);
                        }

                        //obtain authorization.
                        String callbackURL = response.encodeRedirectURL(getCallbackURL(request));
                        token = getConsumerSupport().getUnauthorizedRequestToken(neededResourceId, callbackURL);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Request token obtained for resource " + neededResourceId + ": " + token);
                        }

                        //okay, we've got a request token, now we need to authorize it.
                        requestTokens.put(neededResourceId, token);
                        getTokenServices().storeToken(neededResourceId, token);
                        String redirect = getUserAuthorizationRedirectURL(resourceThatNeedsAuthorization, token,
                                callbackURL);

                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Redirecting request to " + redirect
                                    + " for user authorization of the request token for resource "
                                    + neededResourceId + ".");
                        }

                        request.setAttribute(
                                "org.springframework.security.oauth.consumer.AccessTokenRequiredException", e);
                        this.redirectStrategy.sendRedirect(request, response, redirect);
                        return;
                    } else if (!token.isAccessToken()) {
                        //we have a presumably authorized request token, let's try to get an access token with it.
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Obtaining access token for resource: " + neededResourceId);
                        }

                        //authorize the request token and store it.
                        try {
                            token = getConsumerSupport().getAccessToken(token, verifier);
                        } finally {
                            getTokenServices().removeToken(neededResourceId);
                        }

                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Access token " + token + " obtained for resource " + neededResourceId
                                    + ". Now storing and using.");
                        }

                        getTokenServices().storeToken(neededResourceId, token);
                    }

                    accessTokens.put(neededResourceId, token);

                    try {
                        //try again
                        if (!response.isCommitted()) {
                            request.setAttribute(getAccessTokensRequestAttribute(),
                                    new ArrayList<OAuthConsumerToken>(accessTokens.values()));
                            chain.doFilter(request, response);
                        } else {
                            //dang. what do we do now?
                            throw new IllegalStateException(
                                    "Unable to reprocess filter chain with needed OAuth2 resources because the response is already committed.");
                        }
                    } catch (Exception e1) {
                        resourceThatNeedsAuthorization = checkForResourceThatNeedsAuthorization(e1);
                        neededResourceId = resourceThatNeedsAuthorization.getId();
                    }
                }
            } catch (OAuthRequestFailedException eo) {
                fail(request, response, eo);
            } catch (Exception ex) {
                Throwable[] causeChain = getThrowableAnalyzer().determineCauseChain(ex);
                OAuthRequestFailedException rfe = (OAuthRequestFailedException) getThrowableAnalyzer()
                        .getFirstThrowableOfType(OAuthRequestFailedException.class, causeChain);
                if (rfe != null) {
                    fail(request, response, rfe);
                } else {
                    // Rethrow ServletExceptions and RuntimeExceptions as-is
                    if (ex instanceof ServletException) {
                        throw (ServletException) ex;
                    } else if (ex instanceof RuntimeException) {
                        throw (RuntimeException) ex;
                    }

                    // Wrap other Exceptions. These are not expected to happen
                    throw new RuntimeException(ex);
                }
            }
        }
    } finally {
        OAuthSecurityContextHolder.setContext(null);
        HashMap<String, OAuthConsumerToken> tokensToRemember = new HashMap<String, OAuthConsumerToken>();
        tokensToRemember.putAll(requestTokens);
        tokensToRemember.putAll(accessTokens);
        getRememberMeServices().rememberTokens(tokensToRemember, request, response);
    }
}