This example shows you how to use the Okta Spring Boot Starter 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 spring-boot
.
NOTE: If you'd like to use WebFlux instead of Spring MVC, use
okta start spring-boot --branch webflux
.
You can also clone this repo and run okta start
in it.
git clone https://github.com/okta-samples/okta-spring-boot-sample.git
cd okta-spring-boot-sample
okta start
Manually enable Refresh Token on your Okta application to avoid third-party cookies. Sign in to your Okta Developer Edition account. Press the Admin Console button to navigate to the Okta Admin Console. In the sidenav, navigate to Applications > Applications and find the Okta application for this project named okta-spring-boot-sample
. Edit the application's General Setting to enable the Refresh Token checkbox. Save your changes.
./mvnw spring-boot:run
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 - 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 Spring Boot / Spring Security you can read A Quick Guide to Spring Boot Login Options.