How’d you like to make it really easy for your users to login to your Spring Boot website?

Sure, you could implement a login system that validates users with email. But that’s a messy process with a long turnaround time.

Why not keep things simple?

Fortunately, you can add Twitter login to your website fairly easily. That gives your site SSO-like capabilities for all users who have a Twitter account.

Of course, you could still offer the email verification process to those users of yours who don’t have a Twitter account. That’s a subject for a different article, though.

In this article, we’ll go over how to implement Twitter login with Spring Boot. We’ll use Thymeleaf on the UI side.

You can see a working demo of Twitter login by checking out my demo. You can view the code for that demo on GitHub.

If you’d like to learn more, though, read on.

 

Get a Consumer Key & Secret

The first thing you’re going to need to do is get a Twitter consumer key and secret. Fortunately, that’s really easy to do by registering as a Twitter developer and creating an app.

Once you’ve created an app, view it and click on the “Keys and Access Tokens” tab towards the top of the screen. That tab will show your consumer key and secret.

twitter-developers2

You can see from the image above exactly where your consumer key and secret are located. I’ve blurred mine out for obvious reasons.

You’re going to need to copy and paste those credentials at some point, so keep that window open in the background.

 

Modify Your POM File

Now, open the IDE with your Spring Boot project. I use Eclipse because that’s the IDE that works best for me.

If you don’t have a Spring Boot project already in place, don’t worry. I’ve got the code in GitHub and you’re welcome to pull it all down and follow along with me here.

If you’re starting with your own Spring Boot app, though, you’ll need to modify your POM file. Specifically, you’ll need to add support for Twitter4J.

If you haven’t used it before, Twitter4J is a Java library that makes it easy for Java developers to use the Twitter API. It does that by abstracting all the complexities of making HTTP REST calls.

Here’s the dependency you need to add to your POM file:

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

It’s that simple. Now, your Spring Boot app has Twitter4J support.

 

Adding the Login Button

Now that we’ve got the dependency we need, it’s time to add a Twitter login button. Once again, that’s pretty easy to do because a simple Google image search will show you a variety of buttons you can use for Twitter login.

Pick the image you like best and add it to your page. Again, I’ve already added an image to my demo app so you’re welcome to just use that one as a shortcut.

twitter-login-button

It’s not enough just to add the button, though. You’ll have to make it clickable.

When users click on the button, you’ll want to fetch an OAuth token and then redirect them to Twitter for authorization.

That last sentence is basically where everything happens so let’s take it apart in some detail.

 

Getting the OAuth Token

Since users have to get an OAuth token to login with Twitter, let’s redirect them to a path called /getToken. Our own Spring Boot website will serve up that page.

Here’s what the code looks like on Thymeleaf:

1
<a th:href="@{/getToken}"><img th:src="@{/images/sign-in-with-twitter-gray.png}"/></a>

As you can see, where going to /getToken when the user clicks the Twitter login button. Next, we need to tell Spring Boot what to do when a user accesses that path.

 

The GetTokenController Class

Since the path is /getToken, we’ll define how Spring Boot should respond in a class called GetTokenController.

In this case, we want Spring to redirect to an external URL that will allow users to authorize our app to use their Twitter account. Before we do that, though, we need to get an OAuth token.

Fortunately, it’s easy to get an OAuth token with Twitter4J. Start by instantiating a Twitter object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public Twitter getTwitter() {
    Twitter twitter = null;
     
    //set the consumer key and secret for our app
    String consumerKey = "[your consumer key here]";
    String consumerSecret = "[your consumer secret here]";
     
    //build the configuration
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    Configuration configuration = builder.build();
     
    //instantiate the Twitter object with the configuration
    TwitterFactory factory = new TwitterFactory(configuration);
    twitter = factory.getInstance();
     
    return twitter;
}

Obviously, you’ll want to change the consumerKey and consumerSecret variables above to match your own credentials.

IMPORTANT: In a production-level app, you shouldn’t hardcode your credentials. Instead, reference them from a properties file so they aren’t human-readable. We’re just trying to keep things easy for this demo.

Once you’ve instantiated a Twitter object, you can use it to obtain an OAuth request token. That code looks like this:

1
RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);

Now, you’re probably asking yourself: “What’s the callback URL?” It’s the URL you want users to return to after they authorize your app to use their Twitter account.

In our case, we’ll define a path called /twitterCallback. We haven’t referenced that path in a controller yet, but we’ll do that in an upcoming step.

The code looks like this:

1
2
3
4
5
//get the callback url so they get back here
 
//go get the request token from Twitter
RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);

Of course, that assumes you’re running Spring Boot on localhost and using port 8090. If not, adjust the callback URL accordingly.

 

Setting Attributes

Since the user is going to leave our Spring Boot website and come back, we need our app to “remember” certain objects. Otherwise, it will be just like the user visiting our site for the first time all over again.

Specifically, we need to retain the OAuth request token and the Twitter object that we instantiated in the previous step. We’ll do that by storing those objects in the session.

It’s as simple as this:

1
2
3
4
5
//put the token in the session because we'll need it later
request.getSession().setAttribute("requestToken", requestToken);
 
//let's put Twitter in the session as well
request.getSession().setAttribute("twitter", twitter);

Now, when the user returns to our app, we can just pull those objects out of the session.

 

Forwarding to the Authorization URL

Now, we need to get the authorization URL. That’s the URL we’ll send the users to so that they can authorize our app with Twitter.

Once again, it’s easy as pie. Just call the getAuthorizationURL() method from the Twitter object like so:

1
twitterUrl = requestToken.getAuthorizationURL();

Now, we need to forward the user to that URL. We’ll do that with Spring’s RedirectView class.

We’ll return a RedirectView object in the method that references the /getToken path. Here’s what that code looks like:

1
2
@RequestMapping("/getToken")
public RedirectView getToken(HttpServletRequest request, Model model) {

As you can see, we’re mapping the /getToken path to the getToken() method in GetTokenController.

Here’s what the code at the end of that method looks like:

1
2
3
RedirectView redirectView = new RedirectView();
redirectView.setUrl(twitterUrl);
return redirectView;

Now, the getToken() method will redirect the user to the Twitter authorization URL. So, when users click our “Login with Twitter” button, they’ll be redirected to a page that looks like this:

twitter-login

Obviously, we need users to click the “Authorize app” button to authorize us to use the account.

No matter which button users click, though, they will eventually go back to our app with the /twitterCallback path. We’ll cover the controller that handles that path in the next section.

In the meantime, though, you can view the code for the GetTokenController class on GitHub.

 

The TwitterCallbackController Class

Now, we need a class that will handle the /twitterCallback path. That’s where Twitter will send our users once they’ve authorized our app.

We’ll handle that path in a class called TwitterCallbackController.

Here’s what we want to do in that class:

  • Make sure the user gave us the required authorization
  • Get the objects out of the session that we stored in the previous step
  • Get the OAuth access token
  • Return the user to the “You’re Logged In” page

There’s a lot to unpack there, but it’s easier than it looks.

First, we want to make sure that the user authorized us with Twitter. We’ll do that by looking at the request parameter.

  • If there’s a “denied” request parameter, then the user did not authorize us.
  • If there’s an “oauth_verifier” request parameter, then the user did authorize us.

So our controller method will begin like this:

1
2
3
4
5
6
7
8
9
@RequestMapping("/twitterCallback")
public String twitterCallback(@RequestParam(value="oauth_verifier", required=false) String oauthVerifier,
    @RequestParam(value="denied", required=false) String denied,
    HttpServletRequest request, HttpServletResponse response, Model model) {
 
    if (denied != null) {
        //if we get here, the user didn't authorize the app
        return "redirect:twitterLogin";
    }

As you can see, we’re accepting two optional request parameters with our /twitterCallback path. Those are the same two parameters (“denied” and “oauth_verifier”) that I described just above the code block.

Right out of the gate, we check to see if the “denied” request parameter exists. If so, then we redirect users back the login page because they didn’t authorize the app.

The rest of the code in the method is for people who did authorize the app.

 

Finalizing the Process

First, let’s retrieve the objects we saved in the session:

1
2
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");

Next, let’s get the OAuth access token. We can use that token so that users don’t have to go through the Twitter login process every time they return to our site (that would get annoying real quick).

Here’s the code to get the OAuth token:

1
AccessToken token = twitter.getOAuthAccessToken(requestToken, oauthVerifier);

Once we have the token, we can store it in a cookie and look for it when the user returns to the site. I’ll probably post another article about how to use cookies with Spring Boot at some point in the future.

Now, everything is pretty basic. We’ll just store the user’s Twitter screen name in the model so we can display it in the UI.

1
model.addAttribute("username", twitter.getScreenName());

Then, we’ll return the user to an HTML page that displays that screen name with Thymeleaf. Here’s what the “return” statement looks like:

1
return "twitterLoggedIn";

That will display twitterLoggedIn.html from the templates folder in src/main/resources in our source tree. A complete explanation of how to configure a Spring Boot web app can be found here.

The line in the Thymeleaf template that displays the user’s name looks like this:

1
<h3 th:text="'Congratulations! You are logged in as Twitter user ' + ${username} + '!'"></h3>

You can check out the complete source code for TwitterCallbackController on GitHub.

 

Wrapping It Up

If you want to see an example of the Twitter login in action, check out my demo.

The code for that demo is on GitHub so you can browse the code as well. That’s the same code that I cited throughout this article.

Have fun!