net.oauth.OAuthException Java Examples

The following examples show how to use net.oauth.OAuthException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OAuthSignatureMethod.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check whether the message has a valid signature.
 * @throws URISyntaxException 
 *
 * @throws OAuthProblemException
 *             the signature is invalid
 */
public void validate(OAuthMessage message)
throws IOException, OAuthException, URISyntaxException {
    message.requireParameters("oauth_signature");
    String signature = message.getSignature();
    String baseString = getBaseString(message);
    if (!isValid(signature, baseString)) {

 // *LAMS* added by LAMS
 log.debug("Error. Signature invalid. oauth_signature=" + signature + ", oauth_signature_base_string="
  + baseString + ", oauth_signature_method=" + message.getSignatureMethod());
     		
        OAuthProblemException problem = new OAuthProblemException(
                "signature_invalid");
        problem.setParameter("oauth_signature", signature);
        problem.setParameter("oauth_signature_base_string", baseString);
        problem.setParameter("oauth_signature_method", message
                .getSignatureMethod());
        throw problem;
    }
}
 
Example #2
Source File: OAuthSignatureMethod.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected void initialize(String name, OAuthAccessor accessor)
        throws OAuthException {
    String secret = accessor.consumer.consumerSecret;
    if (name.endsWith(_ACCESSOR)) {
        // This code supports the 'Accessor Secret' extensions
        // described in http://oauth.pbwiki.com/AccessorSecret
        final String key = OAuthConsumer.ACCESSOR_SECRET;
        Object accessorSecret = accessor.getProperty(key);
        if (accessorSecret == null) {
            accessorSecret = accessor.consumer.getProperty(key);
        }
        if (accessorSecret != null) {
            secret = accessorSecret.toString();
        }
    }
    if (secret == null) {
        secret = "";
    }
    setConsumerSecret(secret);
}
 
Example #3
Source File: LtiOauthSigner.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Map<String, String> signParameters(Map<String, String> parameters, String key, String secret, String url, String method) throws LtiSigningException {
    OAuthMessage oam = new OAuthMessage(method, url, parameters.entrySet());
    OAuthConsumer cons = new OAuthConsumer(null, key, secret, null);
    OAuthAccessor acc = new OAuthAccessor(cons);
    try {
        oam.addRequiredParameters(acc);

        Map<String, String> signedParameters = new HashMap<>();
        for(Map.Entry<String, String> param : oam.getParameters()){
            signedParameters.put(param.getKey(), param.getValue());
        }
        return signedParameters;
    } catch (OAuthException |IOException |URISyntaxException e) {
        throw new LtiSigningException("Error signing LTI request.", e);
    }
}
 
Example #4
Source File: OAuthSignatureMethod.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected void initialize(String name, OAuthAccessor accessor)
        throws OAuthException {
    String secret = accessor.consumer.consumerSecret;
    if (name.endsWith(_ACCESSOR)) {
        // This code supports the 'Accessor Secret' extensions
        // described in http://oauth.pbwiki.com/AccessorSecret
        final String key = OAuthConsumer.ACCESSOR_SECRET;
        Object accessorSecret = accessor.getProperty(key);
        if (accessorSecret == null) {
            accessorSecret = accessor.consumer.getProperty(key);
        }
        if (accessorSecret != null) {
            secret = accessorSecret.toString();
        }
    }
    if (secret == null) {
        secret = "";
    }
    setConsumerSecret(secret);
}
 
Example #5
Source File: OAuthSignatureMethod.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected void initialize(String name, OAuthAccessor accessor)
        throws OAuthException {
    String secret = accessor.consumer.consumerSecret;
    if (name.endsWith(_ACCESSOR)) {
        // This code supports the 'Accessor Secret' extensions
        // described in http://oauth.pbwiki.com/AccessorSecret
        final String key = OAuthConsumer.ACCESSOR_SECRET;
        Object accessorSecret = accessor.getProperty(key);
        if (accessorSecret == null) {
            accessorSecret = accessor.consumer.getProperty(key);
        }
        if (accessorSecret != null) {
            secret = accessorSecret.toString();
        }
    }
    if (secret == null) {
        secret = "";
    }
    setConsumerSecret(secret);
}
 
Example #6
Source File: OAuthClient.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
    * Get an access token from the service provider, in exchange for an
    * authorized request token.
    * 
    * @param accessor
    *            should contain a non-null requestToken and tokenSecret, and a
    *            consumer that contains a consumerKey and consumerSecret. Also,
    *            accessor.consumer.serviceProvider.accessTokenURL should be the
    *            URL (determined by the service provider) for getting an access
    *            token.
    * @param httpMethod
    *            typically OAuthMessage.POST or OAuthMessage.GET, or null to
    *            use the default method.
    * @param parameters
    *            additional parameters for this request, or null to indicate
    *            that there are no additional parameters.
    * @throws OAuthProblemException
    *             the HTTP response status code was not 200 (OK)
    */
   @SuppressWarnings("rawtypes")
public OAuthMessage getAccessToken(OAuthAccessor accessor, String httpMethod,
           Collection<? extends Map.Entry> parameters) throws IOException, OAuthException, URISyntaxException {
       if (accessor.requestToken != null) {
           if (parameters == null) {
               parameters = OAuth.newList(OAuth.OAUTH_TOKEN, accessor.requestToken);
           } else if (!OAuth.newMap(parameters).containsKey(OAuth.OAUTH_TOKEN)) {
               List<Map.Entry> p = new ArrayList<Map.Entry>(parameters);
               p.add(new OAuth.Parameter(OAuth.OAUTH_TOKEN, accessor.requestToken));
               parameters = p;
           }
       }
       OAuthMessage response = invoke(accessor, httpMethod,
               accessor.consumer.serviceProvider.accessTokenURL, parameters);
       response.requireParameters(OAuth.OAUTH_TOKEN, OAuth.OAUTH_TOKEN_SECRET);
       accessor.accessToken = response.getParameter(OAuth.OAUTH_TOKEN);
       accessor.tokenSecret = response.getParameter(OAuth.OAUTH_TOKEN_SECRET);
       return response;
   }
 
Example #7
Source File: LtiOauthSigner.java    From basiclti-util-java with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> signParameters(Map<String, String> parameters, String key, String secret, String url, String method) throws LtiSigningException {
    OAuthMessage oam = new OAuthMessage(method, url, parameters.entrySet());
    OAuthConsumer cons = new OAuthConsumer(null, key, secret, null);
    OAuthAccessor acc = new OAuthAccessor(cons);
    try {
        oam.addRequiredParameters(acc);

        Map<String, String> signedParameters = new HashMap<>();
        for(Map.Entry<String, String> param : oam.getParameters()){
            signedParameters.put(param.getKey(), param.getValue());
        }
        return signedParameters;
    } catch (OAuthException |IOException |URISyntaxException e) {
        throw new LtiSigningException("Error signing LTI request.", e);
    }
}
 
Example #8
Source File: OAuthClient.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
    * Get an access token from the service provider, in exchange for an
    * authorized request token.
    * 
    * @param accessor
    *            should contain a non-null requestToken and tokenSecret, and a
    *            consumer that contains a consumerKey and consumerSecret. Also,
    *            accessor.consumer.serviceProvider.accessTokenURL should be the
    *            URL (determined by the service provider) for getting an access
    *            token.
    * @param httpMethod
    *            typically OAuthMessage.POST or OAuthMessage.GET, or null to
    *            use the default method.
    * @param parameters
    *            additional parameters for this request, or null to indicate
    *            that there are no additional parameters.
    * @throws OAuthProblemException
    *             the HTTP response status code was not 200 (OK)
    */
   @SuppressWarnings("rawtypes")
public OAuthMessage getAccessToken(OAuthAccessor accessor, String httpMethod,
           Collection<? extends Map.Entry> parameters) throws IOException, OAuthException, URISyntaxException {
       if (accessor.requestToken != null) {
           if (parameters == null) {
               parameters = OAuth.newList(OAuth.OAUTH_TOKEN, accessor.requestToken);
           } else if (!OAuth.newMap(parameters).containsKey(OAuth.OAUTH_TOKEN)) {
               List<Map.Entry> p = new ArrayList<Map.Entry>(parameters);
               p.add(new OAuth.Parameter(OAuth.OAUTH_TOKEN, accessor.requestToken));
               parameters = p;
           }
       }
       OAuthMessage response = invoke(accessor, httpMethod,
               accessor.consumer.serviceProvider.accessTokenURL, parameters);
       response.requireParameters(OAuth.OAUTH_TOKEN, OAuth.OAUTH_TOKEN_SECRET);
       accessor.accessToken = response.getParameter(OAuth.OAUTH_TOKEN);
       accessor.tokenSecret = response.getParameter(OAuth.OAUTH_TOKEN_SECRET);
       return response;
   }
 
Example #9
Source File: WaveService.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a URL that contains the necessary OAuth query parameters for the
 * given JSON string.
 *
 * The required OAuth parameters are:
 * <ul>
 * <li>oauth_body_hash</li>
 * <li>oauth_consumer_key</li>
 * <li>oauth_signature_method</li>
 * <li>oauth_timestamp</li>
 * <li>oauth_nonce</li>
 * <li>oauth_version</li>
 * <li>oauth_signature</li>
 * </ul>
 *
 * @param jsonBody the JSON string to construct the URL from.
 * @param rpcServerUrl the URL of the handler that services the JSON-RPC
 *        request.
 * @param accessor the OAuth accessor used to create the signed string.
 * @return a URL for the given JSON string, and the required OAuth parameters.
 */
public static String createOAuthUrlString(
    String jsonBody, String rpcServerUrl, OAuthAccessor accessor)
    throws IOException, URISyntaxException, OAuthException {
  OAuthMessage message =
      new OAuthMessage(POST, rpcServerUrl, Collections.<SimpleEntry<String, String>>emptyList());

  // Compute the hash of the body.
  byte[] rawBody = jsonBody.getBytes(UTF_8);
  byte[] hash = DigestUtils.sha(rawBody);
  byte[] encodedHash = Base64.encodeBase64(hash);
  message.addParameter(OAUTH_BODY_HASH, new String(encodedHash, UTF_8));

  // Add other parameters.

  message.addRequiredParameters(accessor);
  if (LOG.isLoggable(Level.FINE)) {
    LOG.fine("Signature base string: " + OAuthSignatureMethod.getBaseString(message));
  }

  // Construct the resulting URL.
  StringBuilder sb = new StringBuilder(rpcServerUrl);
  char connector = '?';
  for (Map.Entry<String, String> p : message.getParameters()) {
    if (!p.getKey().equals(jsonBody)) {
      sb.append(connector);
      sb.append(URLEncoder.encode(p.getKey(), UTF_8));
      sb.append('=');
      sb.append(URLEncoder.encode(p.getValue(), UTF_8));
      connector = '&';
    }
  }
  return sb.toString();
}
 
Example #10
Source File: DataApiOAuthServletTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
public void testDoExchangeTokenUnauthorizedOnOAuthException() throws Exception {
  when(req.getPathInfo()).thenReturn(ACCESS_TOKEN_PATH);
  when(req.getMethod()).thenReturn("GET");

  Map<String, String[]> params = getDoExchangeTokenParams();
  when(req.getParameterMap()).thenReturn(params);

  doThrow(new OAuthException("")).when(validator).validateMessage(
      any(OAuthMessage.class), any(OAuthAccessor.class));

  servlet.doGet(req, resp);

  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  verify(resp).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #11
Source File: AbstractRobot.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Deserializes the given HTTP request's JSON body into an event message
 * bundle.
 *
 * @param req the HTTP request to be deserialized.
 * @return an event message bundle.
 *
 * @throws IOException if there is a problem reading the request's body.
 * @throws IllegalArgumentException if the request is not signed properly.
 */
private EventMessageBundle deserializeEvents(HttpServletRequest req) throws IOException {
  String json = readRequestBody(req);
  LOG.info("Incoming events: " + json);

  EventMessageBundle bundle = SERIALIZER.fromJson(json, EventMessageBundle.class);

  if (bundle.getRpcServerUrl() == null) {
    throw new IllegalArgumentException("RPC server URL is not set in the event bundle.");
  }

  if (!isUnsignedRequestsAllowed()) {
    if (!waveService.hasConsumerData(bundle.getRpcServerUrl())) {
      throw new IllegalArgumentException("No consumer key is found for the RPC server URL: " +
          bundle.getRpcServerUrl());
    }

    // Validates the request.
    try {
      @SuppressWarnings("unchecked")
      Map<String, String[]> parameterMap = req.getParameterMap();
      waveService.validateOAuthRequest(req.getRequestURL().toString(), parameterMap,
          json, bundle.getRpcServerUrl());
    } catch (OAuthException e) {
      throw new IllegalArgumentException("Error validating OAuth request", e);
    }
  }
  return bundle;
}
 
Example #12
Source File: ActiveApiServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testDoPostUnauthorizedWhenValidationFails() throws Exception {
  when(req.getHeaders("Authorization")).thenReturn(
      convertRawEnumerationToGeneric(generateOAuthHeader(ROBOT.getAddress())));
  doThrow(new OAuthException("")).when(validator).validateMessage(
      any(OAuthMessage.class), any(OAuthAccessor.class));

  servlet.doPost(req, resp);

  verify(resp).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #13
Source File: DataApiServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testDoPostUnauthorizedWhenValidationFails() throws Exception {
  doThrow(new OAuthException("")).when(validator).validateMessage(
      any(OAuthMessage.class), any(OAuthAccessor.class));
  Map<String, String[]> params = getOAuthParams();
  when(req.getParameterMap()).thenReturn(params);

  servlet.doPost(req, resp);

  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  verify(resp).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #14
Source File: DataApiOAuthServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testDoRequestTokenUnauthorizedOnOAuthException() throws Exception {
  when(req.getPathInfo()).thenReturn(REQUEST_TOKEN_PATH);
  when(req.getMethod()).thenReturn("GET");

  doThrow(new OAuthException("")).when(validator).validateMessage(
      any(OAuthMessage.class), any(OAuthAccessor.class));

  servlet.doGet(req, resp);

  verify(resp).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #15
Source File: DataApiOAuthServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testDoExchangeTokenUnauthorizedOnOAuthException() throws Exception {
  when(req.getPathInfo()).thenReturn(ACCESS_TOKEN_PATH);
  when(req.getMethod()).thenReturn("GET");

  Map<String, String[]> params = getDoExchangeTokenParams();
  when(req.getParameterMap()).thenReturn(params);

  doThrow(new OAuthException("")).when(validator).validateMessage(
      any(OAuthMessage.class), any(OAuthAccessor.class));

  servlet.doGet(req, resp);

  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  verify(resp).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #16
Source File: BasicLTIUtilTest.java    From basiclti-util-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateMessageFailOnValidateMessageOAuthException() throws Exception {

    SimpleOAuthValidator sov = Mockito.mock(SimpleOAuthValidator.class);
    PowerMockito.whenNew(SimpleOAuthValidator.class).withNoArguments().thenReturn(sov);
    Mockito.doThrow(new OAuthException("failed")).when(sov).validateMessage(Matchers.any(OAuthMessage.class), Matchers.any(OAuthAccessor.class));
    PowerMockito.mockStatic(OAuthSignatureMethod.class);
    PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenReturn("");

    LtiVerificationResult result = BasicLTIUtil.validateMessage(Mockito.mock(HttpServletRequest.class), "https://example.com/lti-launch", "secret");

    Assert.assertEquals(LtiError.BAD_REQUEST, result.getError());
    Assert.assertEquals(Boolean.FALSE, result.getSuccess());
    Assert.assertEquals(null, result.getLtiLaunchResult());
}
 
Example #17
Source File: OAuthClient.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/** Get a fresh request token from the service provider.
    * 
    * @param accessor
    *            should contain a consumer that contains a non-null consumerKey
    *            and consumerSecret. Also,
    *            accessor.consumer.serviceProvider.requestTokenURL should be
    *            the URL (determined by the service provider) for getting a
    *            request token.
    * @param httpMethod
    *            typically OAuthMessage.POST or OAuthMessage.GET, or null to
    *            use the default method.
    * @param parameters
    *            additional parameters for this request, or null to indicate
    *            that there are no additional parameters.
    * @throws OAuthProblemException
    *             the HTTP response status code was not 200 (OK)
    */
   @SuppressWarnings("rawtypes")
public void getRequestToken(OAuthAccessor accessor, String httpMethod,
           Collection<? extends Map.Entry> parameters) throws IOException,
           OAuthException, URISyntaxException {
       accessor.accessToken = null;
       accessor.tokenSecret = null;
       {
           // This code supports the 'Variable Accessor Secret' extension
           // described in http://oauth.pbwiki.com/AccessorSecret
           Object accessorSecret = accessor
                   .getProperty(OAuthConsumer.ACCESSOR_SECRET);
           if (accessorSecret != null) {
               List<Map.Entry> p = (parameters == null) ? new ArrayList<Map.Entry>(
                       1)
                       : new ArrayList<Map.Entry>(parameters);
               p.add(new OAuth.Parameter("oauth_accessor_secret",
                       accessorSecret.toString()));
               parameters = p;
               // But don't modify the caller's parameters.
           }
       }
       OAuthMessage response = invoke(accessor, httpMethod,
               accessor.consumer.serviceProvider.requestTokenURL, parameters);
       accessor.requestToken = response.getParameter(OAuth.OAUTH_TOKEN);
       accessor.tokenSecret = response.getParameter(OAuth.OAUTH_TOKEN_SECRET);
       response.requireParameters(OAuth.OAUTH_TOKEN, OAuth.OAUTH_TOKEN_SECRET);
   }
 
Example #18
Source File: OAuthClient.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
    * Construct a request message, send it to the service provider and get the
    * response.
    * 
    * @param httpMethod
    *            the HTTP request method, or null to use the default method
    * @return the response
    * @throws URISyntaxException
    *             the given url isn't valid syntactically
    * @throws OAuthProblemException
    *             the HTTP response status code was not 200 (OK)
    */
   @SuppressWarnings("rawtypes")
public OAuthMessage invoke(OAuthAccessor accessor, String httpMethod,
           String url, Collection<? extends Map.Entry> parameters)
   throws IOException, OAuthException, URISyntaxException {
       OAuthMessage request = accessor.newRequestMessage(httpMethod, url, parameters);
       Object accepted = accessor.consumer.getProperty(OAuthConsumer.ACCEPT_ENCODING);
       if (accepted != null) {
           request.getHeaders().add(new OAuth.Parameter(HttpMessage.ACCEPT_ENCODING, accepted.toString()));
       }
       Object ps = accessor.consumer.getProperty(PARAMETER_STYLE);
       net.oauth.ParameterStyle style = (ps == null) ? net.oauth.ParameterStyle.BODY
               : Enum.valueOf(net.oauth.ParameterStyle.class, ps.toString());
       return invoke(request, style);
   }
 
Example #19
Source File: OAuthSignatureMethod.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
    * Check whether the message has a valid signature.
    * @throws URISyntaxException 
    *
    * @throws OAuthProblemException
    *             the signature is invalid
    */
   public void validate(OAuthMessage message)
   throws IOException, OAuthException, URISyntaxException {
       message.requireParameters("oauth_signature");
       String signature = message.getSignature();
       String baseString = getBaseString(message);
       String otherBaseString = null;

// Allow for some confusion coming through load balancers
if ( baseString.startsWith(POST_HTTP) ) { 
	otherBaseString = baseString.replaceFirst("^"+POST_HTTP,POST_SECURE);
} else if ( baseString.startsWith(POST_SECURE) ) { 
	otherBaseString = baseString.replaceFirst("^"+POST_SECURE, POST_HTTP);
} else if ( baseString.startsWith(GET_HTTP) ) { 
	otherBaseString = baseString.replaceFirst("^"+GET_HTTP,GET_SECURE);
} else if ( baseString.startsWith(GET_SECURE) ) { 
	otherBaseString = baseString.replaceFirst("^"+GET_SECURE, GET_HTTP);
}

boolean valid = isValid(signature, baseString);
if ( ! valid && otherBaseString != null ) valid = isValid(signature, otherBaseString);

       if (!valid) {
           OAuthProblemException problem = new OAuthProblemException(
                   "signature_invalid");
           problem.setParameter("oauth_signature", signature);
           problem.setParameter("oauth_signature_base_string", baseString);
           problem.setParameter("oauth_signature_method", message
                   .getSignatureMethod());
           throw problem;
       }
   }
 
Example #20
Source File: OAuthSignatureMethod.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static OAuthSignatureMethod newSigner(OAuthMessage message,
        OAuthAccessor accessor) throws IOException, OAuthException {
    message.requireParameters(OAuth.OAUTH_SIGNATURE_METHOD);
    OAuthSignatureMethod signer = newMethod(message.getSignatureMethod(),
            accessor);
    signer.setTokenSecret(accessor.tokenSecret);
    return signer;
}
 
Example #21
Source File: OAuthHttpServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private static OAuthException convertException(org.sakaiproject.oauth.exception.OAuthException originalException) {
    if (originalException instanceof InvalidConsumerException)
        return new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN);
    else if (originalException instanceof ExpiredAccessorException)
        return new OAuthProblemException(OAuth.Problems.TOKEN_EXPIRED);
    else if (originalException instanceof RevokedAccessorException)
        return new OAuthProblemException(OAuth.Problems.TOKEN_REVOKED);
    else if (originalException instanceof InvalidAccessorException)
        return new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
    else if (originalException instanceof InvalidVerifierException)
        return new OAuthProblemException(OAuth.Problems.PARAMETER_REJECTED);
    else
        return new OAuthProblemException();
}
 
Example #22
Source File: WaveService.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a URL that contains the necessary OAuth query parameters for the
 * given JSON string.
 *
 * The required OAuth parameters are:
 * <ul>
 * <li>oauth_body_hash</li>
 * <li>oauth_consumer_key</li>
 * <li>oauth_signature_method</li>
 * <li>oauth_timestamp</li>
 * <li>oauth_nonce</li>
 * <li>oauth_version</li>
 * <li>oauth_signature</li>
 * </ul>
 *
 * @param jsonBody the JSON string to construct the URL from.
 * @param rpcServerUrl the URL of the handler that services the JSON-RPC
 *        request.
 * @param accessor the OAuth accessor used to create the signed string.
 * @return a URL for the given JSON string, and the required OAuth parameters.
 */
public static String createOAuthUrlString(
    String jsonBody, String rpcServerUrl, OAuthAccessor accessor)
    throws IOException, URISyntaxException, OAuthException {
  OAuthMessage message =
      new OAuthMessage(POST, rpcServerUrl, Collections.<SimpleEntry<String, String>>emptyList());

  // Compute the hash of the body.
  byte[] rawBody = jsonBody.getBytes(UTF_8);
  byte[] hash = DigestUtils.sha(rawBody);
  byte[] encodedHash = Base64.encodeBase64(hash);
  message.addParameter(OAUTH_BODY_HASH, new String(encodedHash, UTF_8));

  // Add other parameters.

  message.addRequiredParameters(accessor);
  if (LOG.isLoggable(Level.FINE)) {
    LOG.fine("Signature base string: " + OAuthSignatureMethod.getBaseString(message));
  }

  // Construct the resulting URL.
  StringBuilder sb = new StringBuilder(rpcServerUrl);
  char connector = '?';
  for (Map.Entry<String, String> p : message.getParameters()) {
    if (!p.getKey().equals(jsonBody)) {
      sb.append(connector);
      sb.append(URLEncoder.encode(p.getKey(), UTF_8));
      sb.append('=');
      sb.append(URLEncoder.encode(p.getValue(), UTF_8));
      connector = '&';
    }
  }
  return sb.toString();
}
 
Example #23
Source File: AbstractRobot.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Deserializes the given HTTP request's JSON body into an event message
 * bundle.
 *
 * @param req the HTTP request to be deserialized.
 * @return an event message bundle.
 *
 * @throws IOException if there is a problem reading the request's body.
 * @throws IllegalArgumentException if the request is not signed properly.
 */
private EventMessageBundle deserializeEvents(HttpServletRequest req) throws IOException {
  String json = readRequestBody(req);
  LOG.info("Incoming events: " + json);

  EventMessageBundle bundle = SERIALIZER.fromJson(json, EventMessageBundle.class);

  if (bundle.getRpcServerUrl() == null) {
    throw new IllegalArgumentException("RPC server URL is not set in the event bundle.");
  }

  if (!isUnsignedRequestsAllowed()) {
    if (!waveService.hasConsumerData(bundle.getRpcServerUrl())) {
      throw new IllegalArgumentException("No consumer key is found for the RPC server URL: " +
          bundle.getRpcServerUrl());
    }

    // Validates the request.
    try {
      @SuppressWarnings("unchecked")
      Map<String, String[]> parameterMap = req.getParameterMap();
      waveService.validateOAuthRequest(req.getRequestURL().toString(), parameterMap,
          json, bundle.getRpcServerUrl());
    } catch (OAuthException e) {
      throw new IllegalArgumentException("Error validating OAuth request", e);
    }
  }
  return bundle;
}
 
Example #24
Source File: ActiveApiServletTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
public void testDoPostUnauthorizedWhenValidationFails() throws Exception {
  when(req.getHeaders("Authorization")).thenReturn(
      convertRawEnumerationToGeneric(generateOAuthHeader(ROBOT.getAddress())));
  doThrow(new OAuthException("")).when(validator).validateMessage(
      any(OAuthMessage.class), any(OAuthAccessor.class));

  servlet.doPost(req, resp);

  verify(resp).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #25
Source File: DataApiServletTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
public void testDoPostUnauthorizedWhenValidationFails() throws Exception {
  doThrow(new OAuthException("")).when(validator).validateMessage(
      any(OAuthMessage.class), any(OAuthAccessor.class));
  Map<String, String[]> params = getOAuthParams();
  when(req.getParameterMap()).thenReturn(params);

  servlet.doPost(req, resp);

  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  verify(resp).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #26
Source File: DataApiOAuthServletTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
public void testDoRequestTokenUnauthorizedOnOAuthException() throws Exception {
  when(req.getPathInfo()).thenReturn(REQUEST_TOKEN_PATH);
  when(req.getMethod()).thenReturn("GET");

  doThrow(new OAuthException("")).when(validator).validateMessage(
      any(OAuthMessage.class), any(OAuthAccessor.class));

  servlet.doGet(req, resp);

  verify(resp).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #27
Source File: OAuthClient.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
    * Construct a request message, send it to the service provider and get the
    * response.
    * 
    * @param httpMethod
    *            the HTTP request method, or null to use the default method
    * @return the response
    * @throws URISyntaxException
    *             the given url isn't valid syntactically
    * @throws OAuthProblemException
    *             the HTTP response status code was not 200 (OK)
    */
   @SuppressWarnings("rawtypes")
public OAuthMessage invoke(OAuthAccessor accessor, String httpMethod,
           String url, Collection<? extends Map.Entry> parameters)
   throws IOException, OAuthException, URISyntaxException {
       OAuthMessage request = accessor.newRequestMessage(httpMethod, url, parameters);
       Object accepted = accessor.consumer.getProperty(OAuthConsumer.ACCEPT_ENCODING);
       if (accepted != null) {
           request.getHeaders().add(new OAuth.Parameter(HttpMessage.ACCEPT_ENCODING, accepted.toString()));
       }
       Object ps = accessor.consumer.getProperty(PARAMETER_STYLE);
       net.oauth.ParameterStyle style = (ps == null) ? net.oauth.ParameterStyle.BODY
               : Enum.valueOf(net.oauth.ParameterStyle.class, ps.toString());
       return invoke(request, style);
   }
 
Example #28
Source File: OAuthSignatureMethod.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static OAuthSignatureMethod newSigner(OAuthMessage message,
        OAuthAccessor accessor) throws IOException, OAuthException {
    message.requireParameters(OAuth.OAUTH_SIGNATURE_METHOD);
    OAuthSignatureMethod signer = newMethod(message.getSignatureMethod(),
            accessor);
    signer.setTokenSecret(accessor.tokenSecret);
    return signer;
}
 
Example #29
Source File: OAuthSignatureMethod.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected String getSignature(OAuthMessage message)
throws OAuthException, IOException, URISyntaxException {
    String baseString = getBaseString(message);
    String signature = getSignature(baseString);
    // Logger log = Logger.getLogger(getClass().getName());
    // if (log.isLoggable(Level.FINE)) {
    // log.fine(signature + "=getSignature(" + baseString + ")");
    // }
    return signature;
}
 
Example #30
Source File: OAuthHttpServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private static OAuthException convertException(org.sakaiproject.oauth.exception.OAuthException originalException) {
    if (originalException instanceof InvalidConsumerException)
        return new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN);
    else if (originalException instanceof ExpiredAccessorException)
        return new OAuthProblemException(OAuth.Problems.TOKEN_EXPIRED);
    else if (originalException instanceof RevokedAccessorException)
        return new OAuthProblemException(OAuth.Problems.TOKEN_REVOKED);
    else if (originalException instanceof InvalidAccessorException)
        return new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
    else if (originalException instanceof InvalidVerifierException)
        return new OAuthProblemException(OAuth.Problems.PARAMETER_REJECTED);
    else
        return new OAuthProblemException();
}