I am new to OAuth, and want to get the user ID (an email address) from Google using OAuth.
But I don't want to get the user's Google Contacts Information.
We can get google Email address only not the contacts by making the scope of request token Like :
"https://www.google.com/accounts/OAuthGetRequestToken?scope=https://www.googleapis.com/auth/userinfo#email";
Now do a authorized call to get the response like :
var responseText = oAuthConsumer.GetUserInfo("https://www.googleapis.com/userinfo/email", consumerKey, consumerSecret, token, tokenSecret);
Here by saying authorized call mean to make the HTTP Get request with required paramaters in header.
header string should contain: realm, consumerKey, signatureMethod, signature, timestamp, nounce, OAuthVersion, token
Please refer to http://googlecodesamples.com/oauth_playground to verify your code and to see the correct header string parameters
Related
I am currently implementing Contact Application using Google Contact API in Java. I have completed steps of authorization and obtained an access token and a refresh token.
Now I have the CLIENT_ID , CLIENT_SECRET AND REFRESH_TOKEN with me . But the access token is getting expired within an hour.
Can someone tell how to automatically generate an access token using a refresh token in Java?
You can use Google OAuth2 client library for getting a new access token using a refresh token.
Here is my code for getting a new access token:
public TokenResponse refreshAccessToken(String refreshToken) throws IOException {
TokenResponse response = new GoogleRefreshTokenRequest(
new NetHttpTransport(),
new JacksonFactory(),
refreshToken,
"your clientId",
"your clientSecret")
.execute();
System.out.println("Access token: " + response.getAccessToken());
return response;
}
For more information read the official Google API guide:
OAuth 2.0 and the Google OAuth Client Library for Java
I have implemented this scenario in two ways. Not sure they are the best or not but works well for me.
In both cases you have to store the refresh token along with the email id of the user. Then you have to make a HTTP request in the below format.
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
client_id=**<your_client_id>**&
client_secret=**<your_client_secret>**&
refresh_token=**<refresh_token>**&
grant_type=refresh_token
It will return the access_token and expires_in
Source
Now the question is how and when to do the http request. So for that I have two ways.
1st one
Store the emailid,refresh token, access token and the current time+3600 seconds. In your database you can schedule to check the expire time in every 5 min and if current time of any user is going to reach(before 5 or 10 min) the expire time, get the refresh token and update the value for that particular user. And during api call just fetch the access token of the user.
2nd one
When user do login in your site, get the access token and current time+ 3600secs and store it in browser cookies. Now before doing any api call just check whether the current time(time when api call is done) is less than the expire time(stored in cookie). If its true then you can use the previous access token else get a new one and again update the cookie. Also you have to put another condition that if the cookie is not present at all then also you have to get new refresh token.
I am creating a twitter social login feature for my Java web application, am using the Scribe library.
Following the library tutorial here for verifying the user credentials, you will be able to retrieve the user credential as json object.
The retrieved json object doesn't have the user email, after researching for how to retrieve the email, i found this documentation in twitter api's.
Now, translating the document with the scribe api's didn't work, and still not able to get the email.
I tried all of the following:
OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json");
request.addBodyParameter("include_email", "true");
//OR
request.addQuerystringParameter("include_email", "true");
service.signRequest(accessToken, request);
Response response = request.send();
String result = response.getBody();
Any idea how to retrieve the email using scribe will be appreciated.
Regards
Paypal login workflow is https://www.paypalobjects.com/webstatic/en_US/developer/docs/lipp/oic_flowchart.png
In web application our guys did 2 steps from previous picture and put to database authtoken and refreshToken for customers.
I want later get UserInfo (step 3)
Documentation says that we can get userInfo with GET request with Autorization using accessToken.
https://developer.paypal.com/docs/api/#get-user-information
I tried:
I get access token by App_ID and Secret_Key.
If I put it to GET request i take userInfo for owner paypal application. I cannot put customerID(user_id) to this GET request as params.
If I put customer accessToken to GET request I get unauthorized error, because customer accessToken is old.
I need to refresh it with refreshToken, but I cannot do it.
Server answer is Error code : 400 with response : {"error_description":"Unable to refresh access token","error":"invalid_request","correlation_id":"fee0c71c02cda","information_link":"https://developer.paypal.com/docs/api/#errors"}
Why I cannot refresh accesstoken? (I didn't find any answer in forum)
Or maybe I cannot get User information later and we should do it immediately after step 2?
I choose step 2, i just try valid accessToken from User. And it works.
But If you want refresh token you should send request using autorization by right client_id and client-secret.
i've tried to request
https://graph.facebook.com/oauth/authorize?client_id=MY_API_KEY& redirect_uri=http://www.facebook.com/connect/login_success.html&scope=publish_stream,create_event
but i'm getting an error after redirection:
"The requested URL /login.php?login_attempt=1&next=https%3A%2F%2Fwww.facebook...."
where did login.php come from, that is not the redirection page?!
what is the problem at redirection?
thanks!
The redirect_uri should be a URL on your server where facebook will redirect the user after he/she granted you access to his/her protected resources. There you should exchange the request token--the value of the code querystring parameter returned from facebook--for the access_token with a server-side fetch.
The redirect_uri must be on the same domain as the Site URL setting on the Website with Facebook Login in the facebook application setting at https://developers.facebook.com/apps/{your-app-id}/summary/
Redirect the user to the provider
Redirect the user to the provider so he/she can tell the provider that he/she is giving you access to his/hers protected resources which you specified in the scope. After the user gives consent or rejects, the provider will redirect the user to the redirect_uri on your server. To prevent cross site scripting request forgery, you should generate and store a CSRF token and send it with the request.
https://www.facebook.com/dialog/oauth?
client_id={your-app-id}&
redirect_uri=http://your-site.com/after-redirect&
scope=list,of,scopes&
state={a-hard-to-guess-random-csrf-token}
Exchange the request token (code) for access token
In the request handler at http://your-site.com/after-redirect you should check the error and error_message request params. If there are no errors, you should first validate (compare with the stored one) the state CSRF token and if valid, then exchange the code (request token) for an access token by the provider with a server-side fetch. The redirect_uri and grant_type=authorization_code params are required (at least by some providers).
https://graph.facebook.com/oauth/access_token?
code={request-token}&
client_id={your-app-id}&
client_secret={your-app-secret}&
redirect_uri=http://your-site.com/after-redirect&
grant_type=authorization_code
Use the access token to access the user's protected resources
If the token type is bearer you should sent the access_token in the HTTP headers in the form of Authorization: Bearer {access-token}'. See: https://www.rfc-editor.org/rfc/rfc6750#section-2.1
https://graph.facebook.com/me?
fields=name,birthday,photos.limit(10).fields(id, picture)&
access_token={access-token}
Try this way :
public String getOauthUrl(String clientId, String callbackUrl, String scope) {
return "https://graph.facebook.com/oauth/authorize?client_id="
+ clientId + "&display=page&redirect_uri="
+ callbackUrl + "&scope=" + scope;
}
this is the code i'm using:
URL url2 = new URL("https://www.facebook.com/dialog/oauth?client_id=MY_APP_ID&redirect_uri=https://www.facebook.com/connect/login_success.html&scope=publish_stream,create_event");
URLConnection conn = url2.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String test;
test=rd.readLine();
resp.getWriter().println(test);
rd.close();
I just started looking at scribe for authentication with social networks such as twitter/facebook etc. I am using the example for twitter as reference. However, I don't seem to get oauth_verifier from twitter for some reason (even though the callback is registered through the service builder - I am using localhost in the callback as it worked with another social api). Any helpful suggestions would be quite welcome. thanks in advance.
OAuthService service = new ServiceBuilder()
.provider(TwitterApi.class)
.apiKey(consumerKey)
.apiSecret(consumerSecret)
.callback("http://localhost/oauth/twitter")
.build();
//get the token
Token requestToken = service.getRequestToken();
String authUrl = service.getAuthorizationUrl(requestToken);
Logger.info("authurl::" + authUrl); // not getting the oauth_verifier
Debug output from scribe (I changed the token info):
setting oauth_callback to http://localhost/oauth/twitter
generating signature...
base string is: POST&http%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252Flocalhost%252Foauth%252Ftwitter%26oauth_consumer_key%3DAAACCCV6ASDFGHJCgYBCD%26oauth_nonce%3D607134093%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1353965859%26oauth_version%3D1.0
signature is: +mSqKJIC1Q0pMEFs/gIJViF7kbg=
appended additional OAuth parameters: { oauth_callback -> http://localhost/oauth/twitter , oauth_signature -> +mSqKJIC1Q0pMEFs/gIJViF7kbg= , oauth_version -> 1.0 , oauth_nonce -> 607134093 , oauth_signature_method -> HMAC-SHA1 , oauth_consumer_key -> AAACCCV6ASDFGHJCgYBCD , oauth_timestamp -> 1353965859 }
using Http Header signature
sending request...
response status code: 200
response body: oauth_token=itJrpOP3KLeD7Ha6oy0IRr4HysFut5eAOpIlj8OmNE&oauth_token_secret=X8LmhAUpvIkfEd7t7P1lvwwobC3JJIhUabcEs0Rn5w&oauth_callback_confirmed=true
authurl::https://api.twitter.com/oauth/authorize?oauth_token=itJrpOP3KLeD7Ha6oy0IRr4HysFut5eAOpIlj8OmNE
obtaining access token from http://api.twitter.com/oauth/access_token
setting token to: Token[itJrpOP3KLeD7Ha6oy0IRr4HysFut5eAOpIlj8OmNE , X8LmhAUpvIkfEd7t7P1lvwwobC3JJIhUabcEs0Rn5w] and verifier to: org.scribe.model.Verifier#55ac8c3d
generating signature...
Update:
I am able to receive the oauth_verifier now. I will update this post once I am done testing.
pilot error mostly. I was able to get oauth working with twitter using scribe. After getting the service, the request Token from the service & then the authorizationUrl from the service (while passing in the request token), I was able to redirect to the authorization URL. Once there, I was able to authenticate myself against twitter using my twitter ID which redirected me to the callback URL specified when I created the service. Upon authentication, I received the oauth_verifier which I was able to use to create the verifier & then receive the access token from the service using the verifier and the request token. Then the oauth request was made & signed which resulted in the response from twitter with the user details. Worked. Hope it helps.