Using Twitter OAuth with Twitter4J and Shiro in Bootique

We'll be looking at the logical steps in using Twitter OAuth with the assistance of Apache Shiro. The demo app uses the Bootique Framework and the following Bootique Modules: Jersey (with Jackson), Jetty, MVC (with Mustache), and Shiro Web. The demo app is on GitHub.

We'll look at the screenshots first to get oriented on the process before looking into the logic. First our "Sign In with Twitter" button.

Next the familiar Twitter Authorization page.

Then back to the app where the user with an existing site account is logged in and new users redirected to the Account Signup Page. Account Signup Pages are of course optional.

The Logic

Now onto a review of the logic in using Twitter OAuth with Twitter4J and Shiro. Below is the initial Twitter Sign-in method when clicking the Twitter Sign In Button.

  1. We first get our RequestToken object based on our application Twitter keys which we'll be sending to Twitter in our Authentication Url.
  2. Before going to Twitter we're going to create a Session Shiro Subject with a Twitter Utility User which we'll refer back to later. A Shiro Session Subject is a much easier approach for passing in-process User data than creating a Servlet Listener or using some other HttpServerRequest-level approach.
  3. We build our authentication Url and head to Twitter.

Notice above that we first determine if we have a SocialUser object in session. That would be either a valid SocialUser or an incomplete Site Account due to a previously aborted sign-in. Our SocialUser is in the Spring Social user_connection tradition as you see in our user_social table design.

We are now authorized by our Twitter credentials to login to the site, or optionally create a new Site Account.

  1. We first handle a denied condition if the user cancels on the Twitter Authorization Request.
  2. Twitter returns an OAUTH_TOKEN key in the returned Url for Authorized users.
  3. We use that OAUTH_VERIFIER key to create an AccessToken with Twitter4J.
  4. We retrieve the SocialUser from the AccessToken and if valid, login the user with Shiro.
  5. If a first time user, we create an in-process SocialUser object and save it to our Shiro subject Session.

Site users are automatically logged in at this point, but first time users are directed to the Twitter Authorized Signup Form shown below (again).

The value of Shiro comes into play on the New Site Account form where we can use the additional information on the form to create our Shiro User and add the Shiro username to the SocialUser object (social_user.username) to establish the associated Account User SocialUser.

Posted October 23, 2017 01:03 PM EDT

More Like This Post