2015-08-24

I love how Java keeps reinventing itself to stay current and relevant (I can hear all my Node.js and Ruby friends groaning). The ecosystem that supports Java is keeping pace with new developments as well. Today, it’s as easy today to build, test and deploy a rich Java web app as quickly as in Python or Node.js (more groans).

One piece of that is Spring Boot, which makes building and launching a Java webapp in minutes a reality. Heroku’s focus on Java support also speeds things along.

Finally, Stormpath means developers don’t have to build authentication and authorization workflows. Stormpath’s identity API and single sign-on functionality (via IDSite) provide out-of-the-box account registration, login, email workflows and single sign-on across applications. These flows include default forms and views, all of which are customizable.

In this post, we will put all that together and get the added bonus of Single Signon across your applications – all within 20 minutes.

Read on – tick tock!

Here are the prerequisites you need for this tutorial:

Gradle 2.x

On Mac: brew install gradle

Heroku

Create a Heroku account

Install the Heroku Toolbelt

Login to Heroku: heroku login

A Stormpath Account (which we will also cover below)

Note: You can just as easily use Maven. The source code that goes with this post includes a pom.xml, if that’s your prefered build tool.

To make it super easy, we’ve added a handy Heroku deploy button to each example, so you can see it in action right away. If this takes you more than 20 minutes, please let us know what held you up in the comments. We love feedback.

Launch Spring Boot – 5 Minute Tutorial

This section uses the SpringBootBasic tag in the github repository.



Spring Boot enables you to fire up a fully functioning Java web application just like you would start a simple Java application. It has a main method and everything. For instance, the @SpringBootlApplication annotation does everything that the @Configuration, @EnableAutoConfiguration and @ComponentScan annotations (with their default attributes) do in a vanilla Spring application.

What makes Spring Boot work so well and so easily are Starter packages that add in functionality, including default configuration. The Stormpath Spring Boot Thymeleaf Starter we will use further on bakes in all of the Stormpath functionality for creating new users, logging in and changing passwords. All you do is reference a single jar in your build.gradle or pom.xml file.

For our basic example, we are going to include the core Spring Boot Starter Web and the Thymeleaf Spring Boot Starter. Thymeleaf is a modern HTML 5 Java templating engine.

Here’s our build.gradle:

There are three more files we need to get our basic Spring Boot app going.

IDSiteDemoApplication.java is the application’s entry point:

The @SpringBootApplication annotation sets up all the configuration necessary to launch the application.

HomeController.java maps a URI and resolves to a Thymeleaf template:

The @Controller and @RequestMapping annotations set this class up as a controller and configure it to handle requests at the / URI. Simply returning the String home hooks into the Thymeleaf template architecture which leads us to our final file:

home.html located in the templates folder is the template that will be rendered when browsing to /:

Note: You may notice the th:include directive in the template above. This is part of the Thymeleaf architecture for including files in other files. The full source code for the example has the templates/fragments/head.html file.

Alrighty, then. Let’s round out this first 5 minutes by firing up this most basic of Spring Boot apps.

gradle clean build will do the trick. Then: java -jar build/libs/idsite_demo-0.1.0.jar



Add Stormpath for SpringBoot Authentication

This section uses the SpringBootStormpath tag in the github repository.



In this section, we’ll:

Create a Stormpath Account

Generate a Stormpath API Key Pair

Add an Application to your Stormpath Account

Update your Spring Boot webapp to show some Stormpath app information

Fire it up and watch it work

Create a Stormpath Account

Go to the Stormpath Registration page. Enter your First and Last names, company, email and password.

Click Signup.

Click the link in the verification email you receive. Then, you will see the tenant name that’s been generated for you.

Login. Done.

Note: For more information on multi-tenant applications, we have a handy blog post on it.

Generate a Stormpath API Key Pair

Once you log in to your Stormpath account, you will see this screen:

Click the Create API Key button.

Click the Create API Key button and save the file.

The API Keys stored in that file are used to authenticate your application to Stormpath. In the file, there’s and apiKey.id and a apiKey.secret. You would never want the apiKey.secret exposed. So, for instance, you would never want to have the api keys file checked into a git repository. When we deploy to Heroku later on, I will show you how to configure your app to use the api keys without having to have them in the git respository.

Stormpath uses well documented configuration defaults to make working with our APIs super easy. One of these defaults is the api key file location. The Java SDK will automatically look for the file in your home directory:

If you copy the file you downloaded to that path, no additional configuration is required to connect to Stormpath from your application.

Add an Application to Your Stormpath Account

Back on the admin dashboard, click the Applications tab.

You will notice that there are two applications already present: My Application and Stormpath. They were setup automatically when you registered for Stormpath. Without any other Stormpath applications defined, no further configuration is needed for your Spring Boot application. By default, it will connect to the My Application instance already defined.

However, the ultimate goal here is to get some Single Signon goodness and in order to do that, we’ll need more than one application to sign in to.

So, let’s create another Stormpath application. Click the Create Application button.

Let’s break down the options here.

Name and (optional) description are self explanatory. And, it makes sense that we want this application Enabled.

By default, the Create new Directory checkbox is checked. For our example, I’ve unchecked this option. Rather, I’ve checked the Map Account Stores to this Application checkbox and chosen the My Application Directory. Finally, I’ve clicked the DEFAULT ACCOUNT LOCATION and DEFAULT GROUP LOCATION radio buttons.

So, what’s going on here? The way that Stormpath is organized, an application can use any number of directories as its Account Stores. A Stormpath directory is just a bucket that contains accounts and groups. For our purposes, we can use the directory that was automatically created for us when we registered called My Application Directory. In the bonus section below, I will show you how to create a specific type of directory to add Google authentication to your app. Spoiler alert: It’s super easy.

Update Your Spring Boot Webapp

Let’s hook up our basic Spring Boot app to Stormpath to show some Stormpath app information. This will lay the foundation for being able to integrate with the ID Site service.

First, we are going to add an application.properties file. This let’s us pass in the Stormpath Application identifier so we know which Stormpath Application to connect with. This will be a crucial bit of the configuration when we are deploying multiple instances of our app to Heroku.

Lines two and three disable caches so that we can play with logging in and out of multiple applications. In production, you would not want these caches disabled.

The critical line is the first one. Spring Boot will convert any command line option arguments to a property and add it in to the Spring Environment. This is documented well here.

The stormpath.application.href points to a specific Stormpath Application resource. You can find this value from the admin dshboard by navigating to your Application.

In this case, the Application ID is: 6bHOGj63WM8cfC2nhD3Pki. You’ll see below that we pass that value in on the command line. It is then de-referenced in application.properties by Spring Boot. Stormpath then makes use of the full URL to connect to our Application.

Let’s next take a look at our HomeController:

We’ve now taken advantage of Spring’s @Autowired capability to give us a handle to the Stormpath Application object. Using that, we set the Application’s name and description in the Model object which will be passed on to our template.

This brings us to our next change, the home.html Thymeleaf template:

Using the Thymeleaf notation to pull information out of the model, we are referencing [[${appName}]] and [[${appDescription}]].

Finally, we’ll make a small (but powerful) update to out build.gradle file. We are changing this line:

to this:

We’ve swapped out Spring’s Thymleaf Spring Boot Starter for Stormpath’s. Here’s the cool bit: everything needed to interact with the Stormpath Java SDK is included in this Starter.

There’s a total of 7 lines that have changed in our application files and one file, application.properties that we’ve added in order to start hooking in to Stormpath.

Build Your Java Web Application

Assuming that you put your api key file in the default location of ~/.stormpath/apiKey.properties, this is all you need to do run this example:

Of course, you would put in your own value for app.id.

You can see that the page in the browser is now displaying the information from the Stormpath Application that we created.

Stormpath Single Sign-On with IDSite…

…you guessed it. In Five Minutes.

This section uses the SpringBootStormpathIDSite tag in the github repository.

You may have had the experience of adding authentication and authorization to your applications. Maybe you did it upfront. Maybe it was something you said you’d get to – eventually. Either way it’s a pain. And, it has nothing to do with the problem you are trying to solve. It is critical and necessary, though.

In this section, we are going to add the ability to create new users, login, restrict access to a page to only those users that are logged in and change your password. And, we are going to do it with minimal coding and minimal configuration.

ID Site Configuration for SpringBoot

First, we’ll setup IDSite from the admin dashboard. Click the ID Site tab.

As you scroll around, you will notice that there are a number of fields with the label Upgrade Required. The basic ID Site functionality can be used with our free tier, as we will see momentarily. Having a custom domain or customizing the templates used for authentication requires a paid subscription.

Here. we are simply going to update two fields and save the settings.

For security, you must specify a list of URLs that are allowed to make connections to your ID Site.

Enter http://localhost:8080 in the Authorized Javascript Origin URLs field.

For the security reasons, you must specify a list of authorized redirect URLs.

Enter http://localhost:8080/restricted/id_site_callback and, on a separate line, http://localhost:8080/in the Authorized Redirect URLs field.

Click the Save button. That’s all that’s necessary to configure your ID Site to enable authentication and authorization in your app.

Let’s take a step back and use a precious 30 seconds of our 5 minutes to look at the mechanism behind ID Site.

When a user attempts to access a restricted area of your website, they will be redirected to your ID Site, IF they do not already have an active session.

They will be presented with a familiar login form complete with options to create a new user and to reset their password.

Where did this come from? Is it magic? It’s part of what you get for using ID Site – all the authentication and authorization flows that you usually write on your own. Poorly. (ouch – that was a little harsh. But, seriously – how often do you read about security breaches due to poorly implemented auth code?)

Once authenticated, they will be redirected back to the URL you specify and will be able to access that restricted content.

This process will seem utterly familiar to your users – even mundane. And you will have accomplished it with very little configuration or coding.

Update Your Spring Boot Webapp

We are going to add 50 lines of code in a new controller – total – to hook into ID Site. We will also add a new template that is restricted to people that have logged in to your application and update our home template.

Let’s take a look at that controller, Restricted Controller.

Let’s break this down method by method

getBaseURL

This private method take in an HttpServletRequest object and returns the the base of the full url pulled out of it.

If http://localhost:8080/restricted/secret is the URL, http://localhost:8080 will be returned.

idSiteStep1

This method is bound to the request path /restricted/secret. This kicks off the ID Site interaction resulting in the hosted login form for the user.

In order to be redirected properly to the ID Site, a special URL needs to be built. Fortunately, you don’t have to worry about those details. The IdSiteUrlBuilder object manages all of that for you. All you need to do is to set the callback URL in this case. When your IdSiteUrlBuilder object is all set, calling the build method returns the correct URL string to redirect to. All of the response lines in the idSiteStep1 method are preparing the response to redirect to your ID Site.

idSiteStep2

This method is bound to the request path /restricted/id_site_callback, which is what we programmed in for the setCallbackUrl method in the previous step. This is the glue tht causes ID Site to redirect back to your web app after authenticating. We are using the AccountResult object to pull the Account object out and get at the givenName, which we then pass along to the view template found at restricted/secret.

logout

The final method in this controller is logout. It creates a logout URL using the IdSiteUrlBuilder object. the forLogout method tells the builder to create a logout url. The callback that is set brings us back to the front door of the app.

Let’s take a look at the new template, restricted/secret.html:

There are two interesting lines here, from the perspective of interacting with ID Site.

This line accesses the firstName variable that we retrieved from the Account in the controller and set in the model.

This form sets the action to hit our logout method in the controller and tells it to use an HTTP POST to do it.

Finally, we are adding a single line in to our home.html template that kicks off the whole login flow:

Remember, /restricted/secret will be picked up by the idSiteStep1 method and will redirect us to your ID Site login form.

Fire Up Your Webapp and Try It Out

Start up the app as before:

Since we don’t yet have any users defined in our Stormpath directory, let’s create a new user and then make sure we can log in and log out as that user.

first, browse to the front door: http://localhost:8080

Click the friendly green button.

Click the Create an Account link.

Click the friendly green button.

Huzzah! We’re in!

If you click the green button now, you will be brought back to the home page. If you then click the green button on the home page, you will go directly to the restricted page. You will not see the login form again. This is because you have established a valid session.

If you click the red button, you will be logged out and redirected to the home page. Clicking the green button brings you to the login form once again as you have trashed your session.

You may notice that after we created our account, we were immediately logged in and sent to the restricted page. You can slow this down by requiring email verification in your Stormpath admin console as part of the account creation process.

Note: There is a known issue whereby you cannot be logged into the Stormpath Admin Dashboard and authenticate using ID Site in the same session. We are working on resolving this issue ASAP. It would never affect your users as they would never be in your Stormpath Admin Dashboard. For now, use a separate browser profile or separate browser instance when using the Stormpath Admin Dashbaord.

Single Sign-On with Heroku in 5 Minutes

This section uses the SpringBootStormpathIDSite tag in the github repository.

Note: You can use the Heroku Deploy button above to deploy two different Heroku Apps if you want to test out SSO without deploying yourself.

Phew! Home stretch! So, what’s this SSO I keep hearing so much about? With the foundation we’ve built, we are now in a position to deploy multiple instances of this web app to Heroku. So What? I’ll tell you “So What!”

While it’s a novelty that we can deploy multiple instances of the web app, what really gives it power is ID Site’s Single Signon capability. By the end of this section you will see that by logging in to one instance of the webapp, you can browse to the restricted page of another instance of the web app without having to log in again.

First, we need to add a file so Heroku knows how to launch our app. It’s a one-liner called Procfile:

Notice the bash style variables $PORT and $APP_ID. We’ll get back to these in a moment. This is part of the secret sauce that allows us to deploy the same codebase, but link the web app to different Stormpath Applications.

Let’s setup and deploy one Heroku app and make sure it all works.

Notice the --remote on the end of the command. Heroku automatically adds a git remote to your local repository in order to be able to deploy your app. By default, this remote will be named heroku. Since we will be deploying multiple instances of the app, we want different remote names.

Now that we’ve created the app, we need to set some config parameters.

Remember I said earlier one of the benefits of how Stormpath configures itself is that you are not required to embed sensitive api key information in your code? Here’s where it all comes together. In the above command, we are setting environment variables for our Heroku instance. The Stormpath SDK automatically checks for the presense of STORMPATH_API_KEY_ID and STORMPATH_API_KEY_SECRET environment variables. If present, the SDK will automatically use the values in those environment variables when interacting with the API. APP_ID is a custom environment variable that we make use of in our Procfile. It’s what connects our Spring Boot web app to the right Stormpath Application. The Procfile also has a PORT variable. This is automatically populated by Heroku and does not need to be explicitly set by us.

Ok. The stage is set. Let’s deploy our app!

This generates a ton of output, but let’s look at some of the highlights:

Toward the bottom, Heroku is discovering the process type based on our Procfile. In this case, it’s web.

Last bit of housekeeping for our first app is to configure ID Site to accept connections from it and to redirect to it. Jump back over to your admin dashboard for ID Site and add http://idsite-demo-app1.herokuapp.com to the list of Authorized Javascript Origin URLs and add http://idsite-demo-app1.herokuapp.com/ and http://idsite-demo-app1.herokuapp.com/restricted/id_site_callback to the list of Authorized Redirect URLs.

Make sure you click the Save button at the bottom of the screen.

And, http://idsite-demo-app1.herokuapp.com/ is ready to go! Check it out. Create an account. Log in and log out. Have fun with it.

We’ve now arrived at the gates of the SSO promised land. Here’s all that’s left to do:

Create another Stormpath Application

Create another Heroku Application

Set the configuration of the new Heroku Application

Deploy our Spring Boot app to the new Heroku Application

Update our ID Site to include the new URLs for authorized origin and redirect

We are just rinsing and repeating what we did before.

Let’s go create our new Stormpath Application:

Notice that we are mapping the same Account Store for this new application.

Time to create a new Heroku app:

And, configure it:

Make sure you use the App ID of the newly created Stormpath Application.

Deploy time:

Finally, ID Site URLs update:

You can now check the box on your ToDo list that says: build and deploy an SSO application. You’ve done it!

You can log in to http://idsite-demo-app1.herokuapp.com. Then, you can jump directly over to http://idsite-demo-app2.herokuapp.com/restricted/secret and you will not have to login again!

Happy SSOing!

In this post, you’ve created a Spring Boot web app that takes enables Single Sign-on with Stormpath’s ID Site service. Stormpath hosts the login form and all the other links and form associated with creating a new user and resetting your password.

With a small amount of code in one Controller, you can authenticate and authorize users for your app. And deployed it quickly with Heroku. I’d love to hear about your experience in working with the examples in this post.

If you’re interested in using more features of Stormpath in Spring Boot, here’s our Spring Boot Webapp Sample Quickstart

Feel free to drop a line over to email or to me personally anytime.

Like what you see? Follow @goStormpath to keep up with the latest releases.

Show more