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

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

Introduction

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

Prototype

OAuthConsumerParameter oauth_signature_method

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

Click Source Link

Document

Parameter for the signature method.

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.jasig.ssp.util.security.lti.LtiLaunchErrorHandler.java

private ErrorResponse buildLaunchErrorResponse(HttpServletRequest request, HttpServletResponse response,
        Exception launchError) {/*from   w ww.j av a  2s .com*/
    final UUID errorId = UUID.randomUUID();
    final ErrorResponse errResponse = new ErrorResponse(errorId, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
            launchError);

    if (launchError instanceof UserNotEnabledException) {
        // This means the launching user's account just couldn't be found.
        // This is as opposed to some other system-level error either
        // in the OAuth infrastructure (including signature validation failures)
        // or in the calls to Platform
        errResponse.statusCode = HttpServletResponse.SC_FORBIDDEN;
        errResponse.endUserMessage = endUserErrorMessageWithId("Your user account was not found.", errorId);
        errResponse.loggableMessage = loggableErrorMessageWithId("User account not found in Platform.",
                errorId);
    } else if (launchError instanceof ConsumerDetailsNotFoundException) {
        // The LtiConsumer record couldn't be found *during OAuth validation*
        // This is as opposed to that record going missing during downstream
        // processing, which is represented by UserNotAuthorizedException (below)
        errResponse.statusCode = HttpServletResponse.SC_FORBIDDEN;
        errResponse.endUserMessage = endUserErrorMessageWithId("Could not authenticate this launch request. "
                + "This is likely a configuration problem that will require your system administrator's attention.",
                errorId);
        errResponse.loggableMessage = loggableErrorMessageWithId(
                "LTI Consumer record could not be found during the launch request's OAuth validation step.",
                errorId);
    } else if (launchError instanceof ConsumerDetailsDisabledException) {
        // The LtiConsumer record was found during OAuth validation but was
        // disabled in one way or another.
        errResponse.statusCode = HttpServletResponse.SC_FORBIDDEN;
        errResponse.endUserMessage = endUserErrorMessageWithId("Could not authenticate this launch request. "
                + "This is likely a configuration problem that will require your system administrator's attention.",
                errorId);
        errResponse.loggableMessage = loggableErrorMessageWithId(
                "LTI Consumer record is disabled - usually because of a soft-deletion or a deleted secret.",
                errorId);
    } else if (launchError instanceof UserNotAuthorizedException) {
        // This means there was some sort of infrastructural problem with the
        // LTI authentication context - either the LTI consumer was not
        // set properly into the context after validation or there was some concurrent
        // modification to that consumer record which is now wreaking havoc.
        // Chances are, it was a server-side problem sp we leave the 500-series
        // status code alone
        errResponse.endUserMessage = endUserErrorMessageWithId("Could not authenticate this launch request. "
                + "This is likely a configuration problem that will require your system administrator's attention.",
                errorId);
        errResponse.loggableMessage = loggableErrorMessageWithId(
                "Authentication context became invalid downstream from OAuth validation.", errorId);
    } else if (launchError instanceof PersonAttributesSearchException) {
        // This means there was a system-level faulure looking up the end
        // user in Platform. Not that the user doesn't exist - that there
        // was a technical issue with the lookup itself. This is fundamentally
        // a server-side problem so we leave the 500-series status code alone.
        errResponse.endUserMessage = endUserErrorMessageWithId(
                "Encountered technical difficulties looking up your user account. "
                        + "This is likely a configuration problem that will require your system administrator's attention.",
                errorId);
        errResponse.loggableMessage = loggableErrorMessageWithId(
                "System failure trying to look up launching user account in Platform.", errorId);
    } else if (launchError instanceof AuthenticationException) {
        // OAuthException sometimes just wraps AuthenticationServiceException, which means
        // it should be a 500-series. Else an OAuth failure would always be a 400 series
        if (launchError instanceof AuthenticationServiceException
                || launchError.getCause() instanceof AuthenticationServiceException) {
            errResponse.endUserMessage = endUserErrorMessageWithId(
                    "Encountered technical difficulties validating this request. "
                            + "This is likely a configuration problem that will require your system administrator's attention.",
                    errorId);
            errResponse.loggableMessage = loggableErrorMessageWithId(
                    "System failure trying to validate OAuth parameters.", errorId);
        } else if (launchError instanceof InvalidOAuthParametersException) { // special case called out in spec
            errResponse.statusCode = HttpServletResponse.SC_BAD_REQUEST;
            errResponse.endUserMessage = endUserErrorMessageWithId(
                    "Encountered technical difficulties validating this request. "
                            + "This is likely a configuration problem that will require your system administrator's attention.",
                    errorId);
            errResponse.loggableMessage = loggableErrorMessageWithId(
                    "Request was missing OAuth parameters or OAuth parameters were malformed.", errorId);
        } else if (launchError.getCause() instanceof UnsupportedSignatureMethodException) { // special case called out in spec
            errResponse.statusCode = HttpServletResponse.SC_BAD_REQUEST;
            errResponse.endUserMessage = endUserErrorMessageWithId(
                    "Encountered technical difficulties validating this request. "
                            + "This is likely a configuration problem that will require your system administrator's attention.",
                    errorId);
            final String sigMethod = request
                    .getParameter(OAuthConsumerParameter.oauth_signature_method.toString());
            errResponse.loggableMessage = loggableErrorMessageWithId(
                    "Requested OAuth signature method [" + sigMethod + "] is not supported.", errorId);
        } else {
            errResponse.statusCode = HttpServletResponse.SC_FORBIDDEN;
            errResponse.endUserMessage = endUserErrorMessageWithId(
                    "Could not authenticate this launch request. "
                            + "This is likely a configuration problem that will require your system administrator's attention.",
                    errorId);
            errResponse.loggableMessage = loggableErrorMessageWithId(
                    "OAuth request did not validate. This is usually a violation of signature validation rules.",
                    errorId);
        }
    } else {
        errResponse.endUserMessage = endUserErrorMessageWithId(
                "Encountered technical difficulties handling this launch request. "
                        + "This is likely a configuration problem that will require your system administrator's attention.",
                errorId);
        errResponse.loggableMessage = loggableErrorMessageWithId("Generic system failure.", errorId);
    }
    return errResponse;
}

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.//from   w w  w  .  j  a va2  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;
    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./* w  ww.ja  va  2s .  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.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.");
                }/*from  w ww. j a v a 2 s  .  com*/

                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.ja v a  2s.  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);
}