Search in sources :

Example 6 with OAuthRequestFailedException

use of org.springframework.security.oauth.consumer.OAuthRequestFailedException in project spring-security-oauth by spring-projects.

the class CoreOAuthConsumerSupport method readResource.

/**
 * Read a resource.
 *
 * @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));
    }
}
Also used : InvalidOAuthRealmException(org.springframework.security.oauth.consumer.InvalidOAuthRealmException) OAuthRequestFailedException(org.springframework.security.oauth.consumer.OAuthRequestFailedException)

Example 7 with OAuthRequestFailedException

use of org.springframework.security.oauth.consumer.OAuthRequestFailedException in project spring-security-oauth by spring-projects.

the class CoreOAuthConsumerSupport method getTokenFromProvider.

/**
 * 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.
 * @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;
}
Also used : OAuthRequestFailedException(org.springframework.security.oauth.consumer.OAuthRequestFailedException) OAuthConsumerToken(org.springframework.security.oauth.consumer.OAuthConsumerToken) DecoderException(org.apache.commons.codec.DecoderException)

Example 8 with OAuthRequestFailedException

use of org.springframework.security.oauth.consumer.OAuthRequestFailedException in project spring-security-oauth by spring-projects.

the class CoreOAuthConsumerSupportTests method testReadResouce.

/**
 * readResouce
 */
@Test
public void testReadResouce() throws Exception {
    OAuthConsumerToken token = new OAuthConsumerToken();
    URL url = new URL("http://myhost.com/resource?with=some&query=params&too");
    final ConnectionProps connectionProps = new ConnectionProps();
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(new byte[0]);
    final HttpURLConnectionForTestingPurposes connectionMock = new HttpURLConnectionForTestingPurposes(url) {

        @Override
        public void setRequestMethod(String method) throws ProtocolException {
            connectionProps.method = method;
        }

        @Override
        public void setDoOutput(boolean dooutput) {
            connectionProps.doOutput = dooutput;
        }

        @Override
        public void connect() throws IOException {
            connectionProps.connected = true;
        }

        @Override
        public OutputStream getOutputStream() throws IOException {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            connectionProps.outputStream = out;
            return out;
        }

        @Override
        public int getResponseCode() throws IOException {
            return connectionProps.responseCode;
        }

        @Override
        public String getResponseMessage() throws IOException {
            return connectionProps.responseMessage;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return inputStream;
        }

        @Override
        public String getHeaderField(String name) {
            return connectionProps.headerFields.get(name);
        }
    };
    CoreOAuthConsumerSupport support = new CoreOAuthConsumerSupport() {

        @Override
        public URL configureURLForProtectedAccess(URL url, OAuthConsumerToken accessToken, ProtectedResourceDetails details, String httpMethod, Map<String, String> additionalParameters) throws OAuthRequestFailedException {
            try {
                return new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile(), new StreamHandlerForTestingPurposes(connectionMock));
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public String getOAuthQueryString(ProtectedResourceDetails details, OAuthConsumerToken accessToken, URL url, String httpMethod, Map<String, String> additionalParameters) {
            return "POSTBODY";
        }
    };
    support.setStreamHandlerFactory(new DefaultOAuthURLStreamHandlerFactory());
    when(details.getAuthorizationHeaderRealm()).thenReturn("realm1");
    when(details.isAcceptsAuthorizationHeader()).thenReturn(true);
    when(details.getAdditionalRequestHeaders()).thenReturn(null);
    try {
        support.readResource(details, url, "POST", token, null, null);
        fail("shouldn't have been a valid response code.");
    } catch (OAuthRequestFailedException e) {
    // fall through...
    }
    assertFalse(connectionProps.doOutput);
    assertEquals("POST", connectionProps.method);
    assertTrue(connectionProps.connected);
    connectionProps.reset();
    when(details.getAuthorizationHeaderRealm()).thenReturn(null);
    when(details.isAcceptsAuthorizationHeader()).thenReturn(true);
    when(details.getAdditionalRequestHeaders()).thenReturn(null);
    connectionProps.responseCode = 400;
    connectionProps.responseMessage = "Nasty";
    try {
        support.readResource(details, url, "POST", token, null, null);
        fail("shouldn't have been a valid response code.");
    } catch (OAuthRequestFailedException e) {
    // fall through...
    }
    assertFalse(connectionProps.doOutput);
    assertEquals("POST", connectionProps.method);
    assertTrue(connectionProps.connected);
    connectionProps.reset();
    when(details.getAuthorizationHeaderRealm()).thenReturn(null);
    when(details.isAcceptsAuthorizationHeader()).thenReturn(true);
    when(details.getAdditionalRequestHeaders()).thenReturn(null);
    connectionProps.responseCode = 401;
    connectionProps.responseMessage = "Bad Realm";
    connectionProps.headerFields.put("WWW-Authenticate", "realm=\"goodrealm\"");
    try {
        support.readResource(details, url, "POST", token, null, null);
        fail("shouldn't have been a valid response code.");
    } catch (InvalidOAuthRealmException e) {
    // fall through...
    }
    assertFalse(connectionProps.doOutput);
    assertEquals("POST", connectionProps.method);
    assertTrue(connectionProps.connected);
    connectionProps.reset();
    when(details.getAuthorizationHeaderRealm()).thenReturn(null);
    when(details.isAcceptsAuthorizationHeader()).thenReturn(true);
    when(details.getAdditionalRequestHeaders()).thenReturn(null);
    connectionProps.responseCode = 200;
    connectionProps.responseMessage = "Congrats";
    assertSame(inputStream, support.readResource(details, url, "GET", token, null, null));
    assertFalse(connectionProps.doOutput);
    assertEquals("GET", connectionProps.method);
    assertTrue(connectionProps.connected);
    connectionProps.reset();
    when(details.getAuthorizationHeaderRealm()).thenReturn(null);
    when(details.isAcceptsAuthorizationHeader()).thenReturn(false);
    when(details.getAdditionalRequestHeaders()).thenReturn(null);
    connectionProps.responseCode = 200;
    connectionProps.responseMessage = "Congrats";
    assertSame(inputStream, support.readResource(details, url, "POST", token, null, null));
    assertEquals("POSTBODY", new String(((ByteArrayOutputStream) connectionProps.outputStream).toByteArray()));
    assertTrue(connectionProps.doOutput);
    assertEquals("POST", connectionProps.method);
    assertTrue(connectionProps.connected);
    connectionProps.reset();
}
Also used : MalformedURLException(java.net.MalformedURLException) DefaultOAuthURLStreamHandlerFactory(org.springframework.security.oauth.consumer.net.DefaultOAuthURLStreamHandlerFactory) InvalidOAuthRealmException(org.springframework.security.oauth.consumer.InvalidOAuthRealmException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OAuthRequestFailedException(org.springframework.security.oauth.consumer.OAuthRequestFailedException) URL(java.net.URL) OAuthConsumerToken(org.springframework.security.oauth.consumer.OAuthConsumerToken) ByteArrayInputStream(java.io.ByteArrayInputStream) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) ProtectedResourceDetails(org.springframework.security.oauth.consumer.ProtectedResourceDetails) Test(org.junit.Test)

Aggregations

OAuthRequestFailedException (org.springframework.security.oauth.consumer.OAuthRequestFailedException)8 OAuthConsumerToken (org.springframework.security.oauth.consumer.OAuthConsumerToken)3 ProtectedResourceDetails (org.springframework.security.oauth.consumer.ProtectedResourceDetails)3 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 TreeMap (java.util.TreeMap)2 ServletException (javax.servlet.ServletException)2 AccessTokenRequiredException (org.springframework.security.oauth.consumer.AccessTokenRequiredException)2 InvalidOAuthRealmException (org.springframework.security.oauth.consumer.InvalidOAuthRealmException)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 ArrayList (java.util.ArrayList)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 DecoderException (org.apache.commons.codec.DecoderException)1 Test (org.junit.Test)1