Example usage for org.springframework.security.oauth.common OAuthConsumerParameter oauth_signature

List of usage examples for org.springframework.security.oauth.common OAuthConsumerParameter oauth_signature

Introduction

In this page you can find the example usage for org.springframework.security.oauth.common OAuthConsumerParameter oauth_signature.

Prototype

OAuthConsumerParameter oauth_signature

To view the source code for org.springframework.security.oauth.common OAuthConsumerParameter oauth_signature.

Click Source Link

Document

Parameter for the signature.

Usage

From source file:ltistarter.oauth.OAuth1LibraryTests.java

@Test
public void testParseParameters() throws Exception {
    CoreOAuthProviderSupport support = new CoreOAuthProviderSupport();
    when(request.getHeaders("Authorization"))
            .thenReturn(Collections.enumeration(Arrays.asList("OAuth realm=\"http://sp.example.com/\",\n"
                    + "                oauth_consumer_key=\"0685bd9184jfhq22\",\n"
                    + "                oauth_token=\"ad180jjd733klru7\",\n"
                    + "                oauth_signature_method=\"HMAC-SHA1\",\n"
                    + "                oauth_signature=\"wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D\",\n"
                    + "                oauth_timestamp=\"137131200\",\n"
                    + "                oauth_nonce=\"4572616e48616d6d65724c61686176\",\n"
                    + "                oauth_version=\"1.0\"")));

    Map<String, String> params = support.parseParameters(request);
    assertEquals("http://sp.example.com/", params.get("realm"));
    assertEquals("0685bd9184jfhq22", params.get(OAuthConsumerParameter.oauth_consumer_key.toString()));
    assertEquals("ad180jjd733klru7", params.get(OAuthConsumerParameter.oauth_token.toString()));
    assertEquals("HMAC-SHA1", params.get(OAuthConsumerParameter.oauth_signature_method.toString()));
    assertEquals("wOJIO9A2W5mFwDgiDvZbTSMK/PY=", params.get(OAuthConsumerParameter.oauth_signature.toString()));
    assertEquals("137131200", params.get(OAuthConsumerParameter.oauth_timestamp.toString()));
    assertEquals("4572616e48616d6d65724c61686176", params.get(OAuthConsumerParameter.oauth_nonce.toString()));
    assertEquals("1.0", params.get(OAuthConsumerParameter.oauth_version.toString()));
}

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.// w  w w.java 2s .c  om
 * @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.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.j a v a  2 s .c  o  m*/
 * @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 = getSignatureFactory()
            .getSignatureMethod(details.getSignatureMethod(), details.getSharedSecret(), tokenSecret);
    String signature = signatureMethod.sign(signatureBaseString);
    oauthParams.put(OAuthConsumerParameter.oauth_signature.toString(),
            Collections.singleton((CharSequence) signature));
    return oauthParams;
}

From source file:org.springframework.security.oauth.provider.CoreOAuthProviderSupport.java

/**
 * Loads the significant parameters (name-to-value map) that are to be used to calculate the signature base string.
 * The parameters will be encoded, per the spec section 9.1.
 *
 * @param request The request.//from   www .  ja  v a 2s. com
 * @return The significan parameters.
 */
protected SortedMap<String, SortedSet<String>> loadSignificantParametersForSignatureBaseString(
        HttpServletRequest request) {
    //first collect the relevant parameters...
    SortedMap<String, SortedSet<String>> significantParameters = new TreeMap<String, SortedSet<String>>();
    //first pull from the request...
    Enumeration parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String parameterName = (String) parameterNames.nextElement();
        String[] values = request.getParameterValues(parameterName);
        if (values == null) {
            values = new String[] { "" };
        }

        for (String parameterValue : values) {
            if (parameterValue == null) {
                parameterValue = "";
            }

            parameterName = oauthEncode(parameterName);
            parameterValue = oauthEncode(parameterValue);
            SortedSet<String> significantValues = significantParameters.get(parameterName);
            if (significantValues == null) {
                significantValues = new TreeSet<String>();
                significantParameters.put(parameterName, significantValues);
            }
            significantValues.add(parameterValue);
        }
    }

    //then take into account the header parameter values...
    Map<String, String> oauthParams = parseParameters(request);
    oauthParams.remove("realm"); //remove the realm
    Set<String> parsedParams = oauthParams.keySet();
    for (String parameterName : parsedParams) {
        String parameterValue = oauthParams.get(parameterName);
        if (parameterValue == null) {
            parameterValue = "";
        }

        parameterName = oauthEncode(parameterName);
        parameterValue = oauthEncode(parameterValue);
        SortedSet<String> significantValues = significantParameters.get(parameterName);
        if (significantValues == null) {
            significantValues = new TreeSet<String>();
            significantParameters.put(parameterName, significantValues);
        }
        significantValues.add(parameterValue);
    }

    //remove the oauth signature parameter value.
    significantParameters.remove(OAuthConsumerParameter.oauth_signature.toString());
    return significantParameters;
}

From source file:org.springframework.security.oauth.provider.filter.CoreOAuthProviderSupport.java

/**
 * Loads the significant parameters (name-to-value map) that are to be used to calculate the signature base string.
 * The parameters will be encoded, per the spec section 9.1.
 *
 * @param request The request./*from  w ww. jav a  2s .  co m*/
 * @return The significan parameters.
 */
protected SortedMap<String, SortedSet<String>> loadSignificantParametersForSignatureBaseString(
        HttpServletRequest request) {
    //first collect the relevant parameters...
    SortedMap<String, SortedSet<String>> significantParameters = new TreeMap<String, SortedSet<String>>();
    //first pull from the request...
    Enumeration parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String parameterName = (String) parameterNames.nextElement();
        String[] values = request.getParameterValues(parameterName);
        if (values == null) {
            values = new String[] { "" };
        }

        parameterName = oauthEncode(parameterName);
        for (String parameterValue : values) {
            if (parameterValue == null) {
                parameterValue = "";
            }

            parameterValue = oauthEncode(parameterValue);
            SortedSet<String> significantValues = significantParameters.get(parameterName);
            if (significantValues == null) {
                significantValues = new TreeSet<String>();
                significantParameters.put(parameterName, significantValues);
            }
            significantValues.add(parameterValue);
        }
    }

    //then take into account the header parameter values...
    Map<String, String> oauthParams = parseParameters(request);
    oauthParams.remove("realm"); //remove the realm
    Set<String> parsedParams = oauthParams.keySet();
    for (String parameterName : parsedParams) {
        String parameterValue = oauthParams.get(parameterName);
        if (parameterValue == null) {
            parameterValue = "";
        }

        parameterName = oauthEncode(parameterName);
        parameterValue = oauthEncode(parameterValue);
        SortedSet<String> significantValues = significantParameters.get(parameterName);
        if (significantValues == null) {
            significantValues = new TreeSet<String>();
            significantParameters.put(parameterName, significantValues);
        }
        significantValues.add(parameterValue);
    }

    //remove the oauth signature parameter value.
    significantParameters.remove(OAuthConsumerParameter.oauth_signature.toString());
    return significantParameters;
}

From source file:org.springframework.security.oauth.provider.filter.OAuthProviderProcessingFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    if (!skipProcessing(request)) {
        if (requiresAuthentication(request, response, chain)) {
            if (!allowMethod(request.getMethod().toUpperCase())) {
                if (log.isDebugEnabled()) {
                    log.debug("Method " + request.getMethod() + " not supported.");
                }//w  w w.ja v  a2  s  .  c  o  m

                response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                return;
            }

            try {
                Map<String, String> oauthParams = getProviderSupport().parseParameters(request);

                if (parametersAreAdequate(oauthParams)) {

                    if (log.isDebugEnabled()) {
                        StringBuilder builder = new StringBuilder("OAuth parameters parsed: ");
                        for (String param : oauthParams.keySet()) {
                            builder.append(param).append('=').append(oauthParams.get(param)).append(' ');
                        }
                        log.debug(builder.toString());
                    }

                    String consumerKey = oauthParams.get(OAuthConsumerParameter.oauth_consumer_key.toString());
                    if (consumerKey == null) {
                        throw new InvalidOAuthParametersException(messages.getMessage(
                                "OAuthProcessingFilter.missingConsumerKey", "Missing consumer key."));
                    }

                    //load the consumer details.
                    ConsumerDetails consumerDetails = getConsumerDetailsService()
                            .loadConsumerByConsumerKey(consumerKey);
                    if (log.isDebugEnabled()) {
                        log.debug("Consumer details loaded for " + consumerKey + ": " + consumerDetails);
                    }

                    //validate the parameters for the consumer.
                    validateOAuthParams(consumerDetails, oauthParams);
                    if (log.isDebugEnabled()) {
                        log.debug("Parameters validated.");
                    }

                    //extract the credentials.
                    String token = oauthParams.get(OAuthConsumerParameter.oauth_token.toString());
                    String signatureMethod = oauthParams
                            .get(OAuthConsumerParameter.oauth_signature_method.toString());
                    String signature = oauthParams.get(OAuthConsumerParameter.oauth_signature.toString());
                    String signatureBaseString = getProviderSupport().getSignatureBaseString(request);
                    ConsumerCredentials credentials = new ConsumerCredentials(consumerKey, signature,
                            signatureMethod, signatureBaseString, token);

                    //create an authentication request.
                    ConsumerAuthentication authentication = new ConsumerAuthentication(consumerDetails,
                            credentials, oauthParams);
                    authentication.setDetails(createDetails(request, consumerDetails));

                    Authentication previousAuthentication = SecurityContextHolder.getContext()
                            .getAuthentication();
                    try {
                        //set the authentication request (unauthenticated) into the context.
                        SecurityContextHolder.getContext().setAuthentication(authentication);

                        //validate the signature.
                        validateSignature(authentication);

                        //mark the authentication request as validated.
                        authentication.setSignatureValidated(true);

                        //mark that processing has been handled.
                        request.setAttribute(OAUTH_PROCESSING_HANDLED, Boolean.TRUE);

                        if (log.isDebugEnabled()) {
                            log.debug("Signature validated.");
                        }

                        //go.
                        onValidSignature(request, response, chain);
                    } finally {
                        //clear out the consumer authentication to make sure it doesn't get cached.
                        resetPreviousAuthentication(previousAuthentication);
                    }
                } else if (!isIgnoreInadequateCredentials()) {
                    throw new InvalidOAuthParametersException(
                            messages.getMessage("OAuthProcessingFilter.missingCredentials",
                                    "Inadequate OAuth consumer credentials."));
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Supplied OAuth parameters are inadequate. Ignoring.");
                    }
                    chain.doFilter(request, response);
                }
            } catch (AuthenticationException ae) {
                fail(request, response, ae);
            } catch (ServletException e) {
                if (e.getRootCause() instanceof AuthenticationException) {
                    fail(request, response, (AuthenticationException) e.getRootCause());
                } else {
                    throw e;
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Request does not require authentication.  OAuth processing skipped.");
            }

            chain.doFilter(servletRequest, servletResponse);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Processing explicitly skipped.");
        }

        chain.doFilter(servletRequest, servletResponse);
    }
}

From source file:org.springframework.security.oauth.provider.filter.OAuthProviderProcessingFilter.java

/**
 * Validates the OAuth parameters for the given consumer. Base implementation validates only those parameters
 * that are required for all OAuth requests. This includes the nonce and timestamp, but not the signature.
 *
 * @param consumerDetails The consumer details.
 * @param oauthParams     The OAuth parameters to validate.
 * @throws InvalidOAuthParametersException If the OAuth parameters are invalid.
 *///  ww w . j  av a  2 s . c o m
protected void validateOAuthParams(ConsumerDetails consumerDetails, Map<String, String> oauthParams)
        throws InvalidOAuthParametersException {
    String version = oauthParams.get(OAuthConsumerParameter.oauth_version.toString());
    if ((version != null) && (!"1.0".equals(version))) {
        throw new OAuthVersionUnsupportedException("Unsupported OAuth version: " + version);
    }

    String realm = oauthParams.get("realm");
    realm = realm == null || "".equals(realm) ? null : realm;
    if ((realm != null) && (!realm.equals(this.authenticationEntryPoint.getRealmName()))) {
        throw new InvalidOAuthParametersException(messages.getMessage("OAuthProcessingFilter.incorrectRealm",
                new Object[] { realm, this.getAuthenticationEntryPoint().getRealmName() },
                "Response realm name '{0}' does not match system realm name of '{1}'"));
    }

    String signatureMethod = oauthParams.get(OAuthConsumerParameter.oauth_signature_method.toString());
    if (signatureMethod == null) {
        throw new InvalidOAuthParametersException(messages
                .getMessage("OAuthProcessingFilter.missingSignatureMethod", "Missing signature method."));
    }

    String signature = oauthParams.get(OAuthConsumerParameter.oauth_signature.toString());
    if (signature == null) {
        throw new InvalidOAuthParametersException(
                messages.getMessage("OAuthProcessingFilter.missingSignature", "Missing signature."));
    }

    String timestamp = oauthParams.get(OAuthConsumerParameter.oauth_timestamp.toString());
    if (timestamp == null) {
        throw new InvalidOAuthParametersException(
                messages.getMessage("OAuthProcessingFilter.missingTimestamp", "Missing timestamp."));
    }

    String nonce = oauthParams.get(OAuthConsumerParameter.oauth_nonce.toString());
    if (nonce == null) {
        throw new InvalidOAuthParametersException(
                messages.getMessage("OAuthProcessingFilter.missingNonce", "Missing nonce."));
    }

    try {
        getNonceServices().validateNonce(consumerDetails, Long.parseLong(timestamp), nonce);
    } catch (NumberFormatException e) {
        throw new InvalidOAuthParametersException(messages.getMessage("OAuthProcessingFilter.invalidTimestamp",
                new Object[] { timestamp }, "Timestamp must be a positive integer. Invalid value: {0}"));
    }

    validateAdditionalParameters(consumerDetails, oauthParams);
}