net.oauth.OAuthAccessor Java Examples

The following examples show how to use net.oauth.OAuthAccessor. 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: OAuthClientUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static Token getRequestToken(WebClient requestTokenService,
                                    Consumer consumer,
                                    URI callback,
                                    Map<String, String> extraParams,
                                    Map<String, Object> oauthConsumerProps) throws OAuthServiceException {
    Map<String, String> parameters = new HashMap<>();
    if (extraParams != null) {
        parameters.putAll(extraParams);
    }
    parameters.put(OAuth.OAUTH_CALLBACK, callback.toString());

    if (oauthConsumerProps == null || !oauthConsumerProps.containsKey(OAuth.OAUTH_SIGNATURE_METHOD)) {
        parameters.put(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);
    }
    parameters.put(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());
    parameters.put(OAuth.OAUTH_TIMESTAMP, String.valueOf(System.currentTimeMillis() / 1000));
    parameters.put(OAuth.OAUTH_CONSUMER_KEY, consumer.getKey());

    OAuthAccessor accessor = createAccessor(consumer, oauthConsumerProps);
    return getToken(requestTokenService, accessor, parameters);
}
 
Example #2
Source File: DataApiTokenContainer.java    From swellrt with Apache License 2.0 6 votes vote down vote up
/**
 * Authorize the {@link OAuthAccessor} by generating a new access token and
 * token secret.
 *
 * @param requestToken the requestToken used for identifying the accessor that
 *        needs to be authorized.
 * @return a new {@link OAuthAccessor} with the access token and token secret
 *         set.
 * @throws OAuthProblemException if the request token in the accessor is not
 *         known.
 */
public OAuthAccessor generateAccessToken(String requestToken) throws OAuthProblemException {
  OAuthAccessor accessor = getRequestTokenAccessor(requestToken);

  if (accessor.getProperty(USER_PROPERTY_NAME) == null) {
    // User has not given the consumer permission yet.
    throw OAuthUtil.newOAuthProblemException(OAuth.Problems.PERMISSION_UNKNOWN);
  }

  // Token secret does not need to unique so can be generated now.
  accessor.tokenSecret = generateToken();

  do {
    accessor.accessToken = generateToken();
  } while (accessTokenAccessors.putIfAbsent(accessor.accessToken, accessor) != null);
  requestTokenAccessors.remove(accessor.requestToken);

  LOG.info("Generated access token for " + accessor.getProperty(USER_PROPERTY_NAME));
  return accessor.clone();
}
 
Example #3
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 #4
Source File: DataApiServlet.java    From swellrt with Apache License 2.0 6 votes vote down vote up
/**
 * Entry point for the Data API Calls.
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  OAuthMessage message = new HttpRequestMessage(req, req.getRequestURL().toString());

  OAuthAccessor accessor;
  try {
    message.requireParameters(OAuth.OAUTH_TOKEN);
    accessor = tokenContainer.getAccessTokenAccessor(message.getParameter(OAuth.OAUTH_TOKEN));
  } catch (OAuthProblemException e) {
    LOG.info("No valid OAuth token present", e);
    // Have to set status here manually, cannot use e.getHttpStatusCode
    // because message.requireParameters doesn't set it in the exception.
    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
    return;
  }
  ParticipantId participant =
      (ParticipantId) accessor.getProperty(DataApiTokenContainer.USER_PROPERTY_NAME);
  
  processOpsRequest(req, resp, message, accessor, participant);
}
 
Example #5
Source File: WaveService.java    From swellrt with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param consumerKey the consumer key.
 * @param consumerSecret the consumer secret
 * @param rpcServerUrl the URL of the JSON-RPC request handler
 */
public ConsumerData(String consumerKey, String consumerSecret, String rpcServerUrl) {
  String consumerKeyPrefix = "";
  // NOTE(ljvderijk): Present for backwards capability.
  if (RPC_URL.equals(rpcServerUrl) || SANDBOX_RPC_URL.equals(rpcServerUrl)) {
    consumerKeyPrefix = "google.com:";
  }
  this.consumerKey = consumerKeyPrefix + consumerKey;
  this.consumerSecret = consumerSecret;
  this.rpcServerUrl = rpcServerUrl;

  userAuthenticated = false;
  OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, null);
  consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);
  accessor = new OAuthAccessor(consumer);
}
 
Example #6
Source File: OAuthClientUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static Token getAccessToken(WebClient accessTokenService,
                                   Consumer consumer,
                                   Token requestToken,
                                   String verifier,
                                   Map<String, Object> oauthConsumerProps) throws OAuthServiceException {
    Map<String, String> parameters = new HashMap<>();
    parameters.put(OAuth.OAUTH_CONSUMER_KEY, consumer.getKey());
    parameters.put(OAuth.OAUTH_TOKEN, requestToken.getToken());
    parameters.put(OAuth.OAUTH_VERIFIER, verifier);
    if (oauthConsumerProps == null || !oauthConsumerProps.containsKey(OAuth.OAUTH_SIGNATURE_METHOD)) {
        parameters.put(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);
    }

    OAuthAccessor accessor = createAccessor(consumer, oauthConsumerProps);
    accessor.requestToken = requestToken.getToken();
    accessor.tokenSecret = requestToken.getSecret();
    return getToken(accessTokenService, accessor, parameters);
}
 
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: Util.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static OAuthAccessor convertToOAuthAccessor(Accessor accessor, OAuthConsumer oAuthConsumer)
        throws OAuthProblemException {
    if (accessor == null)
        return null;
    if (!oAuthConsumer.consumerKey.equals(accessor.getConsumerId()))
        throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_REFUSED);
    OAuthAccessor oAuthAccessor = new OAuthAccessor(oAuthConsumer);
    if (accessor.getType() == Accessor.Type.ACCESS)
        oAuthAccessor.accessToken = accessor.getToken();
    else
        oAuthAccessor.requestToken = accessor.getToken();
    oAuthAccessor.tokenSecret = accessor.getSecret();
    // Support Variable Accessor Secret http://wiki.oauth.net/w/page/12238502/AccessorSecret
    if (accessor.getAccessorSecret() != null)
        oAuthConsumer.setProperty(OAuthConsumer.ACCESSOR_SECRET, accessor.getAccessorSecret());
    return oAuthAccessor;
}
 
Example #9
Source File: DataApiTokenContainer.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
/**
 * Authorizes a request token to be exchanged for an access token.
 *
 * @param requestToken the request token used for identification.
 * @param user the user that has authorized the token.
 * @throws OAuthProblemException if the request token does not map to an
 *         accessor or if the token was already used.
 */
public OAuthAccessor authorizeRequestToken(String requestToken, ParticipantId user)
    throws OAuthProblemException {
  Preconditions.checkNotNull(user, "User must not be null");

  OAuthAccessor accessor = getRequestTokenAccessor(requestToken);

  if (accessor.getProperty(USER_PROPERTY_NAME) != null) {
    throw OAuthUtil.newOAuthProblemException(OAuth.Problems.TOKEN_USED);
  }

  accessor.setProperty(USER_PROPERTY_NAME, user);
  requestTokenAccessors.put(requestToken, accessor);

  LOG.info("Authorized request token for " + user);
  return accessor.clone();
}
 
Example #10
Source File: DataApiServletTest.java    From swellrt with Apache License 2.0 6 votes vote down vote up
public void testDoPostExecutesAndWritesResponse() throws Exception {
  String operationId = "op1";
  OperationRequest operation = new OperationRequest("wavelet.create", operationId);
  List<OperationRequest> operations = Collections.singletonList(operation);
  when(robotSerializer.deserializeOperations(anyString())).thenReturn(operations);
  String responseValue = "response value";
  when(robotSerializer.serialize(any(), any(Type.class), any(ProtocolVersion.class))).thenReturn(
      responseValue);
  Map<String, String[]> params = getOAuthParams();
  when(req.getParameterMap()).thenReturn(params);

  OperationService service = mock(OperationService.class);
  when(operationRegistry.getServiceFor(any(OperationType.class))).thenReturn(service);

  servlet.doPost(req, resp);

  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  verify(operationRegistry).getServiceFor(any(OperationType.class));
  verify(service).execute(eq(operation), any(OperationContext.class), eq(ALEX));
  verify(resp).setStatus(HttpServletResponse.SC_OK);
  assertEquals("Response should have been written into the servlet", responseValue,
      stringWriter.toString());
}
 
Example #11
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 #12
Source File: DataApiTokenContainer.java    From swellrt with Apache License 2.0 6 votes vote down vote up
/**
 * Authorizes a request token to be exchanged for an access token.
 *
 * @param requestToken the request token used for identification.
 * @param user the user that has authorized the token.
 * @throws OAuthProblemException if the request token does not map to an
 *         accessor or if the token was already used.
 */
public OAuthAccessor authorizeRequestToken(String requestToken, ParticipantId user)
    throws OAuthProblemException {
  Preconditions.checkNotNull(user, "User must not be null");

  OAuthAccessor accessor = getRequestTokenAccessor(requestToken);

  if (accessor.getProperty(USER_PROPERTY_NAME) != null) {
    throw OAuthUtil.newOAuthProblemException(OAuth.Problems.TOKEN_USED);
  }

  accessor.setProperty(USER_PROPERTY_NAME, user);
  requestTokenAccessors.put(requestToken, accessor);

  LOG.info("Authorized request token for " + user);
  return accessor.clone();
}
 
Example #13
Source File: DataApiOAuthServletTest.java    From swellrt with Apache License 2.0 6 votes vote down vote up
public void testDoExchangeToken() throws Exception {
  when(req.getPathInfo()).thenReturn(ACCESS_TOKEN_PATH);
  when(req.getMethod()).thenReturn("GET");
  Map<String, String[]> params = getDoExchangeTokenParams();
  when(req.getParameterMap()).thenReturn(params);

  servlet.doGet(req, resp);

  verify(validator).validateMessage(any(OAuthMessage.class), any(OAuthAccessor.class));
  verify(resp).setStatus(HttpServletResponse.SC_OK);

  // Verify that the output contains a token and token secret.
  String output = outputStream.toString();
  Map<String, String> parameters = toMap(OAuth.decodeForm(output));
  assertTrue("Access token should be present", parameters.containsKey(OAuth.OAUTH_TOKEN));
  assertTrue(
      "Access token secret should be present", parameters.containsKey(OAuth.OAUTH_TOKEN_SECRET));
  OAuthAccessor accessTokenAccessor =
      tokenContainer.getAccessTokenAccessor(parameters.get(OAuth.OAUTH_TOKEN));
  assertNotNull("Container should have stored the token", accessTokenAccessor);
  assertEquals("Correct secret should be returned", accessTokenAccessor.tokenSecret,
      parameters.get(OAuth.OAUTH_TOKEN_SECRET));
}
 
Example #14
Source File: GoogleCallAction.java    From jivejdon with Apache License 2.0 6 votes vote down vote up
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
	String forwdUrl = mapping.findForward("success").getPath();
	String domainUrl = CallUtil.getCleanDomainUrl(request, forwdUrl);

	GoogleOAuthSubmitter googleOAuthSubmitter = (GoogleOAuthSubmitter) WebAppUtil.getComponentInstance("googleOAuthSubmitter", request);
	OAuthAccessor accessor = googleOAuthSubmitter.request(domainUrl);
	if (accessor.requestToken != null) {
		HttpSession session = request.getSession();
		session.setAttribute("resToken", accessor);
		Map<String, String> params = CallUtil.getParameters(request);
		session.setAttribute("subscriptionParameters", params);
		String authorizationURL = accessor.consumer.serviceProvider.userAuthorizationURL;
		authorizationURL = OAuth.addParameters(authorizationURL, OAuth.OAUTH_TOKEN, accessor.requestToken);
		response.sendRedirect(authorizationURL);
	} else {
		request.setAttribute("errors", "google authserver error");
	}

	return mapping.findForward("failure");
}
 
Example #15
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 #16
Source File: Util.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static OAuthAccessor convertToOAuthAccessor(Accessor accessor, OAuthConsumer oAuthConsumer)
        throws OAuthProblemException {
    if (accessor == null)
        return null;
    if (!oAuthConsumer.consumerKey.equals(accessor.getConsumerId()))
        throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_REFUSED);
    OAuthAccessor oAuthAccessor = new OAuthAccessor(oAuthConsumer);
    if (accessor.getType() == Accessor.Type.ACCESS)
        oAuthAccessor.accessToken = accessor.getToken();
    else
        oAuthAccessor.requestToken = accessor.getToken();
    oAuthAccessor.tokenSecret = accessor.getSecret();
    // Support Variable Accessor Secret http://wiki.oauth.net/w/page/12238502/AccessorSecret
    if (accessor.getAccessorSecret() != null)
        oAuthConsumer.setProperty(OAuthConsumer.ACCESSOR_SECRET, accessor.getAccessorSecret());
    return oAuthAccessor;
}
 
Example #17
Source File: DataApiServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/** Sets the list of parameters needed to test exchanging a request token */
private Map<String, String[]> getOAuthParams() throws Exception {
  OAuthAccessor requestAccessor = tokenContainer.generateRequestToken(consumer);
  tokenContainer.authorizeRequestToken(requestAccessor.requestToken, ALEX);
  OAuthAccessor authorizedAccessor =
      tokenContainer.generateAccessToken(requestAccessor.requestToken);
  Map<String, String[]> params = Maps.newHashMap();
  params.put(OAuth.OAUTH_TOKEN, new String[] {authorizedAccessor.accessToken});
  return params;
}
 
Example #18
Source File: DataApiTokenContainerTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
public void testGenerateRequestToken() throws Exception {
  OAuthAccessor accessor = container.generateRequestToken(consumer);

  assertEquals("Consumer should be retained", consumer, accessor.consumer);
  assertFalse("Request token should be generated", accessor.requestToken.isEmpty());
  assertTrue("Accessor should be in storage",
      areEqual(accessor, container.getRequestTokenAccessor(accessor.requestToken)));
}
 
Example #19
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 #20
Source File: OAuthClientUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static OAuthAccessor createAccessor(Consumer consumer, Map<String, Object> props) {
    OAuthConsumer oAuthConsumer = new OAuthConsumer(null, consumer.getKey(), consumer.getSecret(),
                                                    null);
    if (props != null) {
        for (Map.Entry<String, Object> entry : props.entrySet()) {
            oAuthConsumer.setProperty(entry.getKey(), entry.getValue());
        }
    }
    return new OAuthAccessor(oAuthConsumer);
}
 
Example #21
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 #22
Source File: DataApiTokenContainerTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
public void testRejectRequestTokenAfterAuthorizationThrowsException() throws Exception {
  OAuthAccessor unauthorizedRequestToken = container.generateRequestToken(consumer);

  container.authorizeRequestToken(unauthorizedRequestToken.requestToken, ALEX);
  try {
    container.rejectRequestToken(unauthorizedRequestToken.requestToken);
    fail("Expected OAuthProblemException");
  } catch (OAuthProblemException e) {
    // expected
  }
}
 
Example #23
Source File: DataApiOAuthServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/** Sets the list of parameters needed to test exchanging a request token */
private Map<String, String[]> getDoExchangeTokenParams() throws Exception {
  OAuthAccessor requestAccessor = tokenContainer.generateRequestToken(consumer);
  tokenContainer.authorizeRequestToken(requestAccessor.requestToken, ALEX);
  Map<String, String[]> params = Maps.newHashMap();
  params.put(OAuth.OAUTH_TOKEN, new String[] {requestAccessor.requestToken});
  return params;
}
 
Example #24
Source File: DataApiOAuthServletTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
public void testDoExchangeTokenUnauthorizedOnURISyntaxException() 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 URISyntaxException("", "")).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 #25
Source File: DataApiOAuthServletTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/** Sets the list of parameters needed to test exchanging a request token */
private Map<String, String[]> getDoExchangeTokenParams() throws Exception {
  OAuthAccessor requestAccessor = tokenContainer.generateRequestToken(consumer);
  tokenContainer.authorizeRequestToken(requestAccessor.requestToken, ALEX);
  Map<String, String[]> params = Maps.newHashMap();
  params.put(OAuth.OAUTH_TOKEN, new String[] {requestAccessor.requestToken});
  return params;
}
 
Example #26
Source File: DataApiTokenContainerTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testGenerateAccessTokenForAlreadyAuthorizedTokenThrowsException() throws Exception {
  OAuthAccessor unauthorizedRequestToken = container.generateRequestToken(consumer);
  OAuthAccessor authorizedRequestToken =
      container.authorizeRequestToken(unauthorizedRequestToken.requestToken, ALEX);

  container.generateAccessToken(authorizedRequestToken.requestToken);
  try {
    container.generateAccessToken(authorizedRequestToken.requestToken);
    fail("Expected OAuthProblemException when authorizing an already used token");
  } catch (OAuthProblemException e) {
    // expected
  }
}
 
Example #27
Source File: DataApiTokenContainerTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testGenerateAccessTokenForUnauthorizedTokenThrowsException() throws Exception {
  OAuthAccessor unauthorizedRequestToken = container.generateRequestToken(consumer);

  try {
    container.generateAccessToken(unauthorizedRequestToken.requestToken);
    fail("Expected OAuthProblemException");
  } catch (OAuthProblemException e) {
    // expected
  }
}
 
Example #28
Source File: DataApiTokenContainerTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testGenerateAccessToken() throws Exception {
  OAuthAccessor unauthorizedRequestToken = container.generateRequestToken(consumer);
  OAuthAccessor authorizedRequestToken =
      container.authorizeRequestToken(unauthorizedRequestToken.requestToken, ALEX);
  OAuthAccessor accessToken = container.generateAccessToken(authorizedRequestToken.requestToken);

  assertEquals("Consumer should be retained", consumer, accessToken.consumer);
  assertFalse("Access token should be generated", accessToken.accessToken.isEmpty());
  assertFalse("Token secret should be generated", accessToken.tokenSecret.isEmpty());
  assertTrue("Accessor should be in storage",
      areEqual(accessToken, container.getAccessTokenAccessor(accessToken.accessToken)));
}
 
Example #29
Source File: DataApiTokenContainerTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testRejectRequestTokenAfterAuthorizationThrowsException() throws Exception {
  OAuthAccessor unauthorizedRequestToken = container.generateRequestToken(consumer);

  container.authorizeRequestToken(unauthorizedRequestToken.requestToken, ALEX);
  try {
    container.rejectRequestToken(unauthorizedRequestToken.requestToken);
    fail("Expected OAuthProblemException");
  } catch (OAuthProblemException e) {
    // expected
  }
}
 
Example #30
Source File: OAuthUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void validateMessage(OAuthMessage oAuthMessage,
                                   Client client,
                                   Token token,
                                   OAuthDataProvider provider,
                                   OAuthValidator validator)
    throws Exception {
    OAuthConsumer consumer = new OAuthConsumer(null, client.getConsumerKey(),
        client.getSecretKey(), null);
    OAuthAccessor accessor = new OAuthAccessor(consumer);
    if (token != null) {
        if (token instanceof RequestToken) {
            accessor.requestToken = token.getTokenKey();
        } else {
            accessor.accessToken = token.getTokenKey();
        }
        accessor.tokenSecret = token.getTokenSecret();
    }
    try {
        validator.validateMessage(oAuthMessage, accessor);
    } catch (Exception ex) {
        if (token != null) {
            provider.removeToken(token);
        }
        throw ex;
    }
    if (token != null && validator instanceof DefaultOAuthValidator) {
        ((DefaultOAuthValidator)validator).validateToken(token, provider);
    }
}