List of usage examples for org.springframework.security.oauth.consumer OAuthRequestFailedException OAuthRequestFailedException
public OAuthRequestFailedException(String msg, Throwable t)
From source file:org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport.java
/** * Read a resource.//from www . ja v a 2 s . c o m * * @param details The details of the resource. * @param url The URL of the resource. * @param httpMethod The http method. * @param token The token. * @param additionalParameters Any additional request parameters. * @param additionalRequestHeaders Any additional request parameters. * @return The resource. */ protected InputStream readResource(ProtectedResourceDetails details, URL url, String httpMethod, OAuthConsumerToken token, Map<String, String> additionalParameters, Map<String, String> additionalRequestHeaders) { url = configureURLForProtectedAccess(url, token, details, httpMethod, additionalParameters); String realm = details.getAuthorizationHeaderRealm(); boolean sendOAuthParamsInRequestBody = !details.isAcceptsAuthorizationHeader() && (("POST".equalsIgnoreCase(httpMethod) || "PUT".equalsIgnoreCase(httpMethod))); HttpURLConnection connection = openConnection(url); try { connection.setRequestMethod(httpMethod); } catch (ProtocolException e) { throw new IllegalStateException(e); } Map<String, String> reqHeaders = details.getAdditionalRequestHeaders(); if (reqHeaders != null) { for (Map.Entry<String, String> requestHeader : reqHeaders.entrySet()) { connection.setRequestProperty(requestHeader.getKey(), requestHeader.getValue()); } } if (additionalRequestHeaders != null) { for (Map.Entry<String, String> requestHeader : additionalRequestHeaders.entrySet()) { connection.setRequestProperty(requestHeader.getKey(), requestHeader.getValue()); } } int responseCode; String responseMessage; try { connection.setDoOutput(sendOAuthParamsInRequestBody); connection.connect(); if (sendOAuthParamsInRequestBody) { String queryString = getOAuthQueryString(details, token, url, httpMethod, additionalParameters); OutputStream out = connection.getOutputStream(); out.write(queryString.getBytes("UTF-8")); out.flush(); out.close(); } responseCode = connection.getResponseCode(); responseMessage = connection.getResponseMessage(); if (responseMessage == null) { responseMessage = "Unknown Error"; } } catch (IOException e) { throw new OAuthRequestFailedException("OAuth connection failed.", e); } if (responseCode >= 200 && responseCode < 300) { try { return connection.getInputStream(); } catch (IOException e) { throw new OAuthRequestFailedException("Unable to get the input stream from a successful response.", e); } } else if (responseCode == 400) { throw new OAuthRequestFailedException("OAuth authentication failed: " + responseMessage); } else if (responseCode == 401) { String authHeaderValue = connection.getHeaderField("WWW-Authenticate"); if (authHeaderValue != null) { Map<String, String> headerEntries = StringSplitUtils.splitEachArrayElementAndCreateMap( StringSplitUtils.splitIgnoringQuotes(authHeaderValue, ','), "=", "\""); String requiredRealm = headerEntries.get("realm"); if ((requiredRealm != null) && (!requiredRealm.equals(realm))) { throw new InvalidOAuthRealmException(String.format( "Invalid OAuth realm. Provider expects \"%s\", when the resource details specify \"%s\".", requiredRealm, realm), requiredRealm); } } throw new OAuthRequestFailedException("OAuth authentication failed: " + responseMessage); } else { throw new OAuthRequestFailedException( String.format("Invalid response code %s (%s).", responseCode, responseMessage)); } }
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./* www . j a v a 2 s . c om*/ * @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.client.CoreOAuthConsumerSupport.java
/** * Loads the OAuth parameters for the given resource at the given URL and the given token. These parameters include * any query parameters on the URL since they are included in the signature. The oauth parameters are NOT encoded. * * @param details The resource details. * @param requestURL The request URL./* www .ja va2 s. com*/ * @param requestToken The request token. * @param httpMethod The http method. * @param additionalParameters Additional oauth parameters (outside of the core oauth spec). * @return The parameters. */ protected Map<String, Set<CharSequence>> loadOAuthParameters(ProtectedResourceDetails details, URL requestURL, OAuthConsumerToken requestToken, String httpMethod, Map<String, String> additionalParameters) { Map<String, Set<CharSequence>> oauthParams = new TreeMap<String, Set<CharSequence>>(); if (additionalParameters != null) { for (Map.Entry<String, String> additionalParam : additionalParameters.entrySet()) { Set<CharSequence> values = oauthParams.get(additionalParam.getKey()); if (values == null) { values = new HashSet<CharSequence>(); oauthParams.put(additionalParam.getKey(), values); } if (additionalParam.getValue() != null) { values.add(additionalParam.getValue()); } } } String query = requestURL.getQuery(); if (query != null) { StringTokenizer queryTokenizer = new StringTokenizer(query, "&"); while (queryTokenizer.hasMoreElements()) { String token = (String) queryTokenizer.nextElement(); CharSequence value = null; int equalsIndex = token.indexOf('='); if (equalsIndex < 0) { token = urlDecode(token); } else { value = new QueryParameterValue(urlDecode(token.substring(equalsIndex + 1))); token = urlDecode(token.substring(0, equalsIndex)); } Set<CharSequence> values = oauthParams.get(token); if (values == null) { values = new HashSet<CharSequence>(); oauthParams.put(token, values); } if (value != null) { values.add(value); } } } String tokenSecret = requestToken == null ? null : requestToken.getSecret(); String nonce = getNonceFactory().generateNonce(); oauthParams.put(OAuthConsumerParameter.oauth_consumer_key.toString(), Collections.singleton((CharSequence) details.getConsumerKey())); if ((requestToken != null) && (requestToken.getValue() != null)) { oauthParams.put(OAuthConsumerParameter.oauth_token.toString(), Collections.singleton((CharSequence) requestToken.getValue())); } oauthParams.put(OAuthConsumerParameter.oauth_nonce.toString(), Collections.singleton((CharSequence) nonce)); oauthParams.put(OAuthConsumerParameter.oauth_signature_method.toString(), Collections.singleton((CharSequence) details.getSignatureMethod())); oauthParams.put(OAuthConsumerParameter.oauth_timestamp.toString(), Collections.singleton((CharSequence) String.valueOf(System.currentTimeMillis() / 1000))); oauthParams.put(OAuthConsumerParameter.oauth_version.toString(), Collections.singleton((CharSequence) "1.0")); String signatureBaseString = getSignatureBaseString(oauthParams, requestURL, httpMethod); OAuthSignatureMethod signatureMethod; try { signatureMethod = getSignatureFactory().getSignatureMethod(details.getSignatureMethod(), details.getSharedSecret(), tokenSecret); } catch (UnsupportedSignatureMethodException e) { throw new OAuthRequestFailedException(e.getMessage(), e); } String signature = signatureMethod.sign(signatureBaseString); oauthParams.put(OAuthConsumerParameter.oauth_signature.toString(), Collections.singleton((CharSequence) signature)); return oauthParams; }
From source file:org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport.java
/** * Open a connection to the given URL.// www. j a v a 2s. co m * * @param requestTokenURL The request token URL. * @return The HTTP URL connection. */ protected HttpURLConnection openConnection(URL requestTokenURL) { try { HttpURLConnection connection = (HttpURLConnection) requestTokenURL .openConnection(selectProxy(requestTokenURL)); connection.setConnectTimeout(getConnectionTimeout()); connection.setReadTimeout(getReadTimeout()); return connection; } catch (IOException e) { throw new OAuthRequestFailedException("Failed to open an OAuth connection.", e); } }