net.oauth.OAuthConsumer Java Examples

The following examples show how to use net.oauth.OAuthConsumer. 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
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 #2
Source File: BasicLTIUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/** 
        * getOAuthURL - Form a GET request signed by OAuth
 * @param method
 * @param url
 * @param oauth_consumer_key
 * @param oauth_secret
 * @param signature
 */
public static String getOAuthURL(String method, String url, 
	String oauth_consumer_key, String oauth_secret, String signature)
{
	OAuthMessage om = new OAuthMessage(method, url, null);
	om.addParameter(OAuth.OAUTH_CONSUMER_KEY, oauth_consumer_key);
	if ( signature == null ) signature = OAuth.HMAC_SHA1;
	om.addParameter(OAuth.OAUTH_SIGNATURE_METHOD, signature);
	om.addParameter(OAuth.OAUTH_VERSION, "1.0");
	om.addParameter(OAuth.OAUTH_TIMESTAMP, new Long((new Date().getTime()) / 1000).toString());
	om.addParameter(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());

	OAuthConsumer oc = new OAuthConsumer(null, oauth_consumer_key, oauth_secret, null);
	try {
	    OAuthSignatureMethod osm = OAuthSignatureMethod.newMethod(signature, new OAuthAccessor(oc));
	    osm.sign(om);
	    url = OAuth.addParameters(url, om.getParameters());
	    return url;
	} catch (Exception e) {
		log.error(e.getMessage(), e);
		return null;
	}
}
 
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: 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 #5
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 #6
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 #7
Source File: WaveService.java    From incubator-retired-wave 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 #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: 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 #10
Source File: BasicLTIUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/** 
        * getOAuthURL - Form a GET request signed by OAuth
 * @param method
 * @param url
 * @param oauth_consumer_key
 * @param oauth_secret
 * @param signature
 */
public static String getOAuthURL(String method, String url, 
	String oauth_consumer_key, String oauth_secret, String signature)
{
	OAuthMessage om = new OAuthMessage(method, url, null);
	om.addParameter(OAuth.OAUTH_CONSUMER_KEY, oauth_consumer_key);
	if ( signature == null ) signature = OAuth.HMAC_SHA1;
	om.addParameter(OAuth.OAUTH_SIGNATURE_METHOD, signature);
	om.addParameter(OAuth.OAUTH_VERSION, "1.0");
	om.addParameter(OAuth.OAUTH_TIMESTAMP, new Long((new Date().getTime()) / 1000).toString());
	om.addParameter(OAuth.OAUTH_NONCE, UUID.randomUUID().toString());

	OAuthConsumer oc = new OAuthConsumer(null, oauth_consumer_key, oauth_secret, null);
	try {
	    OAuthSignatureMethod osm = OAuthSignatureMethod.newMethod(signature, new OAuthAccessor(oc));
	    osm.sign(om);
	    url = OAuth.addParameters(url, om.getParameters());
	    return url;
	} catch (Exception e) {
		log.error(e.getMessage(), e);
		return null;
	}
}
 
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: DataApiTokenContainerTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  when(tokenGenerator.generateToken(anyInt())).thenReturn(FAKE_TOKEN);
  container = new DataApiTokenContainer(tokenGenerator);
  OAuthServiceProvider serviceProvider = new OAuthServiceProvider("", "", "");
  consumer = new OAuthConsumer("", "consumerkey", "consumersecret", serviceProvider);
}
 
Example #13
Source File: DataApiServletTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  robotSerializer = mock(RobotSerializer.class);
  converterManager = mock(EventDataConverterManager.class);
  waveletProvider = mock(WaveletProvider.class);
  operationRegistry = mock(OperationServiceRegistry.class);
  ConversationUtil conversationUtil = mock(ConversationUtil.class);
  validator = mock(OAuthValidator.class);
  TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  when(tokenGenerator.generateToken(anyInt())).thenReturn(FAKE_TOKEN);
  tokenContainer = new DataApiTokenContainer(tokenGenerator);

  OAuthServiceProvider serviceProvider = new OAuthServiceProvider("", "", "");
  consumer = new OAuthConsumer("", "consumerkey", "consumersecret", serviceProvider);

  req = mock(HttpServletRequest.class);
  when(req.getRequestURL()).thenReturn(new StringBuffer("www.example.com"));
  when(req.getReader()).thenReturn(new BufferedReader(new StringReader("")));
  when(req.getMethod()).thenReturn("POST");

  resp = mock(HttpServletResponse.class);
  stringWriter = new StringWriter();
  PrintWriter writer = new PrintWriter(stringWriter);
  when(resp.getWriter()).thenReturn(writer);

  servlet =
      new DataApiServlet(robotSerializer, converterManager, waveletProvider, operationRegistry,
          conversationUtil, validator, tokenContainer);
}
 
Example #14
Source File: DataApiTokenContainer.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a new request token for the given {@link OAuthConsumer}.
 *
 * @param consumer the consumer to generate the token for.
 */
public OAuthAccessor generateRequestToken(OAuthConsumer consumer) {
  Preconditions.checkNotNull(consumer, "Consumer must not be null");

  // Accessor can be generated up front with a token secret that does not need
  // to be unique.
  OAuthAccessor accessor = new OAuthAccessor(consumer);
  accessor.tokenSecret = generateToken();

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

  return accessor.clone();
}
 
Example #15
Source File: OAuth.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Performs 3-legged OAuth authorization through Data API.
 *
 * @param service wave service.
 */
public String threeLeggedOAuth(WaveService service) throws IOException {
  Console.println("Paste this URL in your browser:\n" + serverUrl + GET_ALL_TOKENS_URL_POSTFIX);
  Console.println("Type the code you received here: ");
  String authorizationCode = new String(
      Base64.decodeBase64(Console.readLine().getBytes("UTF-8")), "UTF-8");

  StringTokenizer st = new StringTokenizer(authorizationCode);

  String requestToken = st.nextToken();
  String accessToken = st.nextToken();
  String tokenSecret = st.nextToken();

  String requestUrl = serverUrl + REQUEST_URL_POSTFIX;
  String authUrl = serverUrl + AUTH_URL_POSTFIX;
  String accessUrl = serverUrl + ACCESS_URL_POSTFIX;

  OAuthServiceProvider provider = new OAuthServiceProvider(requestUrl
      + "?scope=" + URLEncoder.encode("", "utf-8"), authUrl, accessUrl);
  OAuthConsumer consumer = new OAuthConsumer("", THREE_LEGGED_API_CONSUMER_KEY,
      THREE_LEGGED_API_CONSUMER_SECRET, provider);
  OAuthAccessor accessor = new OAuthAccessor(consumer);
  accessor.requestToken = requestToken;
  accessor.accessToken = accessToken;
  accessor.tokenSecret = tokenSecret;

  String rpcServerUrl = serverUrl + DATA_API_RPC_URL_POSTFIX;
  service.setupOAuth(accessor, rpcServerUrl);
  return rpcServerUrl;
}
 
Example #16
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 #17
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);
    }
}
 
Example #18
Source File: DefaultOAuthStore.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ConsumerInfo getConsumerKeyAndSecret(SecurityToken securityToken, String serviceName,
                                            OAuthServiceProvider provider) throws GadgetException {
    String gadgetUri = securityToken.getAppUrl();
    OAuthConsumerStore consumerStore = consumerStoreService.findByUriAndServiceName(gadgetUri, serviceName);
    if (consumerStore == null) {
        return null;
    }
    OAuthConsumer consumer = createOAuthConsumer(provider, consumerStore);
    String callbackUrl = (consumerStore.getCallbackUrl() != null ?
            consumerStore.getCallbackUrl() : defaultCallbackUrl);

    return new ConsumerInfo(consumer, consumerStore.getKeyName(), callbackUrl);
}
 
Example #19
Source File: Util.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static OAuthConsumer convertToOAuthConsumer(Consumer consumer) {
    if (consumer == null)
        return null;
    OAuthConsumer oAuthConsumer = new OAuthConsumer(consumer.getCallbackUrl(), consumer.getId(),
            consumer.getSecret(), null);
    // Support Accessor Secret http://wiki.oauth.net/w/page/12238502/AccessorSecret
    oAuthConsumer.setProperty(OAuthConsumer.ACCESSOR_SECRET, consumer.getAccessorSecret());
    return oAuthConsumer;
}
 
Example #20
Source File: DataApiOAuthServletTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  validator = mock(OAuthValidator.class);
  sessionManager = mock(SessionManager.class);

  TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  when(tokenGenerator.generateToken(anyInt())).thenReturn(FAKE_TOKEN);
  tokenContainer = new DataApiTokenContainer(tokenGenerator);

  req = mock(HttpServletRequest.class);
  when(req.getRequestURL()).thenReturn(new StringBuffer("www.example.com/robot"));
  when(req.getLocale()).thenReturn(Locale.ENGLISH);
  HttpSession sessionMock = mock(HttpSession.class);
  when(req.getSession()).thenReturn(sessionMock);
  when(req.getSession(anyBoolean())).thenReturn(sessionMock);

  resp = mock(HttpServletResponse.class);
  outputStream = new ServletOutputStreamStub();
  when(resp.getOutputStream()).thenReturn(outputStream);
  outputWriter = new StringWriter();
  when(resp.getWriter()).thenReturn(new PrintWriter(outputWriter));

  OAuthServiceProvider serviceProvider = new OAuthServiceProvider("", "", "");
  consumer = new OAuthConsumer("", "consumerkey", "consumersecret", serviceProvider);

  servlet =
      new DataApiOAuthServlet(REQUEST_TOKEN_PATH,
          AUTHORIZE_TOKEN_PATH, ACCESS_TOKEN_PATH, GET_ALL_TOKENS_PATH,
          serviceProvider, validator, tokenContainer, sessionManager, tokenGenerator);
}
 
Example #21
Source File: GoogleOAuthSubmitter.java    From jivejdon with Apache License 2.0 5 votes vote down vote up
public OAuthAccessor request(String backUrl) {
	OAuthConsumer consumer = new OAuthConsumer(backUrl, goolgeOAuthParamVO.CONSUMER_KEY, goolgeOAuthParamVO.CONSUMER_SECRET,
			goolgeOAuthParamVO.oAuthServiceProvider);
	OAuthAccessor accessor = new OAuthAccessor(consumer);
	try {
		List<OAuth.Parameter> parameters = OAuth.newList(OAuth.OAUTH_CALLBACK, backUrl);
		parameters.add(new OAuth.Parameter("scope", goolgeOAuthParamVO.scope));
		CLIENT.getRequestTokenResponse(accessor, null, parameters);
	} catch (Exception e) {
		logger.error("request error:" + e);
	}
	return accessor;
}
 
Example #22
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 #23
Source File: OAuthServiceImplRobotTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
private OAuthAccessor buildAccessor(String consumerKey,
  String consumerSecret, String requestTokenUrl, String authorizeUrl,
  String callbackUrl, String accessTokenUrl) {
  OAuthServiceProvider provider =
    new OAuthServiceProvider(requestTokenUrl, authorizeUrl, accessTokenUrl);
  OAuthConsumer consumer =
    new OAuthConsumer(callbackUrl, consumerKey, consumerSecret, provider);
  OAuthAccessor accessor = new OAuthAccessor(consumer);
  return accessor;
}
 
Example #24
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 #25
Source File: OAuthServiceImplRobotTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
private OAuthAccessor buildAccessor(String consumerKey,
  String consumerSecret, String requestTokenUrl, String authorizeUrl,
  String callbackUrl, String accessTokenUrl) {
  OAuthServiceProvider provider =
    new OAuthServiceProvider(requestTokenUrl, authorizeUrl, accessTokenUrl);
  OAuthConsumer consumer =
    new OAuthConsumer(callbackUrl, consumerKey, consumerSecret, provider);
  OAuthAccessor accessor = new OAuthAccessor(consumer);
  return accessor;
}
 
Example #26
Source File: DataApiOAuthServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  validator = mock(OAuthValidator.class);
  sessionManager = mock(SessionManager.class);

  TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  when(tokenGenerator.generateToken(anyInt())).thenReturn(FAKE_TOKEN);
  tokenContainer = new DataApiTokenContainer(tokenGenerator);

  req = mock(HttpServletRequest.class);
  when(req.getRequestURL()).thenReturn(new StringBuffer("www.example.com/robot"));
  when(req.getLocale()).thenReturn(Locale.ENGLISH);
  HttpSession sessionMock = mock(HttpSession.class);
  when(req.getSession()).thenReturn(sessionMock);
  when(req.getSession(anyBoolean())).thenReturn(sessionMock);

  resp = mock(HttpServletResponse.class);
  outputStream = new ServletOutputStreamStub();
  when(resp.getOutputStream()).thenReturn(outputStream);
  outputWriter = new StringWriter();
  when(resp.getWriter()).thenReturn(new PrintWriter(outputWriter));

  OAuthServiceProvider serviceProvider = new OAuthServiceProvider("", "", "");
  consumer = new OAuthConsumer("", "consumerkey", "consumersecret", serviceProvider);

  servlet =
      new DataApiOAuthServlet(REQUEST_TOKEN_PATH,
          AUTHORIZE_TOKEN_PATH, ACCESS_TOKEN_PATH, GET_ALL_TOKENS_PATH,
          serviceProvider, validator, tokenContainer, sessionManager, tokenGenerator);
}
 
Example #27
Source File: DataApiServletTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  robotSerializer = mock(RobotSerializer.class);
  converterManager = mock(EventDataConverterManager.class);
  waveletProvider = mock(WaveletProvider.class);
  operationRegistry = mock(OperationServiceRegistry.class);
  ConversationUtil conversationUtil = mock(ConversationUtil.class);
  validator = mock(OAuthValidator.class);
  TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  when(tokenGenerator.generateToken(anyInt())).thenReturn(FAKE_TOKEN);
  tokenContainer = new DataApiTokenContainer(tokenGenerator);

  OAuthServiceProvider serviceProvider = new OAuthServiceProvider("", "", "");
  consumer = new OAuthConsumer("", "consumerkey", "consumersecret", serviceProvider);

  req = mock(HttpServletRequest.class);
  when(req.getRequestURL()).thenReturn(new StringBuffer("www.example.com"));
  when(req.getReader()).thenReturn(new BufferedReader(new StringReader("")));
  when(req.getMethod()).thenReturn("POST");

  resp = mock(HttpServletResponse.class);
  stringWriter = new StringWriter();
  PrintWriter writer = new PrintWriter(stringWriter);
  when(resp.getWriter()).thenReturn(writer);

  servlet =
      new DataApiServlet(robotSerializer, converterManager, waveletProvider, operationRegistry,
          conversationUtil, validator, tokenContainer);
}
 
Example #28
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 #29
Source File: DataApiTokenContainerTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  when(tokenGenerator.generateToken(anyInt())).thenReturn(FAKE_TOKEN);
  container = new DataApiTokenContainer(tokenGenerator);
  OAuthServiceProvider serviceProvider = new OAuthServiceProvider("", "", "");
  consumer = new OAuthConsumer("", "consumerkey", "consumersecret", serviceProvider);
}
 
Example #30
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);
   }