View on Github

Secure your API using Spring Security 5 and Auth0

Auth0 allows you to quickly add authorization to your application. This guide demonstrates how to integrate Auth0 with any new or existing Spring Boot application.

If you have not created an API in your Auth0 dashboard yet, use the interactive selector to create a new Auth0 API or select an existing API that represents the project you want to integrate with.

Review our getting started guide to set up your first API through the Auth0 dashboard.

Each Auth0 API uses the API Identifier, which your application needs to validate the access token.

Permissions let you define how resources can be accessed on behalf of the user with a given access token. For example, you might choose to grant read access to the messages resource if users have the manager access level, and a write access to that resource if they have the administrator access level.

You can define allowed permissions in the Permissions view of the Auth0 Dashboard's APIs section.

Configure Permissions

The sample project uses a /src/main/resources/application.yml file, which configures it to use the correct Auth0 domain and API Identifier for your API. If you download the code from this page it will be automatically configured. If you clone the example from GitHub, you will need to fill it in yourself.

Attribute Description
auth0.audience The unique identifier for your API. If you are following the steps in this tutorial it would be https://quickstarts/api.
spring.security.oauth2.resourceserver.jwt.issuer-uri The value of the iss claim and the issuer URI of the resource server in the JWT issued by Auth0. Spring Security uses this property to discover the authorization server's public keys and validate the JWT signature. The value is Auth0 domain with an https:// prefix and a / suffix (the trailing slash is important).

If you are using Gradle, you can add the required dependencies using the Spring Boot Gradle Plugin and the Dependency Management Plugin to resolve dependency versions:

// build.gradle

plugins {
    id 'org.springframework.boot' version '2.5.12'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
}

If you are using Maven, add the Spring dependencies to your pom.xml file:

// pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.12</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>
</dependencies>

To validate the JWT, you also need to validate that the JWT is intended for your API by checking the aud claim of the JWT. Create a new class named AudienceValidator that implements the OAuth2TokenValidator interface and override the validate method to verify whether the required audience is present.

To configure the application as a Resource Server and validate the JWTs, create a class that extends WebSecurityConfigurerAdapter, add the @EnableWebSecurity annotation, and override the configure method

Protect API endpoints

The routes shown below are available for the following requests:

  • GET /api/public: available for non-authenticated requests
  • GET /api/private: available for authenticated requests containing an access token with no additional scopes
  • GET /api/private-scoped: available for authenticated requests containing an access token with the read:messages scope granted

The example below shows how to secure API methods using the HttpSecurity object provided in the configure() method of the SecurityConfig class. Route matchers restrict access based on the level of authorization required:

Configure JWT Validator

Update the SecurityConfig class to configure a JwtDecoder bean that uses the AudienceValidator. The auth0.audience value from application.yml validates the aud claim. The issuer-uri value from application.yml verifies the issuer.

To make your endpoint return a JSON, you can use a POJO (Plain Old Java Object). The member variables of this object is serialized into the key value for your JSON. Create a new class named Message as an example domain object to return during the API calls.

Create a new class named APIController to handle requests to the endpoints. The APIController has three routes as defined in the Protect API Endpoints section. For this example, allow all origins through @CrossOrigin annotation. Real applications should configure CORS for their use case.

To build and run the sample project, execute the bootRun Gradle task.

Linux or macOS:

./gradlew bootRun

Windows:

gradlew.bat bootRun

If you are configuring your own application using Maven and the Spring Boot Maven Plugin, you can execute the spring-boot:run goal.

Linux or macOS:

mvn spring-boot:run

Windows:

mvn.cmd spring-boot:run
Checkpoint

The sample application will be available at http://localhost:3010/. Read about how to test and use your API in the Using Your API article.

Next Steps

Excellent work! If you made it this far, you should now have login, logout, and user profile information running in your application.

This concludes our quickstart tutorial, but there is so much more to explore. To learn more about what you can do with Auth0, check out:

Did it work?

Any suggestion or typo?

Edit on GitHub
Sign Up

Sign up for an or to your existing account to integrate directly with your own tenant.