/**
  * Gets the login url.
  *
  * @return the login url
  */
 public static String getLoginUrl() {
   OAuthService service = getService();
   Token token = service.getRequestToken();
   Logger.info("Request Token - " + token.getToken() + " with secret " + token.getSecret());
   Cache.add(token.getToken(), token.getSecret());
   return service.getAuthorizationUrl(token);
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
   * , javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    log.info("GET got parameters: " + req.getParameterMap());
    log.info("HTTP Session: " + req.getSession().getAttributeNames());

    HttpSession httpsession = req.getSession();

    try {

      OAuth2Provider provider =
          OAuth2Provider.valueOf((String) httpsession.getAttribute("oauth.service"));
      log.info("Got provider: " + provider);

      String oauthVerifier = "";
      Token requestToken = null;
      Token accessToken = new Token("", provider.getSecret());
      OAuthService service = provider.getOAuthService();

      if (provider.getApi() instanceof DefaultApi20) {
        oauthVerifier = req.getParameter("code");
        log.info("got OAuth 2.0 authorization code: " + oauthVerifier);

      } else if (provider.getApi() instanceof DefaultApi10a) {
        oauthVerifier = req.getParameter("oauth_verifier");
        log.info("got OAuth 1.0a verifier: " + oauthVerifier);
        requestToken =
            req.getParameter("oauth_token") != null
                ? new Token((String) req.getParameter("oauth_token"), provider.getSecret())
                : (Token) httpsession.getAttribute("oauth.requestToken");
      }

      Verifier verifier = new Verifier(oauthVerifier);
      accessToken = service.getAccessToken(requestToken, verifier);
      log.info(
          "Got a OAuth access token: " + accessToken.getToken() + ", " + accessToken.getSecret());

      Cookie accessTokenCookie = new Cookie("oauth.accessToken", accessToken.getToken());
      accessTokenCookie.setMaxAge(14 * 24 * 60 * 60);
      accessTokenCookie.setPath("/");
      resp.addCookie(accessTokenCookie);
      Cookie serviceCookie = new Cookie("oauth.service", provider.toString());
      serviceCookie.setPath("/");
      serviceCookie.setMaxAge(14 * 24 * 60 * 60);
      resp.addCookie(serviceCookie);
      Cookie secretCookie = new Cookie("oauth.secret", accessToken.getSecret());
      secretCookie.setPath("/");
      secretCookie.setMaxAge(14 * 24 * 60 * 60);
      resp.addCookie(secretCookie);

      resp.sendRedirect((String) req.getSession().getAttribute("http.referer"));

    } catch (Exception e) {
      log.log(Level.WARNING, e.getLocalizedMessage(), e);
    }
  }
  @Betamax(tape = "EtsyAPILibraryTape")
  @Test
  public void testRetrieveAccessToken() {
    authenticate();

    Token accessTokenBefore = requestManager.getAccessToken();
    assertEquals(true, requestManager.retrieveAccessToken());
    Token accessTokenAfter = requestManager.getAccessToken();

    assertEquals(accessTokenBefore.getToken(), accessTokenAfter.getToken());
    assertEquals(accessTokenBefore.getSecret(), accessTokenAfter.getSecret());
  }
 @Test
 public void shouldExtractTokenFromOAuthStandardResponse() {
   String response = "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03";
   Token extracted = extractor.extract(response);
   assertEquals("hh5s93j4hdidpola", extracted.getToken());
   assertEquals("hdhd0244k9j7ao03", extracted.getSecret());
 }
    @Override
    protected Void doInBackground(String... verifier) {

      Verifier v = new Verifier(verifier[0]);

      // save this token for practical use.
      Token accessToken = service.getAccessToken(requestToken, v);

      OAuthRequest request =
          new OAuthRequest(Verb.GET, "http://api.openstreetmap.org/api/capabilities");
      service.signRequest(accessToken, request);
      Response response = request.send();

      Log.i("TakeABreak", response.getBody());

      SharedPreferences.Editor editor = settings.edit();

      editor.putString("accessToken", accessToken.getToken());
      editor.putString("accessSecret", accessToken.getSecret());

      // The requestToken is saved for use later on to verify the OAuth request.
      // See onResume() below
      editor.putString("requestToken", requestToken.getToken());
      editor.putString("requestSecret", requestToken.getSecret());

      editor.commit();
      mCallback.onSuccess();

      return null;
    }
 @Test
 public void shouldExtractTokenFromResponseWithCallbackConfirmed() {
   String response =
       "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03&callback_confirmed=true";
   Token extracted = extractor.extract(response);
   assertEquals("hh5s93j4hdidpola", extracted.getToken());
   assertEquals("hdhd0244k9j7ao03", extracted.getSecret());
 }
  private String getSignature(OAuthRequest request, Token token) {
    config.log("generating signature...");
    String baseString = api.getBaseStringExtractor().extract(request);
    String signature =
        api.getSignatureService()
            .getSignature(baseString, config.getApiSecret(), token.getSecret());

    config.log("base string is: " + baseString);
    config.log("signature is: " + signature);
    return signature;
  }
Beispiel #8
0
 public OAuthToken getRequestToken(String clientId, String clientSecret) {
   OAuthService service =
       new ServiceBuilder()
           .provider(LinkedInApi.class)
           .apiKey(clientId)
           .apiSecret(clientSecret)
           .build();
   Token requestToken = service.getRequestToken();
   OAuthToken result = new OAuthToken();
   result.setToken(requestToken.getToken());
   result.setTokenSecret(requestToken.getSecret());
   return result;
 }
Beispiel #9
0
 public boolean createTumblrUser(String oauth_token, String oauth_verifier)
     throws RemoteException, SQLException {
   Verifier verifier = new Verifier(oauth_verifier);
   Token accessToken = RMIServer.service.getAccessToken(RMIServer.request_token, verifier);
   String user_token = accessToken.getToken();
   String user_secret = accessToken.getSecret();
   Token newToken = new Token(user_token, user_secret);
   OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.tumblr.com/v2/user/info");
   request.addHeader("Accept", "application/json");
   RMIServer.service.signRequest(newToken, request);
   System.out.println(request.getHeaders().keySet());
   org.scribe.model.Response response = request.send();
   JSONObject jsonresponse = new JSONObject(response.getBody());
   String name = jsonresponse.getJSONObject("response").getJSONObject("user").getString("name");
   ResultSet resultSet =
       connection
           .createStatement()
           .executeQuery("select * from users where username = \"" + name + "\"");
   if (resultSet.next()) {
     connection
         .createStatement()
         .execute(
             "update users set userToken = \""
                 + user_token
                 + "\" , userSecret = \""
                 + user_secret
                 + "\" where username = \""
                 + name
                 + "\"");
   } else {
     connection
         .createStatement()
         .execute(
             "insert into users (username,password, balance , userToken, userSecret) values (\""
                 + name
                 + "\","
                 + "\"tumblr\","
                 + 100
                 + ", "
                 + "\""
                 + user_token
                 + "\", "
                 + "\""
                 + user_secret
                 + "\")");
   }
   return true;
 }
 public void testOAuthCredential() {
   OAuthCredential credential = new OAuthCredential(REQUEST_TOKEN, TOKEN, VERIFIER, TYPE);
   assertEquals(TOKEN, credential.getToken());
   assertEquals(VERIFIER, credential.getVerifier());
   assertEquals(TYPE, credential.getProviderType());
   Token requestToken = credential.getRequestToken();
   assertEquals(TOKEN, requestToken.getToken());
   assertEquals(SECRET, requestToken.getSecret());
   // test serialization
   byte[] bytes = CommonHelper.serialize(credential);
   OAuthCredential credential2 = (OAuthCredential) CommonHelper.unserialize(bytes);
   assertEquals(credential.getRequestToken().toString(), credential2.getRequestToken().toString());
   assertEquals(credential.getToken(), credential2.getToken());
   assertEquals(credential.getVerifier(), credential2.getVerifier());
   assertEquals(credential.getProviderType(), credential2.getProviderType());
 }
  public static void authenticateEvernote(
      RenderRequest renderRequest, PortletSession portletSession, ThemeDisplay themeDisplay)
      throws OAuthException {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(renderRequest);
    String authorizationUrl = StringPool.BLANK;

    try {

      OAuthService service = getOAuthService(request, themeDisplay);

      if (PortalUtil.getOriginalServletRequest(request).getParameter(OAUTH_VERIFIER) == null) {
        // Send an OAuth message to the Provider asking for a new Request
        // Token because we don't have access to the current user's account.
        Token scribeRequestToken = service.getRequestToken();

        portletSession.setAttribute(REQUEST_TOKEN, scribeRequestToken.getToken());
        portletSession.setAttribute(REQUEST_TOKEN_SECRET, scribeRequestToken.getSecret());

        authorizationUrl = EVERNOTE_SERVICE.getAuthorizationUrl(scribeRequestToken.getToken());

      } else {
        // Send an OAuth message to the Provider asking to exchange the
        // existing Request Token for an Access Token
        Token scribeRequestToken =
            new Token(
                portletSession.getAttribute(REQUEST_TOKEN).toString(),
                portletSession.getAttribute(REQUEST_TOKEN_SECRET).toString());

        Verifier scribeVerifier =
            new Verifier(
                PortalUtil.getOriginalServletRequest(request).getParameter(OAUTH_VERIFIER));

        Token scribeAccessToken = service.getAccessToken(scribeRequestToken, scribeVerifier);

        EvernoteAuth evernoteAuth =
            EvernoteAuth.parseOAuthResponse(EVERNOTE_SERVICE, scribeAccessToken.getRawResponse());

        portletSession.setAttribute(ACCESS_TOKEN, evernoteAuth.getToken());
      }

    } catch (Exception e) {
      throw new OAuthException(e);
    }

    renderRequest.setAttribute(AUTHORIZATION_URL, authorizationUrl);
  }
Beispiel #12
0
  public OAuthToken getAccessToken(
      String clientId, String clientSecret, String authorizationCode, OAuthToken requestToken) {
    OAuthToken token = null;

    try {
      OAuthService service =
          new ServiceBuilder()
              .provider(LinkedInApi.class)
              .apiKey(clientId)
              .apiSecret(clientSecret)
              .build();
      Verifier verifier = new Verifier(authorizationCode);
      Token reqToken = new Token(requestToken.getToken(), requestToken.getTokenSecret());
      Token accessToken = service.getAccessToken(reqToken, verifier);
      token = new OAuthToken();
      token.setToken(accessToken.getToken());
      token.setTokenSecret(accessToken.getSecret());
    } catch (Exception e) {
      log.error("Error getting AccessToken", e);
    }

    return token;
  }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (request.getParameter("oauth_problem") != null) {
      if (request.getParameter("oauth_problem").equals("user_refused"))
        response.sendRedirect("refuse.html");
    } else {
      OAuthService service;
      Token requestToken, accessToken;
      OAuthRequest requestLink;
      org.scribe.model.Response responseLink;
      DBHandler db = new DBHandler();

      service =
          new ServiceBuilder()
              .provider(LinkedInApi.class)
              .apiKey("754z46slfke0xm")
              .apiSecret("Jm46YNdPTb2toxoY")
              .build();

      String oAuthToken = request.getParameter("oauth_token");
      String oAuthVerifier = request.getParameter("oauth_verifier");

      String[] data = db.getData(oAuthToken);
      String oAuthSecret = data[1];
      String roomId = data[2];
      String email = data[3];

      requestToken = new Token(oAuthToken, oAuthSecret);

      Verifier v = new Verifier(oAuthVerifier);
      accessToken = service.getAccessToken(requestToken, v);

      System.out.println("\n\n\n\n\n" + accessToken + "\n\n\n\n\n");

      db.setAccessData(email, accessToken.getToken(), accessToken.getSecret());

      requestLink = new OAuthRequest(Verb.GET, "https://api.linkedin.com/v1/people/~?format=json");
      service.signRequest(accessToken, requestLink); // the access token
      // from step 4
      responseLink = requestLink.send();

      if (responseLink.getCode() != 401) {
        JSONObject j1 = new JSONObject(responseLink.getBody());

        TeamchatAPI api = WebAppTeamChatAPI.getTeamchatAPIInstance(getServletConfig());
        api.perform(
            api.context()
                .byId(roomId)
                .post(
                    new PrimaryChatlet()
                        .setQuestionHtml(
                            "Now you are authorized to send linkedin updates from teamchat"
                                + "<br/><b>Use following keywords -</b><br/><ul>"
                                + "<li>'profile' - Get Profile Information</li>"
                                + "<li>'post' - Post on LinkedIn</li></ol>"
                                + "<li>'reset' - Remove your account from teamchat</li></ul>")));

        request.setAttribute("name", j1.getString("firstName") + " " + j1.getString("lastName"));
        RequestDispatcher rd = request.getRequestDispatcher("Auth.jsp");
        rd.forward(request, response);
      } else response.sendRedirect("error.html");
    }
  }
  @Test
  public void test() throws Exception {
    // Create an appropriately sized blocking queue
    BlockingQueue<String> queue = Queues.newLinkedBlockingQueue();

    // Define our endpoint: By default, delimited=length is set (we need this for our processor)
    // and stall warnings are on.
    UserstreamEndpoint endpoint = new UserstreamEndpoint();
    endpoint.stallWarnings(false);

    final Token appToken =
        new Token(
            "NtGAPn05Q74N0sQrAnjvJrU7z", "7sjmEWkQ68yATYjd9GI2oJ4kebTqp0vfi9J0WHIOfFH3XaOfhV");
    final Token accessToken =
        new Token(
            "4235420180-wR8ylQuJh22hh02XJVgHeGdJxWpQIan8SOiVa7s",
            "yVeJHBYwKMB4DzQ997rG8lRZh1kymvf0F0hAoEsdJbh6X");
    Authentication auth =
        new OAuth1(
            appToken.getToken(),
            appToken.getSecret(),
            accessToken.getToken(),
            accessToken.getSecret());
    // Authentication auth = new com.twitter.hbc.httpclient.auth.BasicAuth(username, password);

    final BlockingQueue<Event> events = Queues.newLinkedBlockingQueue();
    // Create a new BasicClient. By default gzip is enabled.
    BasicClient client =
        new ClientBuilder()
            .name("sampleExampleClient")
            .hosts(Constants.USERSTREAM_HOST)
            .endpoint(endpoint)
            .authentication(auth)
            .processor(new StringDelimitedProcessor(queue))
            .eventMessageQueue(events)
            .build();

    // Establish a connection
    client.connect();

    // Do whatever needs to be done with messages
    for (int msgRead = 0; msgRead < 5; msgRead++) {
      if (client.isDone()) {
        System.out.println(
            "Client connection closed unexpectedly: " + client.getExitEvent().getMessage());
        break;
      }

      String msg = queue.poll(5, TimeUnit.SECONDS);
      if (msg == null) {
        System.out.println("Did not receive a message in 5 seconds");
      } else if (msgRead != 0) {
        final ObjectMapper mapper = new ObjectMapper();
        final TwitterData twitterData = mapper.readValue(msg, TwitterData.class);
        System.out.println(msg);
      }
    }

    client.stop();

    // Print some stats
    System.out.printf("The client read %d messages!\n", client.getStatsTracker().getNumMessages());
  }
Beispiel #15
0
 public String getSecret() {
   return delegate.getSecret();
 }