How to Post a Secure Spring Boot App to Heroku
Join the DZone community and get the full member experience.Join For Free
As a developer, I know better than anyone the ideas for pet projects and big plans that can arise in fits of enthusiasm. However, instead of reacting to these goals, I find myself working on the same mundanity that I was the previous week. It can be hard to find the motivation to actually begin a project—really begin it, not just deployment, user sign in, registration, etc. No one enjoys the repetitive nature of user registration and login forms, and they can make your intention seem like an unlikely dream.
In the beginning, user sign-up forms were… fun. However, as I move forward, I see more and more boilerplate, consisting mostly of copypasta between projects, with only minor changes.
Thankfully, we have access to tools such as PaaS, laaS, and open source. With the basics already built, we only need to connect them in order to spend our time and energy on the delivery for the end-user and unique features.
Although the many options are available to bootstrap a new project, the amount can be difficult to choose from in order to match the right components.
Build a Secure Spring Boot Application
Your website will invite a user to log in and then will present them with some meaningful information, for example, give The Answer.
Tools you’ll be using:
- Spring Boot - agile and time-tested all-in-one suite for the web and REST API development framework with countless integrations and much more.
- Spring Security - swiss knife for the various security setups which provides great flexibility and control all over the application. You’ll be using its OAuth 2.0 module.
- Kotlin - fastest-growing statically typed language which is gaining adoption in different applications.
- kotlinx.html - an HTML-like DSL (domain-specific language) helping developers to build type-safe applications.
- Okta - easy to use authentication and authorization service provider, you’ll offload user management to this service
- Heroku - PaaS provider making deployment process as smooth as possible.
Since you won’t handle authentication and won’t store any personal data, that significantly helps to be compliant with GDPR, CCPA, and other government regulations, as Okta already takes care of that.
Spring Boot has first-class support for Kotlin, easing out potential challenges in some corner cases. Okta provides a very handy autoconfiguration
okta-spring-boot-starter, similar to
spring-boot-starter-web which automagically sets up most of the components for you. With Heroku, you’ll be able to deploy the whole application with a simple
Scaffold a New Spring Boot Project
You can create a project skeleton with a standard directory layout and basic dependencies configured. However, configuring Spring manually can be convoluted, and leave you with cryptic errors just because a dependency was or wasn’t included. Fortunately, Spring Initializr can help with that. It’s a neat online tool giving you an option to set up all dependencies of the project automatically. I prepared a magic link which preselects project’s components.
Should you prefer to select the dependencies yourself, choose options as displayed in the screenshot below:
The Spring Initializr website will generate a zip archive that you’ll need to download, decompress, and import in your favorite IDE.
Touch Up Gradle Dependencies
Although most of the required dependencies are there, you’ll need to add the
kotlinx.html library and the
jcenter repository to
build.gradle.kts. Also, please temporarily exclude the Okta Spring Boot starter to see the application working:
Re-import your Gradle configuration and run the project from your IDE, or from the command line using
The application should start successfully, but a 404 page will be returned when accessing
http://localhost:8080. This is expected behaviour if you didn’t define a handler for the root endpoint.
Prepare a Git Repository for Heroku
To enable Heroku deployments you need to create a new Git repository and commit your application skeleton generated by Spring Initializr. Open you favorite terminal, navigate to your project’s folder, then run the following commands:
These commands will initialise a new Git repository with a default
main branch and create the first commit.
Say Hello World With Spring Boot and Kotlin
One of the best things about the controlled magic of Spring Boot is that it makes complex things plain, and helps to write very concise and easy to read code, especially when teamed up with Kotlin.
HelloController.kt class that returns “Hello, World”.
A lot of things are happening under the hood. This controller has a
@RestController annotation because instead of returning a name of view, you want to return a response body. In this example, it will be rendered as an HTML string.
@GetMapping annotation you declare a GET endpoint bound to
/, and indicate that return mime type is
text/html. Finally, the HTML string
<h1>Hello, World</h1> is returned.
Re-start the application and open your browser to
http://localhost:8080. You should see “Hello, World”.
Use Kotlin’s Statically-Typed HTML Builder
Kotlin provides great syntactic sugar for creating statically-typed DSLs. HTML builder is one of the many practical applications and is implemented as kotlinx.html library. It allows you to create web pages with plain Kotlin code which resembles HTML.
Your web application contains only one page. The corresponding HTML-generating render function
indexPage() has all the HTML boilerplate including basic HTML document layout, Bootstrap CSS inclusion, and styles. The
indexPage() function produces a horizontally and vertically centered ‘hero’ block with content.
Start building your HTML page by adding the following code in a new
views.kt file alongside the controller you just added:
The function producing meaningful content is
FlowContent.guestView(). Note that it is an extension function because HTML DSL components are available only within
FlowContent objects. You can read more about creating a DSL in Kotlin.
Update your controller’s
theAnswer() method to call
After you restart your app and refresh your browser, you should see the output from your template:
Deploy Spring Boot to Heroku
I know that feeling, you can’t wait to put ‘The Thing’ out there on the Internet and share it with your friends. It’s a good time to start deploying as you’ve built a welcoming page.
Please ensure that you have Heroku CLI installed.
Log in to Heroku. You can skip this step if it was done previously:
Then, create a new app with
You should see output like the following:
You’ll find Heroku automatically configures a
remote origin called
heroku. Running a
git push will trigger the build and deploy process automatically. It’s as simple as that!
At the moment, the default JVM Heroku uses is 1.8. You’ll need to create a
system.properties file in your application root to provide the desired version:
Then commit your changes:
Then, deploy to Heroku:
Heroku will build from source once your code is pushed.
Once your application is deployed, it can be easily accessed by running
heroku open. This command opens a new web browser window and navigates to its URL.
Every time you want to deploy your web application, simply push your source code by running
git push heroku main.
Protect Your Spring Boot Application
Many services have a “user’s area” - part of the website or content visible only to the members. In this application, the content of the index page depends on the user login state. Logged in users can see The Answer while guests are invited to sign in. This user registration and login bit might sound trivial but in fact, it causes a number of very serious questions not easy to find answers:
- Where do I store user’s personal data such as name, email, etc.? Is it another table, another database, another type of database, or as a microservice?
- Do I encrypt data, if so what algorithm should I use? Where do I keep encryption keys? Ask yourself if you understand cryptography enough to make the right decision.
- How do I hash passwords? Do I need salt and pepper to cook it right?
- What if I want to add more authentication providers, for instance, social networks? Shall I spend time writing those abstractions I might never use?
- How would I design access management and access token revocation? Does it sound like a very generic thing which must have been implemented by somebody?
- Do I have a good understanding of how to keep user’s PII (Personal Identifiable Information) in compliance with GDPR/CCPA/DPA/other regulations?
Those are just a few questions off the top of my head. I’m certain you’ve got a cool bar story about authentication to tell.
It’s easy to build authentication and authorisation but it’s hard to do it right.
You’ll be using Okta, a software-as-service identity access provider which has excellent integration with Spring Boot and Heroku. Combining Okta with Spring Security makes the sign-in/sign up process as easy as it could be. Yes, you’ll have a user sign up right out of the box. (See bonus section).
Enable the Okta Spring Boot Starter
build.gradle.kts to include
okta-spring-boot-starter artifact and don’t forget to re-import the Gradle model in your IDE.
Add the Okta Add-on to Your Heroku Application
Okta provides an official Okta Heroku Add-on which expedites the development process. You’ll create an Okta account linked to your Heroku app, and automatically configure Okta right from the command line.
heroku addons:create okta to begin. You should see output like the following:
This add-on creates a user and configured Okta application for you. The configuration settings will be specified for your service via environment variables. You can lookup these settings with
This command will return all the environment variables for your app on Heroku.
If you see an empty output you need to wait a minute or two while the setup process is completed.
OKTA_ADMIN_PASSWORD are actual credentials you can use to log in to your application.
Provide Environment Variables for Okta Spring Boot
For OpenID Connect (OIDC) authentication and OAuth 2.0 authorization, only three variables are important to you:
You’ll need to update
application.properties file to provide them for Okta’s Spring Boot starter:
Although the idea of hardcoding secrets into the properties file might look very tempting, especially for a pet project, you should never do that! It’s good hygiene practice to never store secrets in your source control.
Configure IntelliJ IDEA to Run Your Spring Boot App
You probably want to play with the application locally as well, but at the moment it expects environment variables to be set. IntelliJ IDEA allows providing a custom configuration.
In Run Actions(Ctrl-Shift-A) dialogue search for Edit Configurations or use your mouse to edit the current run configuration in dropdown.
OKTA_OAUTH2_CLIENT_SECRET_WEB keys and values from the
heroku config output:
Configure Spring Security
One last step to make the application secure is to configure Spring Security. Create a
WebSecurityConfig class in the same package as your other classes and fill it with the code below.
This configuration allows anyone to access
/ but always authenticates each request; allowing logged in users and guests to access the same URL. In the event of successful login or logout, users will be redirected to the index page
Redirect Users to the Okta Login Page
Spring Security automatically registers an endpoint for Okta at
/oauth2/authorization/okta. This allows you to redirect the user to the right location to start the OIDC authentication process.
To enable login flow for the user add a link to your
Handle an Authenticated User
Upon successful login, you can extract information provided by the authentication service. Spring Boot can inject it straight in to your controller’s handler:
OidcUser contains a variety of fields you might find useful, among them are: name, email, claims, etc.
OidcUser? is null user is not authorized, it effectively makes them a guest.
indexPage() method in
views.kt to match the code below. Now when a user is logged in, they’ll see a warm welcome message:
Run your application via IntelliJ and you should be able to complete the sign-in process:
(Bonus) Enable Self-Registration
Okta can also take care of the registration process, which can be easily enabled in the settings. Head on over to your Heroku dashboard and choose your project. Find the Installed add-ons section and click on okta to open your Okta dashboard.
Navigate to Users > Registration and click Enable Registration. A registration configuration form allows some level of flexibility. For example, you can require new users to provide their first and last name.After you save the configuration, open a new incognito browser window and try to log in. This time, the Okta login form will have a link for user registration:
You can push all your changes to Heroku after committing them.
In this tutorial, you learnt how to quickly bootstrap secured web applications for your ‘pet project’ ideas using Spring Boot with Spring Security, Kotlin, and Okta. You deployed a web application to the Heroku cloud using Heroku CLI and Git command-line tools. It’s always a good idea to use existing frameworks and tools instead of focusing on repetitive tasks such as deployment, authentication, and authorization.
The source code for this tutorial and the examples in it are available on GitHub in the oktadeveloper/okta-spring-boot-heroku-example repository.
Published at DZone with permission of Ruslan Zaharov. See the original article here.
Opinions expressed by DZone contributors are their own.