With more than a billion daily active users, you can be sure that a large portion of your user community is on Facebook. So why not make it easy for them to sign on to your web app with Facebook Login?

The reality is that Facebook Login is a great way to enable people to easily gain access to your website. It’s also an SSO-like solution that allows users to register without jumping through the usual email validation hoops.

In this article, we’ll go over how to implement a Facebook Login solution within your own Spring Boot web app.

As is usually the case, you can look at the full source code on GitHub.

 

Get the Facebook App

The first thing you need to do is head over to Facebook Developers and create a new app. As of this writing, you do that by selecting “Add a New App” from the “My Apps” dropdown in the upper, right-hand corner.

facebook-developers

 

It’s beyond the scope of this article to go into complete detail about how to create a Facebook app. For the purposes of this tutorial, be sure to make a note of both the Facebook App ID and App Secret.

facebook-app

 

As you can see from the image above, it’s easy to get the Facebook App ID and App Secret from the Dashboard view.

You’ll also need to set your URL and app domain. Otherwise, Facebook will reject any attempt to login from that domain.

facebook-app2

You can set the Site URL and app domain on the Basic Settings page. In this case, use localhost so you can test the app in your local environment.

 

Use Facebook4J

You could code directly against the Facebook API. But why do that when somebody has written a perfectly good Java library that makes life easy?

Even better: that library is free.

Go ahead and include Facebook4J in your project. Here’s the relevant block in the POM file:

1
2
3
4
5
<dependency>
    <groupId>org.facebook4j</groupId>
    <artifactId>facebook4j-core</artifactId>
    <version>[2.4,)</version>
</dependency>

 

The Login Controller

Next, code the “home page” controller that simply sends users to an HTML page with a big, fat Facebook login button. Here’s what that class looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Controller
public class FacebookLoginController {
     
    //starting page for Facebook login demo
    @RequestMapping("/facebookLogin")
    public String facebookLogin(Model model) {
        return "facebookLogin";
    }
     
     
    //redirect to demo if user hits the root
    @RequestMapping("/")
    public String home(Model model) {
        return "redirect:facebookLogin";
    }
}

As you can see, there’s nothing overly complicated in there. The first method just redirects users to an HTML page. The second method redirects the root to the same page.

 

The Login Page

So what does the code for the login page look like? That’s what we’ll go through here.

The short answer is that it’s nothing complicated. Basically, it just shows the user a Facebook login button and then loads another URL when the user clicks on it.

Here’s what the relevant code looks like:

1
2
3
4
<div class="col-md-12" style="text-align:left;margin-bottom:250px">
    <h3>Click the button below to sign in with Facebook</h3>
    <a href="./getToken"><img th:src="@{/images/facebook-login.png}" /></a>
</div>

Once again, that’s nothing fancy if you’ve been doing web development for even a little while. It’s basically a clickable image.

As you can see, the code uses Thymeleaf as its front-end technology of choice. That’s why the image source is coded with an @ sign and curly braces.

On the screen, it looks like this:

facebook-login

Users who click the “Login with Facebook” button will be forwarded to the /getToken URL path.

 

The GetTokenController

Next, map the /getToken URL path to a controller class. Call it GetTokenController.

In a nutshell, the method that handles the /getToken request will return a RedirectView object that forwards the user to an external site (in this case, Facebook).

Here’s what that code looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@RequestMapping("/getToken")
public RedirectView getToken(HttpServletRequest request,Model model) {
    //this will be the URL that we take the user to
    String facebookUrl = "";
         
    try {
        //get the Facebook object
        Facebook facebook = getFacebook();
             
        //get the callback url so they get back here
        String callbackUrl = "http://localhost:8090/facebookCallback";
             
        //let's put Facebook in the session
        request.getSession().setAttribute("facebook", facebook);
             
        //now get the authorization URL from the token
        facebookUrl = facebook.getOAuthAuthorizationURL(callbackUrl);
         
        LOGGER.info("Authorization url is " + facebookUrl);
    } catch (Exception e) {
        LOGGER.error("Problem logging in with Facebook!", e);
    }
         
    //redirect to the Facebook URL
    RedirectView redirectView = new RedirectView();
    redirectView.setUrl(facebookUrl);
    return redirectView;
}

There’s a lot going on in that code, so lets break it down line-by-line.

The code starts off by instantiating the Facebook4J Facebook object. We’ll cover that method separately in a moment.

The next line sets the callback URL. In this case, it’s written for a Spring Boot app that runs on a local host and uses port 8090. Change that string accordingly if you’re doing anything different.

Keep in mind, though, that the URL path for the callback string should always be /facebookCallback.

Following that, the code sets the Facebook object in the session. That way, the object can be retrieved when Facebook sends the user back to the Spring Boot web app.

The next line of code grabs the Facebook OAuth Authorization URL from the Facebook object. That’s the Facebook URL you’ll send the user to so he or she can login.

Finally, that last block of code instantiates the RedirectView object, sets the URL property in that object to the Facebook OAuth Authorization URL, and returns the object.

That means the user will be redirected to Facebook for login.

 

The Facebook Object

In the code above, you can see a method called getFacebook(). That method instantiates the Facebook4J Facebook object.

Here’s the code for that method:

1
2
3
4
5
6
7
8
9
10
11
12
13
public Facebook getFacebook() {
    Facebook facebook = null;
         
    //set the consumer key and secret for our app
    String appId = "[your app id here]";
    String appSecret = "[your app secret here]";
         
    FacebookFactory factory = new FacebookFactory();
    facebook = factory.getInstance();
    facebook.setOAuthAppId(appId, appSecret);
                 
    return facebook;
}

The code starts off by setting the appId and appSecret variables to the values of the Facebook App ID and App Secret, respectively. Be sure to set those to your own values.

The next block uses FacebookFactory to create an instance of Facebook and invokes the setOAuthAppId() method with the App ID and App Secret values passed in as strings.

Finally, the method returns the Facebook object.

 

The FacebookCallbackController Class

So what happens when Facebook authenticates the user and sends him/her back to our app? That’s handled by the FacebookCallbackController class.

Here’s what that class looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RequestMapping("/facebookCallback")
public String facebookCallback(@RequestParam(value="code", required=true) String oauthCode,
    HttpServletRequest request, HttpServletResponse response, Model model) {
     
    //get the objects from the session
    Facebook facebook = (Facebook) request.getSession().getAttribute("facebook");
     
    try {
        AccessToken token = facebook.getOAuthAccessToken(oauthCode);
         
        //store the user name so we can display it on the web page
        model.addAttribute("username", facebook.getName());
         
        return "facebookLoggedIn";
    } catch (Exception e) {
        LOGGER.error("Problem getting token!",e);
        return "redirect:facebookLogin";
    }
}   

The code starts off by grabbing the Facebook object from the session. That’s so it can be used later in the application (in this case, it isn’t used).

Next, the code gets the AccessToken object from the Facebook object. You can store that object in a cookie so the user doesn’t have to login when coming back to the site (that’s not demonstrated here, either).

The next line sets the user’s name in a model attribute called “username.” That way, it can be displayed on the page.

Finally, the code returns the string (“facebookLoggedIn”) that maps to an HTML file of the same name (“facebookLoggedIn.html”) so the user can receive confirmation of a successful login.

Here’s what that page looks like:

loggedin

 

Wrapping It Up

That wasn’t too difficult was it? Now, you can incorporate Facebook Login within your own Spring Boot app to make it easier for people to login to your site.

Be sure to check out the source code on GitHub.

Have fun!