Ahoy Spring user!
Recently, I added Okta login to my application to secure the admin section of the website. This is simple enough to accomplish but suddenly I felt the need to run my application locally without any authentication for testing purposes. As I couldn't find any good info on this on the web I decided to share the solution I came up with.
Full source code is here:
- Register for a free developer account at https://developer.okta.com/
- Create a Spring Boot project with the following Spring Initialzer settings. Dependencies: Spring Web, Spring Security, Thymeleaf & OAuth2 Client. This solution works specifically with OAuth2 Client and not the native Okta library.
- In Okta application configuration change the Login redirect URIs to: http://localhost:8080/login/oauth2/code/okta
- In your application.properties configure the following:
- And you need to define a Web Security Config to enable Okta authentication:
To enable several different security profiles I came up with the following solution. We define several Web Security Configurations each with its own
@Profile("ProfileX) annotation, which enables this profile only when this profile is enabled in Spring.
The code looks likes this:
The relevant applications.properties sections look like this (of course only the one you want to use should be enabled, and it should be enabled only at runtime in your CI/CD pipeline):
Once we have the code and know how to make it work one issue remains, what is the best way to run it locally with authentication disabled without modifying the application.properties files and risking pushing those modifications to productions.
Two options that I like the most:
- Configure the relevant Spring profile in InteliJ, go to "Edit Configurations..." And set the profile as local
- Configure a bootRun task in build.gradle that will set the profile to local (unless defined otherwise in the environment):
That's it. Hope you found this useful. Leave comments and likes :)