Monthly Archives: August 2011

Gotchas of Authentication Flow for application on Facebook – OAuth 2.0 (2)

Facebook logo


Vietnamese: bài viết này trình bày tiếp một số điểm có thể gây nhầm lẫn trong quá trình chứng thực Facebook OAuth 2.0.


Following the first article, this one continue presenting about the cases that can make developers confused.

3. Big Facebook logo prevent redirection:

According to Facebook documents, the server must redirect users to “authorization page”  to grant permissions.

But every redirect command sent from server leads to a blank page with a big blue Facebook logo instead!
If the same URL is put directly in a browser, then it goes to the correct page.

In short, Facebook has stopped the redirection from a third-party server. The user needs to redirect themselves, or we can help them by redirecting with javascript.

4. Tricky privacy settings:

One thing developers should know is that Facebook give full privacy control to the users. A user can change permissions any time they want. It means after a user approve your application, they still can:

  • Change their email, personal information
  • Choose to not provide you their real email, but a proxy email of Facebook
  • Remove some permission of your application (for example, publish feeds on wall)

Ofcourses, Facebook provides callback functions when those permissions change. However I don’t think it’s worth the efforts to handle all of these events, at least for a quick prototype application.

5. De-authorization callback

The authorization callback is the URL that Facebook will call if a user remove your application. At that time, the application should remove all user data that they save: access token, personal information…

At first glance, this seems to be a moral requirement. But in practice, obsolete data should not be kept anyway. Believe me, Facebook data flow is fragile, and you are asking for business logic troubles if not following the rule.

Gotchas of Authentication Flow for application on Facebook – OAuth 2.0 (1)


Vietnamese: bài viết này trình bày một số điểm có thể gây nhầm lẫn trong quá trình chứng thực Facebook OAuth 2.0


The Facebook Authentication Flow is rather complicated than it seems, and not very well documented. Here are some tips that maybe helpful if you are trying to make things work:

1. Notice parameters returned from Facebook:

  • code: When Facebook returns “code” parameter in Http request to your redirect URI, it means you need to use that code to request for access token.
  • signed_request: Signed request has several children parameters. An usual presumption is that this signed request always has Facebook ID of the current user. In fact it does if your application has already been authorized by that user. If not, you need to redirect the user to the giving-permission page.
  • request_ids: is used if your application has the “invite friends” functions. This is a comma-separated string (for example: “158187550924606,158187550924608,158187550924614″). Each number in that string is ID of an invitation sent (maybe by > 1 user). So we can say that a new user can accept the invitation of more than 1 Facebook user. In fact it is, since the app request may appears like “Viet X & Nam Y has invited you to use this app“. People often find it confused because they presume that a user can only be referred by only 1 user.

2. Always ask Facebook if your access token valid:

Even if you ask user to give “offline_access” right to your application, there’s a good chance that your stored access token will get expired. How do you know? Well, the only way available now is using your access token to request something, and if it fails, ask for a new one. That’s the way it works.

sometimes it’s hard to say a thing, though simple.

(to be continued)

Fav-icon – the simple trademarks of website

Facebook Favicon

God is in the details, said the architect Ludwig mies van der Rohe. Our world is built from billions of tiny elements, which is impossible to recognize if we just look on the surface. But coming closer, even a dust may have its history.

And a fav-icon has a history itself, too.

Did you ever notice that tiny icon which appears on top of your browser page/tab, whenever you visit a website? Yes, it has a name – a favicon. I’m not going to tell you about how the standard established. I’m going to tell you what I feel: about how it’s easy to miss these icons.

As a young web developer, I did not too much, but at least some real website. And yet it’s unbelievable that I doesn’t know about the favicon until recently. Maybe my teachers in university have mention it while I’m sleeping? Don’t know.

And one beautiful day, I suddenly realize how difficult to move among my chrome tabs without seeing their icons. Then I learn about favicon and how to make them. All that costs not more than 15 minutes. Now I know how to make a favicon myself.

@sagisou: this post is for you.

Lesson learned from the Exception Filter

Long time ago, while I’m still a student, I have a chance to read Foundation of Programming“. “All exception should be captured, to show a understandable, friendly error message to customer”.

But now I realize that it’s not enough. In a recent web project, I created an exception filter to handle all exceptions popping out:

public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String errorMessage = "";

		try {
			chain.doFilter(request, response);
		} catch (SessionExpiredException e){, e);
                    errorMessage = "Your session has been expired";
		} catch (InvalidFacebookIdException e) {
                   // ...
		} catch(FacebookAccountAlreadyRegisteredException e) {
                   // ...
		} catch (Exception e) {
                   // ...

Do you notice the duplicate code? At any exception caught, the system must log the error, compose the mesage, then redirect to the error page.There are more than dozen of exceptions like that. How can we “clean” the code?

Thanks bro Tinh, here’s a (customized) solution:

public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		try {
			chain.doFilter(request, response);
		} catch (Exception e) {
                   errorMessage = e.getMessage();
                   log.error("Error occur: " + e.getMessage(), e);

All errors now are caught in one place: general Exception instead of concrete type.Two problems remain:

  • How to catch the right exception, because they are wrapped by Servlet Exception.
  • Guarantee all Customized Exception have a message

The answer for the first question:

private String getUsefulMessage(Exception e) {
Exception default = e.getMessage();
do {
if (e.getClass().getName().equals(InvalidFacebookId.class.getName())) return e.getMessage();
// ... same for other exceptions
e = e.getCause();
} while(e.getCause() != null);

return default;

It’s the same, yes, for logic. But the later is more clearer.

The second question is more about coding policy than a technical problem, so I leave it out. In the case of our team, we decide that each exception should have an understandable getMessage().

Keeping shape in high pressure


/* Vietnamese: Một vài cách để chống stress dành cho lập trình viên khi làm việc với cường độ cao */

In programming community, working under high pressure is often a “must have” ability. Here list some of my tips to maintain good conditions in those situation:

Take some rest: Keep in mind that a weary brain do more harm than good things. Men are no machine. If you are trying to get a bug solved, things may turn out that you created even more bugs.Don’t take quick fix: a common situation is that before an important release, we are inclined to take hot-fix. A hard-code message, a magic number, which seems no harm at the moment, will cause you BIG trouble later.

Be assured, in those time, you are inclined to make errors more than anytime. Be careful even to the log message, or you will find yourself among lots of trash code later.

Sleep enough: easy to say, but hard to do. IT guys often feels good working at the night: the network is fast, no intervention… But I still think working too late is a bad idea. 8 hours a day is enough – if you want to maintain health.

Supply foods: Brainstorming requires much of energy, just like physical activities. This item even more important if you can’t guarantee the time of your sleeps. Prepare some snacks, noodles if you’re going to work overtime. You will not regret it.

Stay cool: Keeping a calm emotion is important. No matter how important a release is, it’s surely not the end of world. When I began working, I feels great pressure everytime a bug pop out near our deadline. But my seniors are different. They solve the problem step by step. And in the end, everything is just fine.

Dependency Injection

/* Vietnamese: Bài viết này nhằm mục đích giải thích một cách đơn giản nhất khái niệm Dependency Injection – một khái niệm mới mẻ những đã khá phổ biến trong thế giới lập trình hiện nay */

To my readers (if there’s any yet): I have written this blog for a while. At first, it should reflect my learning process – not all, but every post is a mark somehow. For over half of a year, now I think it’s best to make many short posts instead of lengthly ones. Thank all of you for your support.

Dependency Injection is a fairly new concept. Its origin can be traced back to Rod Johnson – the founder of Spring Framework. But we won’t go to history lesson now, let’s skip to the content itself.

The basic idea of “Dependency Injection” lies on the problem: how we should manage the dependency between modules(in the simplest case, object) in a large system.

An object should not initialize its dependencies. Dependencies of an object should be given to it by the environment.

Let’s see the following example:

Naturally, when a module A(Printer) need module B(PaperService), the original OOP thinking styles should produce something like this:

class Printer {

PaperService paperService;

public Printer () {

paperService = new PaperServiceImpl();




But by Dependency Injection way, it should be like this:

 class Printer {

PaperService paperService;

public Printer(PaperServiceImpl service) {

this.paperService = service;