How to provide a Twitter PIN statically during OAuth authentication - java

http://twitter4j.org/en/code-examples.html - How to provide a Twitter PIN statically during OAuth authentication, the code example talks about providing a PIN if its already available.
Our application is a standalone java application and would prefer to pass credentials via a property file without any human intervention.

Twitter will provide you the PIN code.
In the example, Twitter4J supposes that somebody will copy the URL it gave (with requestToken.getAuthorizationURL() at line 10) in a web browser and will authorize the application via the browser. After that, the user is supposed to write in the example program the PIN code displayed in its browser.
There are two big drawbacks for you in this example :
Human intervention
Which code will you give to your example program if Twitter do not give you a PIN code (and it will happen if the callback URL of your Twitter application is not "oob") ?
You will have to simulate the human intervention to get the PIN code. Unfortunately, Twitter4J does not seem to get methods to do this (I do not see such method in the Javadoc) so you will have to code yourself the following process :
Retrieve the HTML code of the web page at requestToken.getAuthorizationURL().
This HTML page contains a form whose some parameters will be posted with the username (or email) and the user's password to get the PIN code. These parameters are called "oauth_token" (the temporary OAuth token that you already have), "deny" (a tag used if you do not want to authorize the application) and "authenticity_token". All of them are in <input> HTML tags. Pick them.
Simulate the posting of the form. For this you will have to use the POST oauth/authorize endpoint. The URL is https://api.twitter.com/oauth/authorize?oauth_token=<your OAuth Token>. The request has to be authenticated following the Twitter process for Authenticating requests. This is the content of what you will post : "authenticity_token=<the form's "authenticity_token" parameter>&session[username_or_email]=<user's name or email>&session[password]=<the user's password in clear>". If you don't authorize the app, append "&deny=<the form's "deny" parameter>" in the body message. There will not be any problem for you since you have got the credentials (session[xxx] parameters) in a property file and you picked the other parameters in the form (cf 2.).
The Twitter API will give you back an web page. If the authorization was successful, the PIN will be inside. However, be careful. The PIN takes different names depending on the callback URL. If the callback URL is "oob", the PIN code is called OAuth PIN. It is a 4-digit number somewhere in a <div id="oauth_pin"> HTML tag. Otherwise, it is called OAuth Verifier. It is contained in a URL located in a <div class="happy notice callback"> HTML tag. In this URL, the PIN is the oauth_verifier of the request string. It looks like an OAuth token.
Don't hesitate to have a look at the HTML code of the web pages of the 2nd and the 4th step of my process. It is very useful to understand the process.

I spent some time today trying to figure out how to authenticate without user intervention using Twitter4j Library. I came up with the following:
ConfigurationBuilder conf = new ConfigurationBuilder();
conf.setOAuthConsumerKey(CONSUMER_KEY);
conf.setOAuthConsumerSecret(CONSUMER_KEY_SECRET);
conf.setOAuthAccessToken(TOKEN);
conf.setOAuthAccessTokenSecret(TOKEN_SECRET);
Twitter twitter = new TwitterFactory(conf.build()).getInstance();
By using ConfigurationBuilder, I'm now able to authenticate automatically. Of course you need to set values for CONSUMER AND TOKEN keys accordingly. Here's how I verified it:
User user = twitter.verifyCredentials();
System.out.println("Successfully verified credentials of " + user.getScreenName());
Hope this helps!

Related

JAVA youtube api allow users to upload to my channel without login

I was playing around with youtube api samples that they provide in this link
with JAVA
I can search for videos upload videos to specific channel and all the code that they provide works fine.
the only problem I face is "when I try to upload it opens my default browser and asks me to sign in"
like this screenshot.
here is what in my head I know it's not that simple it's just a imagination of what I want to achieve.
// String myaccount = "username#gmail.com"
// String mypassword = "123456789"
// String mychannel_id = "UCU7mv98lde1hon2DXIgGMKg"
// signin(myaccount,mypassword,mychannel_id);
// upload(video.mp4);
what I have:
client_id, client_secret in json file
the channel id, account, and the password
i was searching for about a day and all i got is ..
access token
,Token Service API
,identity toolkit api
,onBehalfOfContent,onBehalfOfContentOwner
however I don't know how they work or where I can get them
finally I have small idea I traced the code and I found it saves a file with all credentials in C://users/user-name/.oauth-credentials
it's not readable but it seems like it is used to authorize the account with the password and channel id
can I use this?
would it expire for any reason and i have to refresh and if so how can I refresh it?
thanks for help BTW

Google reCaptcha test without frontend

Im trying to integrate google reCaptcha into our backend. I'm getting always invalid-input-response. I'm using testing secret key, post or get doesn't matter. It is said it will accept any response, but do they think any response at all or any user generated response? It seams that I need to create proper page with captcha to test it. Not just some curl http://localhost:8080/app/register --data "g-recaptcha-response=aaaa"
Is the g-recaptcha-response some identifier of "captcha try" as there is no text to be send, that user enters, in case of the new "I'm not robot" captcha.
You understand that the purpose of recaptcha is to force human interaction? google recaptcha wil prompt the human user for some input (lke identify objects in pictures) and save the result in a cookie. without the interactive part, there is no way to test the feature

How to frame URL with username and password to access Rest API using basic authentication Java?

I have developed Rest API basic authentication, I am able to get the JSON response only when I test using Advanced Rest Client plugin(for Chrome), But how to access the JSON response by passing username and password in URL? How can others consume my rest API? Do I need to give any login popup? How can I achieve this? Any help would be highly appreciated.
your method should be POST and you need to create a encripted token for every login, and you need to active that token up to user logged out or anything else, you can store that token in browser cache, when user logged out then remove that token as well. for every user action you need to verify that token. you can generate token using MD5 also.
i think it may help you.

Google API Authorization Using Scribe OAuth Java Library

I am trying to make a Java class which would call upon Google's API to recreate an access token to a user's account with new permissions/larger scope. This class is to be instantiated by a Java servlet I had created. I want a function within that class to return a new access token. For this class to do that, I am using the Scribe library.
In Scribe's quick guide, there are two steps which concern me and have me stumped:
Step Three: Making the user validate your request token
Let’s help your users authorize your app to do the OAuth calls. For
this you need to redirect them to the following URL:
String authUrl = service.getAuthorizationUrl(requestToken);
After this either the user will get a verifier code (if this is an OOB
request) or you’ll receive a redirect from Twitter with the verifier
and the requestToken on it (if you provided a callbackUrl)
Step Four: Get the access Token
Now that you have (somehow) the verifier, you need to exchange your
requestToken and verifier for an accessToken which is the one used to
sign requests.
Verifier v = new Verifier("verifier you got from the user");
Token accessToken = service.getAccessToken(requestToken, v); // the requestToken you had from step 2
It does not seem to specify how to get that verifier from the user. How am I supposed to do that? How do I redirect my user to the authURL, and how do I get it to send its verifier back to this class of mine, which initiated the request to begin with?
If this is unclear, let me structure the question differently, taking Scribe out of the equation: To get an authorization code from Google (which would be used to then get a refresh token and access token), I would execute the following URL connection from within the servlet (yes, I've tried to answer this problem without the Scribe library, and still can't figure it out):
URL authURL = new URL("https://accounts.google.com/o/oauth2/auth");
HttpsURLConnection authCon = (HttpsURLConnection) authURL.openConnection();
authCon.setRequestMethod("GET");
authCon.setDoOutput(false);
authCon.setConnectTimeout(100000);
authCon.setRequestProperty("response_type", "code");
authCon.setRequestProperty("client_id", CLIENT_ID);
authCon.setRequestProperty("redirect_uri",
"http://**************.com/parseAuth/");
authCon.setRequestProperty("scope", convertToCommaDelimited(scopes));
authCon.setRequestProperty("state", csrfSec);
authCon.setRequestProperty("access_type", "offline");
authCon.setRequestProperty("approval_prompt", "auto");
authCon.setRequestProperty("include_granted_scopes", "true");
What has me stuck is what I should be putting for the redirect URI. After getting the user's approval for the new scope, this authorization URL would return an authorization code to the redirect URI, and seemingly nothing to whatever called it. (Am I correct in this?) So if I have another servlet as the redirect URI to parse/extract the authorization code from the response, how in the world do I get that authorization code back to my first, initial servlet? It seems to me that there is no way to have it give back the value to the servlet, in the same position of the code from which the URL was called. It looks like the function has to end there, and all new action must take place within that new servlet. But if that is the case, and I send that auth code to Google's API which would send back a refresh token and access token to ANOTHER servlet I would make to be its redirect URI, how do I possibly get that information back to what it is which called the initial servlet to begin with? That seems to be the same problem at its core, with the problem I am having with Scribe.
I've been stuck on this for many hours, and can't seem to figure out what it is I am supposed to do. I feel like I am missing some key concept, element, or step. I need this clarified. If it is at all relevant, my servlet is hosted on a Jboss application server on OpenShift.

Google Client Login Handling AuthToken

I have a non-gae, gwt application and it have a module that allows users to create documents online via google docs api.
To do that, i first ask user to enter the name and type of the document, than create a new document via google docs api with the given parameters and onSucces part of that servlet returns edit link which is used in client side to open a new page to edit the created document.
Problem that, eachtime i try to open that editLink user have to enter login informations. To solve this i try to use Google Client Login but i am totally lost i think.
First i have username and password of user and can directly use them, after searching i tried some examples which usually returns a token like this and that. Now what should i do with token? How can it be used to complete login process or should totally find another way to do login? All those oauth1,oauth2 and etc. documentations confused me a little bit.
here are my steps;
Server side;
LinkedHashMap<String, String> hashMap = new LinkedHashMap<String, String>();
// Login
DocumentList docList = new DocumentList("document");
docList.login(ServletUtil.googleDocsLoginInfo().get("username"), ServletUtil.googleDocsLoginInfo().get("password"));
//Create document with a unique suffix
String docName= parameterName+ "-Created-" + new Date();
docList.createNew(docName, dosyaTur);
// Find the created document and store editLink
DocumentListFeed feed = docList.getDocsListFeed("all");
for (final DocumentListEntry entry : feed.getEntries()) {
if (entry.getTitle().getPlainText().equals(docName)) {
hashMap.put("editlink", entry.getDocumentLink().getHref());
}
}
return hashMap;
And Client side;
#Override
public void onSuccess(LinkedHashMap<String, String> result) {
String editLink = result.get("editlink");
Window.open(editLink,"newwindow","locationno");
}
Thanks for your helps.
If I may suggest using OAuth instead of Client Login, which is outdated and less secure.
The functionality is basically the same (for OAuth 2.0 there are more ways to handle the login).
I know, trying to understand how to access the api via OAuth is very confusing, so I try to break it down a little:
If you use OAuth 2.0 you may want to use a library like this one or you can try out my own (although I wrote it for Android, this could work with other Java Apps including Web Apps)
This is what happens when a user logs in the first time with your app:
> Your App sends an authorization request containing some information about your app - for example your app needs to be registered with google and therefore has a special application key
< The Server sends you a url, open it in a new browser window and let the user login. There he will be asked to allow your app to access his account (or some parts of it) - when he confirms he will be prompted an Authorization Code which he needs to copy
> The user gets back to your app, where you will ask him for the authorization code. After he gave it, your app connects again with the server and sends the code as some kind of authorization grant of the user.
< The Server answers with a access token
All you need to do is use this access token (also called a bearer token) in all your requests to the server hidden in the header message.
I am sorry I can't give you a more precise answer right now, since I never used GWT. All I can say is, try using OAuth2, it is actually very simple (after you learn what all this confusing things like authorization flow, bearer token etc are) and really comfortable for your user, once the he has done the first login.

Categories