Every API developer is looking for ways to manage their application more securely, without sacrificing speed or ease of implementing new features. To that end, we recently updated the core Stormpath product – our REST API – to Spring Boot. Along the way, we utilized a number of critical efficiencies that would be of value to anyone developing an API using Spring Boot.

Many teams find it difficult to manage authentication and access control to their APIs, so we want to share a few architectural principles and tips from our migration to make it easier to manage your Spring Boot API.

Note: Below we use the command line tool httpie (https://github.com/jkbrzt/httpie) to exercise the examples.

1. Use the @RestController Annotation

Using @RestController (instead of simply @Controller) ensures that you will return a Java Object rather than a reference to an HTML template. Like this:

Execute:http -v localhost:8080

2. Take Advantage of Automatic POJO to JSON Conversion

Spring Boot automatically converts your POJOs (plain old Java classes) to JSON for you!

Execute: http -v localhost:8080

3. Use Dependency Injection With Autowired Services

Autowiring services enables abstracting out business logic without having complex setup, configuration, or instantiation of Java Objects.

NOTE: I recently refactored the above code from using field level injection to using constructor injection. From the perspective of Spring dependency injection, the result is the same. Even one of the Spring engineers advises against field level dependency injection. TL;DR: While slightly more verbose, constructor injection is safer and more easily tested than field level injection.

This example uses Stormpath to return a personalized greeting once you are authenticated. To exercise this you’ll first need to setup a Stormpath account as outlined here. If you followed the instructions and put your Stormpath API Key file in the standard location (~/.stormpath/apiKey.properties) there’s nothing else to do!

Fire up the app and execute this: http -v localhost:8080

Next, we need to authenticate so we can move forward with our example, so we’ll exercise Stormpath’s built in OAuth 2.0 functionality to authenticate and get back a personalized message. Make sure you’ve created a user for your Stormpath application in the Admin Console. For more information on Stormpath’s OAuth support in the Java SDK and its integrations, check out our Java Product Documentation.


Once that’s done, save the Access Token for use with our application:

Now, let’s hit our application again with authentication:

Now, we get the personalized response from our Service that the Controller has access to thanks to dependency injection.

4. Layer in Spring Security

Spring Security adds an authorization layer to Spring applications that makes it really easy to determine who should have access to what. It uses a declarative configuration syntax and includes annotations to limit who can access methods based on group membership and fine-grained permissions.

If you’re interested in learning more, I’ve also written an in-depth Stormpath, Spring Boot and Spring Security tutorial. We also have a great tutorial that takes you from zero to full functioning Spring Security + Spring Boot WebMVC app in our open-source Java SDK project. Find the tutorial documentation here.

By default everything is locked down in Spring Security and the Stormpath Spring Security integration is a great example that follows this convention. To try out Spring Security with Stormpath, you simply need to apply the Stormpath integration in a configuration like so:

http.apply(stormpath()) is all that’s needed to configure the Stormpath Spring Security integration. The next two lines allow unauthenticated access to the “/” endpoint.

Let’s take a look at how this impacts a method in our controller:

In this case, there’s no need to perform the null check on the account since we know that the only way to get into this method if after authentication. For example:

We are redirected to /login since we are unauthenticated. If I use my access token as before, it looks like this:

5. Uniform Error Handling

Good API design dictates that your API returns a common response, even when something goes wrong. This makes parsing and marshalling JSON into Java Objects easier and more reliable.

Let’s try out an example. Here, we require a header called: Custom-Header. If that header is not present, an exception is thrown:

If we look at the “happy path,” all is well:

What if we don’t have the Custom-Header header?

So, what’s wrong with this? For one, it doesn’t conform to the response format we’ve already established. Also, it results in a 500 (Internal Server Error) error, which is never good.

Fortunately, Spring Boot makes this an easy fix. All we need to do is add an exception handler. No other code changes are required.

Let’s look at the response now:

Now we have the correct response, 400 (Bad Request). We also have the response in the same format as successful responses.

Bonus Tip: Try Stormpath

Stormpath offers an advanced, developer-centric Identity service that includes both authentication and authorization and can be implemented in minutes. The Stormpath REST API lets developers quickly and easily build a wide variety of user management functions they would otherwise have to code themselves, including: