Professional Documents
Culture Documents
Blog
About
Contact
First I developed a basic "magic" class for the Facebook API publicclassFacebook{
//getthesefromyourFBDevApp
privatestaticfinalStringapi_key="MYAPIKEY"
privatestaticfinalStringsecret="MYSECRETKEY"
privatestaticfinalStringclient_id="MYCLIENTID"
//setthistoyourservletURLfortheauthenticationservlet/filter
privatestaticfinalStringredirect_uri="http://www.onmydoorstep.com.au/f
///setthistothelistofextendedpermissionsyouwant
privatestaticfinalString[]perms=newString[]{"publish_stream",
publicstaticStringgetAPIKey(){
returnapi_key
}
publicstaticStringgetSecret(){
returnsecret
}
publicstaticStringgetLoginRedirectURL(){
return"https://graph.facebook.com/oauth/authorize?client_id="+
client_id+"&display=page&redirect_uri="+
redirect_uri+"&scope="+StringUtil.delimitObjectsToString(",",
}
publicstaticStringgetAuthURL(StringauthCode){
return"https://graph.facebook.com/oauth/access_token?client_id="
client_id+"&redirect_uri="+
redirect_uri+"&client_secret="+secret+"&code="+authCode
}
}
You'll need the visural-common library for some of the code above.
I want the "email" and "publish_stream" extended permissions, so that I
can get the user's email address and post updates back to their stream in
Facebook. You can customise this list with the permissions that you need.
The process of authentication is simple.
1. You create a link on your web UI (generally labelled "Login With Facebook"
or something like that) to the Facebook.getLoginRedirectURL() URL.
2. Facebook will authorise the user with the permissions you requested, and
redirect the user to your "redirect_uri" as speci ed above.
3. In a servlet or lter at your "redirect_uri" you need to
Stringcode=sr.getParameter("code")
if(StringUtil.isNotBlankStr(code)){
StringauthURL=Facebook.getAuthURL(code)
URLurl=newURL(authURL)
try{
Stringresult=readURL(url)
StringaccessToken=null
Integerexpires=null
String[]pairs=result.split("&")
for(Stringpair:pairs){
String[]kv=pair.split("=")
if(kv.length!=2){
thrownewRuntimeException("Unexpectedauthresponse"
}else{
if(kv[0].equals("access_token")){
accessToken=kv[1]
}
if(kv[0].equals("expires")){
expires=Integer.valueOf(kv[1])
}
}
}
if(accessToken!=null&&expires!=null){
UserServiceus=UserService.get()
us.authFacebookLogin(accessToken,expires)
res.sendRedirect("http://www.onmydoorstep.com.au/")
}else{
thrownewRuntimeException("Accesstokenandexpiresnotfou
}
}catch(IOExceptione){
thrownewRuntimeException(e)
}
}
}
privateStringreadURL(URLurl)throwsIOException{
ByteArrayOutputStreambaos=newByteArrayOutputStream()
InputStreamis=url.openStream()
intr
while((r=is.read())!=1){
baos.write(r)
}
returnnewString(baos.toByteArray())
}
publicvoiddestroy(){
}
}
classUserService{
//....
publicvoidauthFacebookLogin(StringaccessToken,intexpires){
try{
JSONObjectresp=newJSONObject(
IOUtil.urlToString(newURL("https://graph.facebook.com/me?access
Stringid=resp.getString("id")
StringfirstName=resp.getString("first_name")
StringlastName=resp.getString("last_name")
Stringemail=resp.getString("email")
//...
//createandauthorisetheuserinyourcurrentsystemw/dataabov
//...
}catch(Throwableex){
thrownewRuntimeException("failedlogin",ex)
}
}
}
You might also enjoy reading Blog, and comments launched for On My Doorstep...
MHTML Browser Compatibility - CSS Inlining
The 5 Minute Guice Primer
It's Oh So Quiet...
Announcing - visural-wicket
Discuss / Comment
There are 101 comments.
Alessandro on Mon, 5 Jul 2010 at 18:31
Hi, rst of all: thanks for this post.
I try it, but i get an error in the readURL method: the error is
java.lang.IllegalArgumentException: Invalid uri ...
I think that there is some not valid char in the uri (something like : or /)
Didn't you got the same error?
thanks again
Bye
Richard Nichols on Mon, 5 Jul 2010 at 22:47
No didn't get anything like that. I'm guessing your error comes
from the line "url.openStream();"?
In which case the URL can not be connected.
What's the URL that get's passed to readURL()?
(remove your secret key before posting it)
Don on Wed, 7 Jul 2010 at 10:38
Hi Richard, Thanks for writing this up!
Quick Question: what does IOUtil.urlToString do?
Don on Wed, 7 Jul 2010 at 11:41
Never mind -- I see. It must be executing the HTTP get request,
returning the result as a string, then parsing the JSON.
http://www.json.org/java/index.html
Dan on Sun, 11 Jul 2010 at 02:16
Hi,
Thanks for a great post, I implemented it for an iFrame
application, but for some reason the oauth page comes at rst
grayed, only after I press allow it returns and looks ok, Can you elaborate on
this issue?
Thanks,
Dan
Richard Nichols on Sun, 11 Jul 2010 at 02:28
Correct, Facebook doesn't allow you to implement this in an
iframe afaik, I believe as a security precaution. There are
several posts about in on Facebook's developer forum.
thanks!
Facebook API, but they seem to have made it mandatory that you redirect
the user to Facebook in the main browser page for the new API.
Joe Mansori on Wed, 8 Sep 2010 at 17:21
Does facebook o er the possibility to get a access-token that
can be stored to db and used
for the authenticated user ? e.g like twitter provides a accesstoken and access-token-secret once
the user oAuths the external app..
paul on Thu, 9 Sep 2010 at 11:54
Hey, Could you post the web.xml details for your lter. i'm
having trouble with multiple-redirects and i think my url
mapping may be incomplete.
Richard Nichols on Fri, 10 Sep 2010 at 19:57
good.
@Joe Mansori
Hi Joe, I believe that the access token that you get from
Facebook can be expired by Facebook at any time. You could
store it for later use, but you should check that it's still active
and the log the user out of your site if the token is no longer
@paul
You just need it mounted at a single URL - /fbauth
e.g.
< lter>
< ltername>FBOAuth</ lter-name>
< lterclass>com.visural.servlet.FBOAuth</ lter-class>
</ lter>
< lter-mapping>
< ltername>FBOAuth</ lter-name>
<urlpattern>/fbauth</url-pattern>
</ lter-mapping>
techkrish on Tue, 14 Sep 2010 at 08:33
Thanks for this lovely example.. really saved a lot of trouble in
implementing the OAuth protocol for Facebook.. Kudos for
sharing..
paul on Fri, 17 Sep 2010 at 09:04
Hey, is it possble that facebook have changed the reply format
of the Facebook.getAuthURL(code) request. The string splitting
decribed above does not seem to work, and i'm wondering
should the request string be treated as a 'signed_request'?
Thanks again. P
Richard Nichols on Fri, 17 Sep 2010 at 17:29
@paul Hmm, still works ok for me. What sort of data are you
seeing coming back?
am bugged with serialisation exceptions for days now when trying to use
Apache Solr CommonsHttpSolrServer within a IDataProvider
implementation. Do you have an idea how to detach HttpClient in Wicket to
avoid serialisation on it?
GReg
pol on Wed, 6 Oct 2010 at 01:52
Hi Richard,
Is it possible to auto ll the login page of facebook with your
email and password?
Thanks a lot!
Richard Nichols on Wed, 6 Oct 2010 at 02:01
@pol that's up to facebook + user's browser i.e. whether the
return encodedAuthCode;
}
</code>
The same needs to be done when building the uri in the authFacebookLogin
in the 'UserService' for the access token.
Richard Nichols on Sun, 7 Nov 2010 at 18:07
@Darren Brown - good pick up! My bad.
http://localhost:9092/register.jsp&client_secret=xxxxxx&code=xxxxx8U URL
directly do you get the same error?
client_id=MY_APP_ID&redirect_uri=http://localhost:8888/MY_APP&client_secret=MY
Invalid query
but when i enter the same url in the address bar, it returns the correct
output i.e. access token and expire time in the body. Could you guess what's
wrong?
If its related somehow, i'm trying to run this locally on the google app
engine's plugin for eclipse.
Thanks in advance.
Richard Nichols on Thu, 27 Jan 2011 at 14:39
@Ankit see Darren Brown's comment re: URL Encoding the
strings correctly
facebook. I've given the same IP in my facebook app for callback. I am using
the following url:
https://graph.facebook.com/oauth/authorize?
client_id=&redirect_uri=/oauth_redirect&scope=
(I've tried by removing /oauth_redirect too, but didn't worked)
Hope to see some positive response...
Thanks and Regards...
Richard Nichols on Thu, 3 Feb 2011 at 01:06
@Apporva
I bleieve your redirect URI must be a fully quali ed URL, e.g.
"http://www.onmydoorstep.com.au/fbauth" and be the same
URL has you registered with Facebook for your app.
aleadam on Tue, 1 Mar 2011 at 03:18
Great post! Life saver :)
Although I'm having the same issue as Nishant, i.e.,
<code>
HTTP ERROR 500
Problem accessing /auth. Reason:
javax.net.ssl.SSLHandshakeException: Could not verify SSL
certi cate for:
https://graph.facebook.com/oauth/access_token?...(etc)
</code>
It works ne on the address bar and it appeared only after encoding the URL
as suggested by Darren Brown (before, I was getting the invalid URI
exception). Working on FF 3.6.13 on ubuntu Maverick Meerkat (10.10). I do all
my development on linux so I would really appreciate any suggestion to
overcome this.
Thanks in advance,
aleadam
aleadam on Tue, 1 Mar 2011 at 17:52
Well, it seems that it's a known issue in appengine:
https://groups.google.com/group/google-appenginejava/browse_thread/thread/c19d8407128e3eae/de7ec403d542e11f?
java/browse_thread/thread/c19d8407128e3eae/de7ec403d542e11f?
#de7ec403d542e11f
So, to x the issue, I replaced the readURL() function with the following code.
I hope someone will nd it useful.
<code>
private String readURL(URL url) throws IOException {
FetchOptions opt = FetchOptions.Builder.doNotValidateCerti cate();
HTTPRequest request = new HTTPRequest (url, HTTPMethod.GET, opt);
URLFetchService service = URLFetchServiceFactory.getURLFetchService();
HTTPResponse response = service.fetch(request);
if (response.getResponseCode() == HttpURLConnection.HTTP_OK) {
byte[] content = response.getContent();
ByteArrayInputStream bais = new ByteArrayInputStream (content);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int r;
while ((r = bais.read()) != -1) {
baos.write(r);
}
return new String(baos.toByteArray());
} else {
return null;
}
}
</code>
Vineet on Sun, 6 Mar 2011 at 13:02
Thanks a ton Man!!! I was trying to write my rst FB application
but faced lot of problems due to lack of documentation over
internet. Your article helped immensely. Thanks for writing
such an article. Keep up the good work :)
Haj on Sun, 10 Apr 2011 at 00:56
Thank You, Thank you very much. This is my rst approach to
Java. I started at 09:50 am and ended at 01:55 am. I LEARNED
A LOT FROM YOU. Thank you very much!
Thank you,
-harish
Lina on Fri, 17 Jun 2011 at 05:50
Hi Richard...Thanks for your greaaaaat example... It works
hi Richard,
thanks for the great post.
My question is , with the above peace of code we are able to
get the access_token for the face book user to act on behalf of
him from our application,,,,,,,
But is there a way to have a common token for multiple social networks like
face book and twitter ... (i am able to get token for both of them separately).
thank you.
Trickmaker on Sat, 5 Nov 2011 at 13:37
Thanks for your code, let me how I can get this into my
website how i can make page only for users login through
facebook.
Sandesh on Thu, 1 Dec 2011 at 00:53
http://code.google.com/p/visural-common/
Hi Richard,
THank you very much for the post. I have a question,
Facebook is not giving me three values, how do I get the new
Login URLs?
In Facebook we have
App ID: so thi s is the API_KEY or CLIENT_ID?
App Secret: this is the secret.
So is missing one value??
thank you very much
Pedro
Karthik on Mon, 23 Apr 2012 at 03:56
I have a doubt.
http://graph.facebook.com/oauth/authorize?
client_id=%XXXXXX%22&display=page&redirect_uri=%22https://www.facebook.com
Karthik on Mon, 23 Apr 2012 at 03:57
Sorry,
client_id.
Hi
what about the get() method in UserService?
"UserService us = UserService.get();"
Just tried to use the code above. Did I miss something?
Richard Nichols on Tue, 30 Oct 2012 at 04:11
@An
UserService is just an example - I'm assuming that in your
project you have a UserService of some sort which allows to
you read / verify user accounts. If you don't you'll need to
implement one! :)
Sat on Sat, 23 Mar 2013 at 15:33
Hi Richard,
Can you please help me on the below.
callback_url =
http://localhost:18080/example/pub/social/facebook/signup/step2
OAuthService service = new ServiceBuilder().provider(FacebookApi.class)
.apiKey(apiKey).apiSecret(apiSecret) .scope("email")
.callback(callbackUrl).build();
String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
return "redirect:" + map.get("AUTHORIZATION_URL");
OAuthService service = new ServiceBuilder().provider(FacebookApi.class)
.apiKey(apiKey).apiSecret(apiSecret).build(); Veri er veri erObj = new
Veri er(veri er); //String s = getAccesstoken(veri er);
Token accessToken = service.getAccessToken(EMPTY_TOKEN, veri erObj) I
am getting below error @ last line
Response body is incorrect. Can't extract a token from this: '{"error":
Hi Rickhard,
redirect url
Thanks for the info, can you help how to call lter from
Thanks RitaSaluja
For those of you who have been wondering what is the value
for client_id: It appears that this actually is you App ID and API
key is the same value as your App ID. Source:
http://stackover ow.com/questions/4240837/facebook-api-key-same-asapplication-id
out.
Cheers!
Thanks for this post - it was the only thing that helped me out.
Even using plug and play oAuth libraries like Scribe failed for
me, but following the directions outlined here got me sorted
Hi Bro,
I trid this code but i get an error at this point can you pls help
me out this????????????
This is the line... redirect_u+"&scope="+StringUtil.delimitObjectsToString(",",
perms);
And the Error is "The method delimitObjectsToString(String, String[]) is
unde ned for the type StringUtil"
https://www.facebook.com/login.php?
loginattempt=1&next=https%3A%2F%2Fwww.facebook.com%2Fv2.2%2Fdialog%2Foauth%3F
publicclassFacebookTokenRefresh6{
privatestaticDefaultHttpClientclient
privatestaticStringFACEBOOK_ID="abcd@mycompany.com"
privatestaticStringFACEBOOK_PW="Mypassw0rd"
publicstaticvoidmain(String[]args)throwsException{
StringauthUri="https://graph.facebook.com/oauth/authorize"
Stringcallback="http://mycompany.com/"
StringclientId="1234567"
try{
//Step1:Generateshortdurationaccesstoken
OAuthClientRequestrequest=OAuthClientRequest
.authorizationLocation(authUri).setClientId(clientId)
.setRedirectURI(callback).setResponseType("code"
.buildQueryMessage()
//ItredirectsmycorrectlytotheURLthatIcontainsthecorrectcode
//Iaminterested.
//ButwhenItrytoexecutetheURLusingHttpPostfollowingcodeis
//notreturningvalidredirectURLwithcode.Cansomeonetellmewhat
//amImissinghere.
System.out.println("****************redirecturlisredirectURL
client=newDefaultHttpClient()
HttpPostrequest2=newHttpPost(redirectURL)
List<NameValuePair>parameters=newArrayList<NameValuePair
parameters.add(newBasicNameValuePair("lsd","
parameters.add(newBasicNameValuePair("email",FACEBOOK_ID
parameters.add(newBasicNameValuePair("pass",FACEBOOK_PW
parameters.add(newBasicNameValuePair("default_persistent
parameters.add(newBasicNameValuePair("charset_test"
parameters.add(newBasicNameValuePair("timezone",&
parameters.add(newBasicNameValuePair("timezone",&
parameters.add(newBasicNameValuePair("lgnrnd","
parameters.add(newBasicNameValuePair("lgnjs","
parameters.add(newBasicNameValuePair("locale","
request2.setEntity(newUrlEncodedFormEntity(parameters))
HttpResponseresponse2=client.execute(request2)
intcode2=response2.getStatusLine().getStatusCode()
System.out.println("*******************code2"
if(response2.getStatusLine().getStatusCode()==302){
StringredirectURL2=response2.getFirstHeader("
System.out.println("*******************redirectURL2
}
}
}catch(Exceptione){
e.printStackTrace()
}
}
}
Hi..
This will work on java desktop fb application? Because am
creating fb desktop application.so that am asking
I just to get the entire json data from the server of many users.
Can u able to send the code for that
Add a comment
Name
John Smith
Email
Not displayed - used for your Gravatar or to contact you later
Comment
Markdown formatted text allowed, no HTML (will be escaped).
PostComment