This example shows you how to use the Micronaut's OAuth 2.0 support to login a user. The login is achieved through the Authorization Code Flow where the user is redirected to the Okta-Hosted login page. After the user authenticates, they are redirected back to the application and a local cookie session is created.
It also shows how to return the user's information from an API using an OAuth 2.0 access token.
Before running this sample, you will need the following:
- Java 17+
- The Okta CLI Tool
- An Okta Developer Account, create one using
okta register
, or configure an existing one withokta login
Grab and configure this project using okta start micronaut
.
You can also clone this repo and run okta start
in it.
git clone https://github.com/okta-samples/okta-micronaut-sample.git
cd okta-micronaut-sample
okta start
Sign into your Okta Developer Edition account to add a required setting to your Micronaut Okta app to avoid third-party cookies. Navigate to Applications > Applications and select "okta-micronaut-sample" application to edit. Find the General Settings and press Edit. Enable Refresh Token in the Grant type section. Save your changes.
source .okta.env
Run the application with Maven
./mvnw mn:run
The application uses Micronaut Ahead-of-time optimizations (AOT) optimizations via the Micronaut Maven Plugin. You can enable Micronaut Security AOT optimizations in aot-jar.properties
.
Run the application via the Micronaut Application Gradle Plugin.
./gradlew run
Or, run an optimized JAR with Gradle:
./gradle optimizedRun
Log in at http://localhost:8080
.
You can also retrieve user information from the /hello
endpoint with an OAuth 2.0 access token.
First, you'll need to generate an access token.
-
Run
okta apps create spa
. Setoidcdebugger
as an app name and press Enter. -
Use
https://oidcdebugger.com/debug
for the Redirect URI and set the Logout Redirect URI tohttps://oidcdebugger.com
. -
Navigate to the OpenID Connect Debugger website.
- Fill in your client ID
- Use
https://{yourOktaDomain}/oauth2/default/v1/authorize
for the Authorize URI - Use
openid offline_access
for the Scope - Select code for the response type and Use PKCE
- Click Send Request to continue
-
Set the access token as a
TOKEN
environment variable in a terminal window.TOKEN=eyJraWQiOiJYa2pXdjMzTDRBYU1ZSzNGM...
-
Test the API with HTTPie and an access token.
http :8080/hello Authorization:"Bearer $TOKEN"
For more details on how to build an application with Okta and Micronaut you can read Build Native Java Apps with Micronaut, Quarkus, and Spring Boot.