spring logo
java logo

Authorization in Spring Boot

Updated on April 17, 2024
Photo of Matt Raible
Matt RaibleDeveloper Advocate

Introduction

Learning GoalLearn how to build a Spring Boot resource server that's secured with OAuth 2.0, the Okta Spring Boot starter, and Spring Security.

In this guide, you will:

  • Learn how to build a Spring Boot API with Java.
  • Learn how to secure your API with OAuth 2.0.
  • Test your protected API endpoints.

Why Use Spring to Build Apis?

Spring Boot is one of the most popular frameworks for developing Java applications and REST APIs. If you want to be employed for years to come, Java is a good language to learn. Put those two together, and you have a winning combination!

The OAuth 2.0 authorization framework is a protocol that allows a user to grant a third-party website or application access to the user's protected resources without necessarily revealing their long-term credentials or even their identity.

In the context of OAuth 2.0, a resource server is your API server that provides access to protected resources after the application has obtained an access token from the Identity Provider (IdP).

In this guide, you'll learn how to use Java and Spring Boot to build a REST API that's secured with OAuth 2.0. You'll also learn how to make authenticated requests to test it works as expected.

Set up a Development Environment

  • Use your favorite text editor or IDE. We recommend using IntelliJ IDEA.
  • Ensure that you have Java 17+ installed in your system. You can easily install it using SDKMAN!.
  • Windows commands in this guide are written for PowerShell.

Create an Auth0 account

If you already have an Auth0 account, you can log in to your tenant and continue to the next step.

Otherwise, sign up for a free Auth0 account.

During the sign-up process, you create something called an Auth0 Tenant, where you configure your use of Auth0.

Once you sign in, Auth0 takes you to the Auth0 Dashboard, where you can configure and manage Auth0 assets, such as applications, APIs, connections, and user profiles.

Set up the Auth0 CLI

If you are not familiar with the Auth0 CLI, you can follow the "Auth0 CLI Basics" lab to learn how to build, manage, and test your Auth0 integrations from the command line.

There are different ways to install the Auth0 CLI, depending on your operating system.

LOADING...

Create a Spring Boot API

Use your browser and start.spring.io to create a new Spring Boot project with Spring Web and Okta dependencies.

This guide is using Spring Boot version 3.2.4.

You can also create projects with the command line. To create a Gradle project, run the following command:

LOADING...

Run the following command if you prefer to create a Maven project instead:

LOADING...

The Okta Spring Boot starter is a thin wrapper around Spring Security's resource server and OAuth client support. It does audience validation for resource servers and secures all endpoints by default.

Navigate to the resource-server directory:

COMMAND
cd resource-server

Then, run the app with the following command:

GRADLE
MAVEN
./gradlew bootRun

Open the http://localhost:8080 URL in your favorite browser. You'll be prompted to log in since the Okta Spring Boot starter secures all URLs by default. You won't be able to log in yet because you haven't configured OAuth yet.

Secure Your API with OAuth 2.0

In a terminal, connect the Auth0 CLI to your Auth0 tenant.

COMMAND
auth0 login
Visit the Access Your Tenant section of the "Auth0 CLI Basics" lab to learn more about the auth0 login command.

Then, run the command below to see your available Auth0 tenants:

COMMAND
auth0 tenants list

Copy the domain of the Auth0 tenant that you'd like to use and paste it into the following input box:

When you enter a value in the input fields present on this page, any code snippet that uses such value updates to reflect it. Using the input fields makes copying and pasting code as you follow along easy.

For security, these configuration values are stored in memory and only used locally. They are gone as soon as you refresh the page! As an extra precaution, you should use values from an Auth0 test application instead of a production one.

Now, update the content of the src/main/resources/application.properties file to configure a resource server using the Auth0 domain:

src/main/resources/application.properties
# trailing slash is important
okta.oauth2.issuer=https://AUTH0-DOMAIN/
okta.oauth2.audience=${okta.oauth2.issuer}api/v2/

The second value, okta.oauth2.audience, reads from the first, okta.oauth2.issuer, so you only need to provide a value for okta.auth2.issuer. The audience used in this example is for the Auth0 Management API. You can create a new API, but for simplicity, we're using the one that comes by default when you create an Auth0 tenant.

Create a HelloController.java class next to DemoApplication.java:

LOADING...

Populate it with the following code:

src/main/java/com/example/demo/HelloController.java
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
@RestController
class HelloController {
@GetMapping("/hello")
public String hello(Principal principal) {
return "Hello, " + principal.getName() + "!";
}
}

This controller is protected by Spring Security because the Okta Spring Boot starter auto-configures everything to be protected by default.

Test Your API

Restart the app:

GRADLE
MAVEN
./gradlew bootRun

Open a new terminal to test the /hello endpoint you created in the HelloController.java file:

LOADING...

You will get a 401 Unauthorized response because you didn't pass in an access token.

Get an access token

You can get an access token using the Auth0 CLI to test making a secure call to your protected API endpoint:

COMMAND
auth0 test token -a https://AUTH0-DOMAIN/api/v2/ -s openid

Select any available client when prompted. You will be prompted to open a browser window and log in with a user credential. You can sign up as a new user using an email and password or using the Google social login.

If you'd like to see what's in the access token you created, you can copy and paste it into JWT.io or use JWT UI.

You can also get an access token using the Authorization Code Flow.

Paste the access token value in the following field so that you can use it to test your resource server:

Run the following command to make an authenticated request to your resource server:

LOADING...

You should receive a 200 OK response with a message similar to the following:

Hello, auth0|61bcbc76f64d4a0072af8a1d!

Stop the resource server using Ctrl+C.

Recap

In this guide, you learned how to build a Spring Boot API with Java, secure it with OAuth 2.0, and learn how to make authenticated requests using the tool of your preference. Isn't it cool how you can create and test a Spring Boot app with Auth0 so quickly?

curl -G https://start.spring.io/starter.tgz -d dependencies=web,okta -d baseDir=resource-server | tar -xzvf -
./gradlew bootRun
auth0 tenants list
auth0 test token -a https://AUTH0-DOMAIN/api/v2/ -s openid
curl localhost:8080/hello -i --header "Authorization: Bearer AUTH0-ACCESS-TOKEN"

Check out our other Spring Boot guides Authentication in Spring Boot and Role Based Access Control in Spring Boot to learn more about Auth0 security integration in Spring Boot Java applications.

Be sure to visit the Okta Spring Boot Starter's GitHub repository to stay informed on the latest developments and join the growing community of Spring Boot users who use Okta.