List of usage examples for org.springframework.security.oauth.consumer ProtectedResourceDetails getId
String getId();
From source file:org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport.java
public InputStream readProtectedResource(URL url, OAuthConsumerToken accessToken, String httpMethod) throws OAuthRequestFailedException { if (accessToken == null) { throw new OAuthRequestFailedException("A valid access token must be supplied."); }/* ww w . j a va 2 s .c om*/ ProtectedResourceDetails resourceDetails = getProtectedResourceDetailsService() .loadProtectedResourceDetailsById(accessToken.getResourceId()); if ((!resourceDetails.isAcceptsAuthorizationHeader()) && !"POST".equalsIgnoreCase(httpMethod) && !"PUT".equalsIgnoreCase(httpMethod)) { throw new IllegalArgumentException("Protected resource " + resourceDetails.getId() + " cannot be accessed with HTTP method " + httpMethod + " because the OAuth provider doesn't accept the OAuth Authorization header."); } return readResource(resourceDetails, url, httpMethod, accessToken, resourceDetails.getAdditionalParameters(), null); }
From source file:org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport.java
/** * Get the consumer token with the given parameters and URL. The determination of whether the retrieved token * is an access token depends on whether a request token is provided. * * @param details The resource details. * @param tokenURL The token URL./*from w w w . j av a2 s . c o m*/ * @param httpMethod The http method. * @param requestToken The request token, or null if none. * @param additionalParameters The additional request parameter. * @return The token. */ protected OAuthConsumerToken getTokenFromProvider(ProtectedResourceDetails details, URL tokenURL, String httpMethod, OAuthConsumerToken requestToken, Map<String, String> additionalParameters) { boolean isAccessToken = requestToken != null; if (!isAccessToken) { //create an empty token to make a request for a new unauthorized request token. requestToken = new OAuthConsumerToken(); } TreeMap<String, String> requestHeaders = new TreeMap<String, String>(); if ("POST".equalsIgnoreCase(httpMethod)) { requestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); } InputStream inputStream = readResource(details, tokenURL, httpMethod, requestToken, additionalParameters, requestHeaders); String tokenInfo; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = inputStream.read(buffer); while (len >= 0) { out.write(buffer, 0, len); len = inputStream.read(buffer); } tokenInfo = new String(out.toByteArray(), "UTF-8"); } catch (IOException e) { throw new OAuthRequestFailedException("Unable to read the token.", e); } StringTokenizer tokenProperties = new StringTokenizer(tokenInfo, "&"); Map<String, String> tokenPropertyValues = new TreeMap<String, String>(); while (tokenProperties.hasMoreElements()) { try { String tokenProperty = (String) tokenProperties.nextElement(); int equalsIndex = tokenProperty.indexOf('='); if (equalsIndex > 0) { String propertyName = OAuthCodec.oauthDecode(tokenProperty.substring(0, equalsIndex)); String propertyValue = OAuthCodec.oauthDecode(tokenProperty.substring(equalsIndex + 1)); tokenPropertyValues.put(propertyName, propertyValue); } else { tokenProperty = OAuthCodec.oauthDecode(tokenProperty); tokenPropertyValues.put(tokenProperty, null); } } catch (DecoderException e) { throw new OAuthRequestFailedException("Unable to decode token parameters."); } } String tokenValue = tokenPropertyValues.remove(OAuthProviderParameter.oauth_token.toString()); if (tokenValue == null) { throw new OAuthRequestFailedException("OAuth provider failed to return a token."); } String tokenSecret = tokenPropertyValues.remove(OAuthProviderParameter.oauth_token_secret.toString()); if (tokenSecret == null) { throw new OAuthRequestFailedException("OAuth provider failed to return a token secret."); } OAuthConsumerToken consumerToken = new OAuthConsumerToken(); consumerToken.setValue(tokenValue); consumerToken.setSecret(tokenSecret); consumerToken.setResourceId(details.getId()); consumerToken.setAccessToken(isAccessToken); if (!tokenPropertyValues.isEmpty()) { consumerToken.setAdditionalParameters(tokenPropertyValues); } return consumerToken; }
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 ww w. ja va 2s. 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); } }