Example usage for org.springframework.security.oauth.consumer ProtectedResourceDetails isAcceptsAuthorizationHeader

List of usage examples for org.springframework.security.oauth.consumer ProtectedResourceDetails isAcceptsAuthorizationHeader

Introduction

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

Prototype

boolean isAcceptsAuthorizationHeader();

Source Link

Document

Whether the provider of this resource accepts the OAuth Authorization HTTP header.

Usage

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.");
    }/*from   ww  w .  j av a2  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

/**
 * Read a resource.//from  w  ww. j  av  a2 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

/**
 * Internal use of configuring the URL for protected access, the resource details already having been loaded.
 *
 * @param url          The URL./*from ww  w .  j  a v  a2s  .c o m*/
 * @param requestToken The request token.
 * @param details      The details.
 * @param httpMethod   The http method.
 * @param additionalParameters Any additional request parameters.
 * @return The configured URL.
 */
protected URL configureURLForProtectedAccess(URL url, OAuthConsumerToken requestToken,
        ProtectedResourceDetails details, String httpMethod, Map<String, String> additionalParameters) {
    String file;
    if (!"POST".equalsIgnoreCase(httpMethod) && !"PUT".equalsIgnoreCase(httpMethod)
            && !details.isAcceptsAuthorizationHeader()) {
        StringBuilder fileb = new StringBuilder(url.getPath());
        String queryString = getOAuthQueryString(details, requestToken, url, httpMethod, additionalParameters);
        fileb.append('?').append(queryString);
        file = fileb.toString();
    } else {
        file = url.getFile();
    }

    try {
        if ("http".equalsIgnoreCase(url.getProtocol())) {
            URLStreamHandler streamHandler = getStreamHandlerFactory().getHttpStreamHandler(details,
                    requestToken, this, httpMethod, additionalParameters);
            return new URL(url.getProtocol(), url.getHost(), url.getPort(), file, streamHandler);
        } else if ("https".equalsIgnoreCase(url.getProtocol())) {
            URLStreamHandler streamHandler = getStreamHandlerFactory().getHttpsStreamHandler(details,
                    requestToken, this, httpMethod, additionalParameters);
            return new URL(url.getProtocol(), url.getHost(), url.getPort(), file, streamHandler);
        } else {
            throw new OAuthRequestFailedException("Unsupported OAuth protocol: " + url.getProtocol());
        }
    } catch (MalformedURLException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport.java

public String getAuthorizationHeader(ProtectedResourceDetails details, OAuthConsumerToken accessToken, URL url,
        String httpMethod, Map<String, String> additionalParameters) {
    if (!details.isAcceptsAuthorizationHeader()) {
        return null;
    } else {//  w  ww .j a  v  a2 s .co  m
        Map<String, Set<CharSequence>> oauthParams = loadOAuthParameters(details, url, accessToken, httpMethod,
                additionalParameters);
        String realm = details.getAuthorizationHeaderRealm();

        StringBuilder builder = new StringBuilder("OAuth ");
        boolean writeComma = false;
        if (realm != null) { //realm is optional.
            builder.append("realm=\"").append(realm).append('"');
            writeComma = true;
        }

        for (Map.Entry<String, Set<CharSequence>> paramValuesEntry : oauthParams.entrySet()) {
            Set<CharSequence> paramValues = paramValuesEntry.getValue();
            CharSequence paramValue = findValidHeaderValue(paramValues);
            if (paramValue != null) {
                if (writeComma) {
                    builder.append(", ");
                }

                builder.append(paramValuesEntry.getKey()).append("=\"")
                        .append(oauthEncode(paramValue.toString())).append('"');
                writeComma = true;
            }
        }

        return builder.toString();
    }
}

From source file:org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport.java

public String getOAuthQueryString(ProtectedResourceDetails details, OAuthConsumerToken accessToken, URL url,
        String httpMethod, Map<String, String> additionalParameters) {
    Map<String, Set<CharSequence>> oauthParams = loadOAuthParameters(details, url, accessToken, httpMethod,
            additionalParameters);/*from   w ww  . ja  v  a 2  s . c  o m*/

    StringBuilder queryString = new StringBuilder();
    if (details.isAcceptsAuthorizationHeader()) {
        //if the resource accepts the auth header, remove any parameters that will go in the header (don't pass them redundantly in the query string).
        for (OAuthConsumerParameter oauthParam : OAuthConsumerParameter.values()) {
            oauthParams.remove(oauthParam.toString());
        }

        if (additionalParameters != null) {
            for (String additionalParam : additionalParameters.keySet()) {
                oauthParams.remove(additionalParam);
            }
        }
    }

    Iterator<String> parametersIt = oauthParams.keySet().iterator();
    while (parametersIt.hasNext()) {
        String parameter = parametersIt.next();
        queryString.append(parameter);
        Set<CharSequence> values = oauthParams.get(parameter);
        if (values != null) {
            Iterator<CharSequence> valuesIt = values.iterator();
            while (valuesIt.hasNext()) {
                CharSequence parameterValue = valuesIt.next();
                if (parameterValue != null) {
                    queryString.append('=').append(urlEncode(parameterValue.toString()));
                }
                if (valuesIt.hasNext()) {
                    queryString.append('&').append(parameter);
                }
            }
        }
        if (parametersIt.hasNext()) {
            queryString.append('&');
        }
    }

    return queryString.toString();
}

From source file:org.springframework.security.oauth.consumer.CoreOAuthConsumerSupport.java

public String getOAuthQueryString(ProtectedResourceDetails details, OAuthConsumerToken accessToken, URL url,
        String httpMethod, Map<String, String> additionalParameters) {
    Map<String, Set<CharSequence>> oauthParams = loadOAuthParameters(details, url, accessToken, httpMethod,
            additionalParameters);//from   w  w w .  j av a  2 s .c  o m

    StringBuilder queryString = new StringBuilder();
    if (details.isAcceptsAuthorizationHeader()) {
        //if the resource accepts the auth header, remove any parameters that will go in the header (don't pass them redundantly in the query string).
        for (OAuthConsumerParameter oauthParam : OAuthConsumerParameter.values()) {
            oauthParams.remove(oauthParam.toString());
        }

        if (additionalParameters != null) {
            for (String additionalParam : additionalParameters.keySet()) {
                oauthParams.remove(additionalParam);
            }
        }
    }

    Iterator<String> parametersIt = oauthParams.keySet().iterator();
    while (parametersIt.hasNext()) {
        String parameter = parametersIt.next();
        queryString.append(parameter);
        Set<CharSequence> values = oauthParams.get(parameter);
        if (values != null) {
            Iterator<CharSequence> valuesIt = values.iterator();
            while (valuesIt.hasNext()) {
                CharSequence parameterValue = valuesIt.next();
                if (parameterValue != null) {
                    queryString.append('=').append(parameterValue);
                }
                if (valuesIt.hasNext()) {
                    queryString.append('&').append(parameter);
                }
            }
        }
        if (parametersIt.hasNext()) {
            queryString.append('&');
        }
    }

    return queryString.toString();
}