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.
Related
I follow the steps in the Spotify Web Api Tutorial using the authorization-code from the Spotify Accounts Authentication Examples. Everything is okey, I register an application with Spotify, authenticate a user and get authorization to access user data and when the page show me the user data the refresh token is different each time I authenticate myself. I think refresh token shuld not change.
The only modification I did in the example code was replace the client id, client secret and the redirect uri with the correct values from my application.
Any advices?
For the Authorisation Code Flow you just need to do that initial authentication you're already doing. It will always return a new refresh token however that token can be used over an over with 4. Requesting a refreshed access token; Spotify returns a new access token to your app from Authorisation Guide that will return you a new access token for subsequent calls and you won't need to do the Authentication Step you're doing multiple times just keep doing that one.
In an OAuth1 process, I save my token and my secret and recreate my access token like the following:
accessToken = new Token(token, secret);
In an OAuth2 process, I only get a code. If I save this code and try to recreate the access token like following, the app crashes:
Verifier v = new Verifier(code);
accessToken = service.getAccessToken(null, v);
The response:
org.scribe.exceptions.OAuthException: Cannot extract an acces token. Response was: {"code": 400, "error_type": "OAuthException", "error_message": "No matching code found."}
How do I recreate an access token in an OAuth2 process?
I think the problem here is not with your Java code to extract the token (the bit that you're showing at least) - that looks fine from what I can tell.
The error message is a response back from the service you're trying to authorize with (e.g. twitter, or whatever it is in your case) saying that
code
is not known. That could happen if too much time has passed since you got that authorization code from the service, or simply that the authorization code you have is wrong for some reason.
In order to provide proper answer, I'd need to see a bit more code... how precisely are you getting the value of
code
that is going into the constructor of
Verifier
? Please can you provide more of the code you're using for that?
[Sorry, I would have added this as a comment, but don't have enough reputation.]
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!
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.
I am developing a Java Application where I am implementing 3-legged OAuth using google gdata in Java. This application is registered on Google App Engine. At the first stage, I am getting the unauthorized request-token successfully. I am storing that token in session and create a link using createUserAuthorizationUrl(oauthParameters). Then on clicking the link, it redirect me to "Grant Access Page".
Now, even though I grant access, it doesn't show me this page. But, it redirects me to my callback url. However, this seems proper. But, it also doesn't add the entry under My Account. Here, I am storing the oauth_token in session.
When getting redirected, the url of that page contains oauth_token & oauth_verifier, both ! Now, on this callback url, I have a submit button & set action of for to an accessTokenServlet.java. The code of this servlet is as follow :
Now I am sending request to fetch Access Token. My code is :
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);
oauthParameters.setOAuthType(OAuthParameters.OAuthType.THREE_LEGGED_OAUTH);
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
oauthParameters.setOAuthToken(request.getSession().getAttribute("oauth_token").toString());
oauthParameters.setOAuthTokenSecret(request.getSession().getAttribute("oauth_token_secret").toString());
try {
String accessToken = oauthHelper.getAccessToken(oauthParameters);
out.println("Access Token : " + accessToken);
} catch (OAuthException e) {
//System.out.print("Response Status : " + response.getStatus());
out.println("Exception : ");
e.printStackTrace();
return;
}
While clicking on submit button, it prints "Access Token : " & nothing ! No token returns !
I am getting wrong at the stage of authorizing the request token itself. But, I am not getting, what problem got generated ?
The page with the verifier you linked to should only happen if you pass in an oauth_callback of oob — this indicates that you will be moving the verifier out-of-band. I strongly recommend against using oob for anything but debugging. Instead, you should be setting a callback URL and getting the verifier out of the query string.
In the code above, I don't see anything that sets the verifier in the OAuth parameters, so that's likely your problem. You're also not doing much in the way of error handling, and that's a really important piece of the OAuth flow — for example, once you've got it working, try canceling the OAuth process and see how your application handles it.
You will only see the entry in your issued tokens list after you've fully completed the process and obtained an upgraded access token.