You are on page 1of 67

Richard Nichols

Blog

About

Contact

Implementing Facebook OAuth 2.0


Authentication in Java
Previous Next

Published Wed, 30 Jun 2010 101 comments

I recently switched onmydoorstep.com.au's Facebook


login feature from the old "Facebook Connect" API implemented with
facebook-java-api over to the new Facebook Graph API / OAuth 2.0
authentication.
This was far easier to implement than the original authentication, particular
under Apache Wicket, but it should be easier regardless of your Java
framework of choice.
Here's how I did it.

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

Retrieve the request parameter "code"


Make another request to the URL Facebook.getAuthURL(request.getParameter("code"))
Parse the response for the "access_token" and "expires", assuming that it
was a valid response that contained them.
4. You use your access token to retrieve data about the user and/or make
other calls to the Facebook Graph API
Due to the way Apache Wicket works, I implemented a Servlet Filter for the
"redirect_uri" (/fbauth) publicclassFBOAuthimplementsFilter{
publicvoidinit(FilterConfigfc)throwsServletException{
}
publicvoiddoFilter(ServletRequestsr,ServletResponsesr1,FilterChain
HttpServletRequestreq=(HttpServletRequest)sr
HttpServletResponseres=(HttpServletResponse)sr1

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(){
}
}

This is a cut-down version of my actual code as I do a bunch of other things


on onmydoorstep.com.au which is more related to internal house-keeping
and UX.
Your "UserService" might look something like -

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)
}
}
}

So, just to recap, the sequence of authentication is as follows -

1. User clicks a link on your site to Facebook.getLoginRedirectURL()


2. Facebook asks them for their username/password to log in to your
application
3. Assuming they authenticate with Facebook, Facebook then redirects the
user to your "redirect_uri" with a parameter "code" passed along.
4. You use the "code" parameter to query the Facebook authentication service
- Facebook.getAuthURL(request.getParameter("code"))
5. Assuming it was a valid authentication code, Facebook will pass you back
an "access_token" that you can use to access the Facebook Graph API for
the given user.
This could certainly be formalised into a reusable chunk of code. I may get
around to adding it to visural-common, but right now there's a lot of
onmydoorstep-speci c stu in the real code.
Anyhow, hope it helps someone out!

About the Author


Richard Nichols is an Australian software engineer with a
passion for making things.
Follow him on twitter or subscribe by RSS or email.

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.

Richard Nichols on Wed, 7 Jul 2010 at 17:23


Correct, it's part of the code.google.com/p/visural-common
library, and just opens a connection to the URL, reads the
result and returns it as a string.
bobo on Fri, 9 Jul 2010 at 18:23
Hi
Thank you for this blog to shed a light about java
implementation with Facebook OAuth2.0.. I'd like to test and
try this approach. Can you specify which library JSONObject is from?
Richard Nichols on Fri, 9 Jul 2010 at 18:26
The JSONObject is from the json.org Java implementation -

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.

bobo on Mon, 12 Jul 2010 at 16:36


Thanks, Richard!
According to Graph API, the publishing to FB is needed to post
a form targeting https://graph.facebook.com/pro le_id/feed.
My situation is a servlet or lter would formulate a message and then post it
to FB. Whthin a servlet or a lter, I would like to know how to mimic posting a
form with HttpServletResponse back to the url above. Beside using Apache
HttpClient or out.write( a html form), is there a bettter way to handle it?
Richard Nichols on Tue, 13 Jul 2010 at 07:43
HttpClient is a fully featured solution, but might be overkill. I'm
considering adding a simple solution to visural-common for
this and covering in a future blog post. Something along the
lines of - http://www.devx.com/Java/Article/17679/1954

bobo on Wed, 14 Jul 2010 at 14:29


I used GAE library HTTPRequest and URLFetchService to solve
the problem. But, I am looking forward to seeing your
solution.
Thanks again.
Rachel on Fri, 16 Jul 2010 at 05:51
I just wanted to say- thanks so so so much.
Your post is a ray of sunshine in the sea of crappy
misinformation that is programming with java and facebook.
Keep 'em coming!
Sam Edwards on Fri, 16 Jul 2010 at 22:09
Thanks, this was a really good article and helped a bunch,

thanks!

felix on Sat, 17 Jul 2010 at 07:20


Hi richard,
Thanks for the api.
I've implemented a the graph authentication mechanism and
i'm able to get an access token. however facebook does not
redirect me to the url i speci ed in the 'redirect_url' but instead displays the
token on the 'https://graph.facebook.com/oauth/access_token?.*' page.
where could the error be.
regards.
Richard Nichols on Sat, 17 Jul 2010 at 18:33
Correct, the client doesn't get redirected to the redirect_uri

when receiving the access token - it's just to prove to facebook


that you are the originator of the original request.
The user (client browser) would have been redirected to the
redirect_uri (at which you place the servlet lter) in the
previous step (3). In step 4, your servlet lter on the server side accesses the
access_token URL to retrieve it to make subsequent requests to the graph
API.
kike on Thu, 12 Aug 2010 at 14:50
hi, im working with a facebook apps with netbeans an i cant
get the authenti cation values of code, and acces token, i read
your code and i have a problem with this line:
if (StringUtil.isNotBlankStr(code))
because i dont know where you de ne that object
i need you help please.
Regards

Richard Nichols on Thu, 12 Aug 2010 at 17:15


@Kike
StringUtil is part of the visural-common library, you can
download it at http://code.google.com/p/visural-common/
Anthony on Mon, 30 Aug 2010 at 02:56
Hi Richard,
Thanks all for your great article.
I need some helps about which mecanism is necessary between my client
side (in Flex - AS3) and my server side (in JAVA - with Spring) to make a
Facebook authentication ? I do a Facebook application, so, when Facebook
plateform launch my application, which authentication mecanism should be
done ? My Flex app client, must just call a service (on server side), and in this

service can I do the same way like in this article ?


Thank you very much,
Best regards
Anthony
Richard Nichols on Mon, 30 Aug 2010 at 04:52
@Anthony
I don't think the set up described in this article would work for
you. I don't know much about Flex, but the above
authentication relies on redirecting the client through
authentication pages on Facebook's site, so it only really works for traditional
websites.
I'm not able to advise on the best option for Flex, so I'd suggest the Facebook
developer portal is probably the best place to start.
HTH

Anthony on Tue, 31 Aug 2010 at 03:12


Hi Richard,
Just a question : why not used the OAuth Java Library instead
your implementation ? What is the best approach ?
Thanks Richard,
Anthony
Richard Nichols on Tue, 31 Aug 2010 at 05:23
@Anthony
OAuth 2.0 and OAuth 1.0 are very di erent in how they
operate.
OAuth 2.0 (at least Facebook's implementation) is quite simple (as you can
see with the amount of code above needed to implement it). Unlike with the

original OAuth, I don't think a fully edged library is needed.


ali on Fri, 3 Sep 2010 at 14:38
hey richard, thanks a lot of the e ort!
I'm trying to implement the same functionality but for a
facebook application which is using Iframe.
when I redirect to
https://graph.facebook.com/oauth/authorize from the application within the
facebook it shows a blank page. do you know of anyways how to achieve this
for an iframe application?
thanks again
Richard Nichols on Fri, 3 Sep 2010 at 17:10
@ali
No, as far as I know the OAuth 2.0 authentication method
doesn't allow this. It was possible previously with the old

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?

Khoo Chen Shiang on Sun, 19 Sep 2010 at 10:19


It's seems to me whenever we requesting for user to grant us
"o ine" permission, the auth response does not return with
"expires" parameters, thus the string splitting function will not
work..
Commnet here in case some one facing similar situation
Anyway, thanks for sharing.
Richard Nichols on Sun, 19 Sep 2010 at 19:53
@Khoo Chen - thanks for the info - that makes a lot of sense.

pol on Tue, 28 Sep 2010 at 23:56


Hi Richard,
Can I view the Facebook login page in a widget or iframe?
Thanks.
Richard Nichols on Wed, 29 Sep 2010 at 01:45
@pol - no as mentioned before it needs to render in a
dedicated browser window for security.

pol on Wed, 29 Sep 2010 at 02:28


Is it possible to make a replicate of facebook login in java and
view it on widget?
Thanks a lot.
Richard Nichols on Wed, 29 Sep 2010 at 02:38
@pol if it were possible I would guess it would be against the
Facebook API's terms of use. The user is redirected to
Facebook so that they know they're giving their login details
securely to Facebook, not to your site.
dibosh on Sat, 2 Oct 2010 at 12:46
hi,
I'm developing a desktop java IM client for facebook(its my CSE

year-2 term nal project,so thats obvious how much i am


intended to do it!)..i am trying to use facebook-java-api...but i am in deep
water to nd a way about how to log in using my app!? is there an api for
login that i need to use in my java code?i have api key & secret key for
my app..what i need is very simple..a gui that requests user to enter his
facebook mail id & password,then my app will allow him to chat in
facebook through itself...i am running out of time..& really in a x....is
there anyone kind enough to show me the perfect way to do so...i will be
greatfull.i've gone through a lots of examples but all of them are on servlets
or needs to access through website.I need to build something like pidGin or
eBuddy mobile messenger...all i need is just a perfect example to login as i
stated...looking forward to having a great response....
thanks in advancedibosh
Greg on Sat, 2 Oct 2010 at 19:03
Hi Richard,
You mentioned using Apache HttpClient for http requests. I

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

browser is set to remember / auto- ll elds

Richard Nichols on Wed, 6 Oct 2010 at 02:03


@Greg you could detach it to a HttpSession parameter technically putting non-serializable stu in HttpSession is
against servlet spec, but unless you're clustering w/ session
replication it shouldn't cause any issues
Itay on Sun, 31 Oct 2010 at 10:57
Hi,
I'm trying to build an app that login with my
username&password to facebook, and just get the HTTP
src of the home page (or a user object if it simpler to get the
info from there).

do i need to use the app key / secret key / whatever?


can i use the code above?
there shouldn't be a place for putting my password?
i will appreciate if you could provide some simple main just to run things
out.... cause those classes doesn't tell me a lot...
thanks in advance!
Richard Nichols on Tue, 2 Nov 2010 at 19:34
@Itay the above code is for the Facebook Graph API for
applications to authenticate via Facebook.
You may want to do some background reading before diving
in - I'd suggest starting at
http://developers.facebook.com/docs/authentication/
Darren Brown on Sun, 7 Nov 2010 at 01:55
Hello Richard,

This tutorial is superb! @Allessandro and maybe one small


improvement. It turns out that the accessToken and the
authCode can sometimes cause trouble if they are not URL
encoded. I believe that this was why he was getting this invalid
uri error. So I would throw in some utf8 encoding and encode
the authCode when building the AuthURL. Something like this:
<code>
public static String getAuthURL(String authCode){
return "https://graph.facebook.com/oauth/access_token?client_id=" +
client_id+"&amp;redirect_uri=" +
redirect_uri+"&amp;client_secret="+secret+"&amp;code="+encode(authCode);
}
public static String encode(String authCode) {
String encodedAuthCode = null;
try {
encodedAuthCode = URLEncoder.encode(authCode, "UTF-8");
} catch (UnsupportedEncodingException e) {
// This should never happen, we have speci ed UTF-8 correctly, Log error
}

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.

Nishant on Mon, 13 Dec 2010 at 15:34


Weirdly, I am getting this exception
HTTP ERROR 500
Problem accessing /register.jsp. Reason:
sun.security.validator.ValidatorException: PKIX path building
failed: sun.security.provider.certpath.SunCertPathBuilderException: unable

to nd valid certi cation path to requested target


Caused by:
javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path
----------At line
InputStream is = url.openStream();
where url is https://graph.facebook.com/oauth/access_token?
client_id=xxxx&amp;redirect_uri=http://localhost:9092/register.jsp&amp;client_secret=xxxxxx
Not sure what's going wrong.
Richard Nichols on Mon, 13 Dec 2010 at 15:37
@Nishant if you hit the

http://localhost:9092/register.jsp&client_secret=xxxxxx&code=xxxxx8U URL
directly do you get the same error?

Nishant on Tue, 14 Dec 2010 at 05:05

I guess you meant, http://localhost:9092/register.jsp?


code=2.4xxxCA -- yeah It throws the same exception. I
basically have one HTML that contains the link same as you
provide by getLoginRedirectURL() and the redirect_uri points
to the http://localhost:9092/register.jsp, which is same as FBOAuth lter. The
error is thrown in FBOAuth#readUrl at InputStream is = url.openStream();
However when I try, https://graph.facebook.com/oauth/access_token?
client_id=xxx&amp;client_secret=xxx&amp;code=xxx&amp;redirect_uri=http://localhost:9092
in browser, it shows access token etc, correctly. Weirdly, it seem to be
machine issue -- so I tried this <a
href="http://blogs.sun.com/andreas/entry/no_more_unable_to_ nd"
rel="nofollow">No more 'unable to nd valid certi cation path to requested
target'</a> It does not help either.
Finally, as last try, I tried on Windows. The code seem to be working. But I am
unsure why it does not work on Ubuntu Karmic Koala (9.10)
Marten on Wed, 22 Dec 2010 at 10:20

Great great post sir! Thanks a lot!

jagan on Thu, 30 Dec 2010 at 12:46


Hi,
Thanks for the great post. i am getting
"java.security.AccessControlException: access denied
(java.net.SocketPermission graph.facebook.com:443 connect,resolve)"
exception. Do you have any solution for this problem? Thanks again.
iteezy on Wed, 12 Jan 2011 at 10:01
Greate post. Keek up the good work. I was looking for simple
OAuth solution and here it is!

remus on Wed, 19 Jan 2011 at 03:18


really nice. I started researching about fbconnect and have a
question: how will you know that the user logged out from
facebook and now he requests a page from your site?
rachel on Fri, 21 Jan 2011 at 02:26
thank you very much

Richard Nichols on Tue, 25 Jan 2011 at 16:45


@remus you can store the access-token against your users
session and periodically make a facebook graph API call with
the token. If Facebook response that the token is no longer
valid then you can log them out of your site, if you wish.

Ankit on Thu, 27 Jan 2011 at 08:34


hey,
I got the same error as Alessandro, i.e.
Invalid uri 'https://graph.facebook.com/oauth/access_token?

client_id=MY_APP_ID&amp;redirect_uri=http://localhost:8888/MY_APP&amp;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

Ankit on Fri, 28 Jan 2011 at 00:44


That works! this never crossed my mind. Thanks a ton.

Apoorva Pralkash on Tue, 1 Feb 2011 at 07:28


Hello Nichols,
Great post... I am making a Liferay portlet, for fetching
facebook data...
I'm getting some problem in authentication...
Everything seems to be working ne on my machine, but when I am using it
over LAN(throught my IP followed by my server port), it is going in a in nite
loop and then message appears - connection to the server was reset. In the
mean time, in status bar, it shows repeatedly connecting/connected to

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=&amp;redirect_uri=/oauth_redirect&amp;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!

Ranjeet Ranjan on Tue, 12 Apr 2011 at 19:29


Nice information

harish kumar v on Mon, 9 May 2011 at 11:51


Hi guys, this example shows using facebook api on servlets
but could any one help me to create a similar on a desktop
application????

Thank you,
-harish
Lina on Fri, 17 Jun 2011 at 05:50
Hi Richard...Thanks for your greaaaaat example... It works

c0ooo00ll... but I have a strange problem and I can't gure it


out!!!
Whenever I run the sample code I have to sign in with the
"Owner Account" of my application to get the access_token ,
otherwise it throws exception "java.lang.RuntimeException:
Access token and expires not found" . Do you have any idea what the
problem might be?
thaaaaaaaaaaannxxxx
Lina on Wed, 22 Jun 2011 at 06:25
Ok the problem is solved but I don t know how :-D
just a small improvement to what Khoo Chen Shiang said... Yes
if you use o ine_access permission for the application , the
Try block will be changed. My teammate wrote the code for
the o ine mode.
try{
String code = request.getParameter("code");

String accessToken = null;


if (StringUtil.isNotBlankStr(code)) {
String authURL = Facebook.getAuthURL(code);
URL url = new URL(authURL);
String result = Facebook.readURL(url);
String[] pairs = result.split("=");
accessToken = pairs[1];
}
gourab on Sat, 2 Jul 2011 at 23:46
Nice article.

Vitor on Fri, 2 Sep 2011 at 07:32


Thanks for the post.

Helped me a lot. It explains a lot of things that i couldn't nd


on other websites.

Herman A. Junge (@hermanjunge) on Fri, 16 Sep 2011 at 21:37


I could be able port your logic to #nodejs.
Thank You!
Devinka on Mon, 24 Oct 2011 at 06:06
Thank you very much for the tutorial, This works ne

mahesh burra on Fri, 4 Nov 2011 at 01:10

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

Thanks for above example.


But FB will give access_token &amp; expires after
authentication.
After expires time can we access FB using same access token?
Pablo on Tue, 31 Jan 2012 at 18:34
Hi richard, congratulations for this excellent tutorial. I'd like to
ask you what libraries or Binaries you did use for reading the
"inputStream" from the JSONObject response (resp), i saw you
used "IOUtil" (IOUtil.urlToString(new
URL("https://graph.facebook.com/me?access_token=" + accessToken)))) , BUT
i can't nd it. I'll appreciate you rhelp, thanks.
Richard Nichols on Thu, 2 Feb 2012 at 23:57
@Pablo

http://code.google.com/p/visural-common/

Pablo on Sat, 4 Feb 2012 at 19:25


Thank you again, it works perfectly

Ebenezer Akansah on Fri, 16 Mar 2012 at 07:31


hi everybody.. im new to the whole programming gig n i need
loads of help.. ive been given a project to create a j2me chat
app, sumtin lyk ebuddy n i dnt know where to start.. can
anybody help me?? im dying here. tanks in advance..
Peter Fields on Wed, 28 Mar 2012 at 00:08

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.

I created a new app on FB and added the site url as


"http://localhost:8080/&lt;&gt;". But when i try to call the
loginRedirect, i get the error, "redirect_uri isn't an absolute
URI. Check RFC 3986."

http://graph.facebook.com/oauth/authorize?
client_id=%XXXXXX%22&amp;display=page&amp;redirect_uri=%22https://www.facebook.com
Karthik on Mon, 23 Apr 2012 at 03:57
Sorry,

the url is this one,


https://graph.facebook.com/oauth/authorize?
client_id="XXXXXXX"&amp;display=page&amp;redirect_uri="http://127.0.0.1:8080/&lt;&gt;/get
Malathy on Thu, 17 May 2012 at 03:33

Really nice article.


I have an issue with auth code.
I am not able to fetch the auth code from the redirected URL,
though can see it in the browser.
The below line of code returns null to me.
String code = sr.getParameter("code");
Can you please help me on this regard.
Pedro on Sun, 17 Jun 2012 at 19:43
How to know if the user is already logged on (using server
side)? is there a way to logout using Server Side call?
sandeep srivastav on Sun, 8 Jul 2012 at 12:12
Please let me know, what is client_id in this program.
Because when i registered one app in facebook, i did not get

client_id.

akhil patil on Wed, 1 Aug 2012 at 09:19


Thanks a lot! im starting with this stu about facebook api.i
think it will prove to be useful.
Ashutosh Chia on Tue, 28 Aug 2012 at 07:44
Hello! I've been reading your web site for a long time now and
nally got the courage to go ahead and give you a shout out
from Lubbock Texas! Just wanted to mention keep up the
fantastic work!
An on Mon, 29 Oct 2012 at 17:47

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":

{"message":"redirect_uri isn't an absolute URI. Check RFC


3986.","type":"OAuthException","code":191}}'
Settings n facebook app :
Website with Facebook Login : http://localhost:18080/example/ App domain :
localhost Kindly let me know if I am wrong anywhere...New to scribe and
facebook platform

Rita on Wed, 10 Apr 2013 at 02:58

Hi Rickhard,
redirect url

Thanks for the info, can you help how to call lter from

Thanks RitaSaluja

Nikolai Konovalov on Sat, 13 Apr 2013 at 21:37

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

Hurray on Mon, 29 Apr 2013 at 14:25

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

Nithin M on Tue, 10 Sep 2013 at 05:19

Thank you for this post.I am working on desktop version to


retrieve facebook page access token using java .I have App ID
and App Secret but i am not able to nd a good link that will
guide me to implement it.I have some knowledge on How facebook graph
API works.Please can you help me to implement a method that will retrieve
facebook page access token using App ID and App Secret parameters .Thank
you.

venkata krishna on Fri, 22 Aug 2014 at 08:43

Hi richard, clientid and appkey is same or not


i want to know how to call and where to call our methods in
our class like getloginurl(),andgetAuthurl()... please let me know ...iwant to
use in my project

Hemanth on Thu, 16 Oct 2014 at 02:15

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"

Noobcanon on Wed, 26 Nov 2014 at 15:36

Is there a maven download for this example?

Alchemist on Sat, 13 Dec 2014 at 08:23

Is it possible to implement above feature using just java.


I tried following but not working: GOAL: code: To obtain
Facebook OAuth code which can be used to renew token.
I am trying to automate refreshing FB token. My goal to execute Oauth
generated URL using HTTPPost and get the code. But when I run this
program it does not return the code.
Main question that I have is that: How do we call HttpPost to execute a URL
that requires login. In this case
Result of URL obtained from Step 1 below: I am trying to execute a oauth
token https://graph.facebook.com/oauth/authorize?
responsetype=code&redirecturi=http%3A%2F%2Fmycompany.com%2F&client_id=123456
URL to get the code but this
Goal of step 2 (automation of running step 1 that internally requires

authenticating user by verifying user using facebook login) URL redirects to


facebook login page to authenticate user

https://www.facebook.com/login.php?
loginattempt=1&next=https%3A%2F%2Fwww.facebook.com%2Fv2.2%2Fdialog%2Foauth%3F
publicclassFacebookTokenRefresh6{
privatestaticDefaultHttpClientclient
privatestaticStringFACEBOOK_ID=&quotabcd@mycompany.com&quot
privatestaticStringFACEBOOK_PW=&quotMypassw0rd&quot

publicstaticvoidmain(String[]args)throwsException{
StringauthUri=&quothttps://graph.facebook.com/oauth/authorize&quot
Stringcallback=&quothttp://mycompany.com/&quot
StringclientId=&quot1234567&quot
try{
//Step1:Generateshortdurationaccesstoken
OAuthClientRequestrequest=OAuthClientRequest
.authorizationLocation(authUri).setClientId(clientId)
.setRedirectURI(callback).setResponseType(&quotcode&quot
.buildQueryMessage()

//STEP 1 generate URL String url = request.getLocationUri();


//WhenirunthisURLmanuallyinbrowserandaddmyemailandpassword.
//ItredirectsmycorrectlytotheURLthatIcontainsthecorrectcode

//ItredirectsmycorrectlytotheURLthatIcontainsthecorrectcode
//Iaminterested.

//ButwhenItrytoexecutetheURLusingHttpPostfollowingcodeis
//notreturningvalidredirectURLwithcode.Cansomeonetellmewhat
//amImissinghere.

//Automation of step 1 that internally redirects to fb login page. Can


someone please help me gure //out what am I missing here. Any help or
hint is greatly appreciated.
HttpPostoauthPost=newHttpPost(url)
client=newDefaultHttpClient()
HttpResponseresponse=client.execute(oauthPost)
intcode=response.getStatusLine().getStatusCode()
System.out.println(&quot*******************code&quot+code
if(response.getStatusLine().getStatusCode()==302){
StringredirectURL=response.getFirstHeader(&quotLocation&

System.out.println(&quot****************redirecturlisredirectURL
client=newDefaultHttpClient()
HttpPostrequest2=newHttpPost(redirectURL)
List&ltNameValuePair&gtparameters=newArrayList&ltNameValuePair
parameters.add(newBasicNameValuePair(&quotlsd&quot,&quot
parameters.add(newBasicNameValuePair(&quotemail&quot,FACEBOOK_ID
parameters.add(newBasicNameValuePair(&quotpass&quot,FACEBOOK_PW
parameters.add(newBasicNameValuePair(&quotdefault_persistent
parameters.add(newBasicNameValuePair(&quotcharset_test&quot
parameters.add(newBasicNameValuePair(&quottimezone&quot,&

parameters.add(newBasicNameValuePair(&quottimezone&quot,&
parameters.add(newBasicNameValuePair(&quotlgnrnd&quot,&quot
parameters.add(newBasicNameValuePair(&quotlgnjs&quot,&quot
parameters.add(newBasicNameValuePair(&quotlocale&quot,&quot
request2.setEntity(newUrlEncodedFormEntity(parameters))
HttpResponseresponse2=client.execute(request2)
intcode2=response2.getStatusLine().getStatusCode()
System.out.println(&quot*******************code2&quot
if(response2.getStatusLine().getStatusCode()==302){
StringredirectURL2=response2.getFirstHeader(&quot
System.out.println(&quot*******************redirectURL2
}
}
}catch(Exceptione){
e.printStackTrace()
}
}
}

bg on Mon, 24 Aug 2015 at 07:31

Do we have similar implementation of oauth2.0(three-legged)


for linkedIn API.

thameem on Wed, 14 Oct 2015 at 01:19

Hi..
This will work on java desktop fb application? Because am
creating fb desktop application.so that am asking

Richard Nichols on Wed, 14 Oct 2015 at 04:14

No, the protocol requires a server portion in order to work.

Syed Jameer on Sat, 2 Jan 2016 at 02:18

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

2014 Richard Nichols

All Posts | search...