Skip to main content

Spring Social Facebook Authentication Example for multiple users

How to Fix Spring-Social Facebook one user per application problem.

Problem

I was working on this Accessing FaceBook Data tutorial and it was easy peasy to get it up and running. However, when I tested it for some time I realised that it only supports one user. So when the first users log in to facebook, only his details will be shared across all new sessions/users and they won’t be asked for any kind of authentication. One of the forum says that this example is supposed to demonstrate what can be done and is not intended for production use.

What is the cause of this problem?

Spring Boot autoconfigures a lot of things behind the scenes. It does autoconfigure the Facebook, LinkedIn and Twitter properties and sets up the connection factories for social providers. However,  the implementation of UserIdSource always returns “anonymous” as the user ID. Once the first Facebook connection is established the second browser will try to find a connection for “anonymous” which it finds and gives you an authorised Facebook object.

Here is the culprit code

Solution

The solution is to override the “anonymous” as the UserId for each new user/session. So for each session, we can simply return a SessionID, however, it may not be unique enough to identify users, especially if it’sh being cached or stored somewhere in a connection database.
Using a Universally Unique Identifier(UUID) would be a safer bet.So we will store a new UUID in session so it persists between different requests but is alive only till the session is valid. See the below method which does the trick.

The Complete Code

You will need to create a class say Socialconfig and make sure it is available in the classpath (src/main/java/).Find below the complete code

Follow this Video

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami