Build a Secure Java Application with Apache Shiro and OAuth 2.0

Apache Shiro is a Java security framework that can perform authentication, authorization, session management, along with a host of other features for building secure applications.

In this tutorial, you will build a simple Java REST application using JAX-RS. JAX-RS, like many Java APIs, is a set of interfaces, and you will need to pick an implementation. For this post, I’ll use Jersey (the reference implementation of JAX-RS), but you can use Apache CXF, RESTeasy, or your favorite implementation, as none of these APIs will be Jersey specific.

In the OAuth 2.0 world, REST services are typically resource servers. Overly simplified, this means they authenticate using an access token sent in the Authorization HTTP header, formatted as: Authorization: Bearer <access-token>.

Prerequisites:

Create a new JAX-RS project

You can see the completed example on GitHub.

There are a few ways to create a new Maven based project. I usually use my IDE, but you can also generate one on the command line. Whichever way you decide, start with a pom.xml file that looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.okta.example</groupId>
    <artifactId>okta-shiro-jaxrs-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

</project>

Next, add the dependencies:

    <dependencies>
        <dependency>
            <groupId>com.okta.shiro</groupId>
            <artifactId>okta-shiro-plugin</artifactId>
            <version>0.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-jaxrs</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-servlet-plugin</artifactId>
            <version>1.5.3</version>
            <scope>runtime</scope>
        </dependency>

        <!-- logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.30</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
            <scope>runtime</scope>
        </dependency>

        <!-- JAX-RS, runtime only dependencies -->
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.30.1</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.30.1</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
            <version>2.30.1</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

To make running the WAR file easy, we can add the Jetty Maven Plugin to the pom file:

    <build>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.27.v20200227</version>
                <configuration>
                    <httpConnector>
                        <port>8000</port>
                    </httpConnector>
                </configuration>
            </plugin>
        </plugins>
    </build>

Create a JAX-RS Endpoint

A JAX-RS application contains at least two parts: the REST resources/endpoints, to serve the requests, and the Application class to hold them all together. The resources are simply Java objects that have annotations mapping an HTTP request to a method.

Create a simple resource that displays the current user’s email address in src/main/java/com/okta/example/shiro/SecureEndpoint.java

package com.okta.example.shiro;

import org.apache.shiro.authz.annotation.RequiresAuthentication;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;

@Path("/") (1)
@Produces({"plain/text"}) (2)
public class SecureResource {

    @GET (3)
    @RequiresAuthentication (4)
    public String showUser(@Context SecurityContext securityContext) { (5)
        return "Current User: " + securityContext.getUserPrincipal().getName(); (6)
    }
}
1 The base path for all methods in this class
2 Keep things simple in this post and just return plain text
3 This method will handle HTTP GET requests
4 Require Authentication!
5 Inject the current user’s security context
6 Get the name from the Java Principal

If you need to get other information out of the access token, cast the user principal to an OktaJwtPrincipal and use the getClaim() method:

OktaJwtPrincipal jwtPrincipal = (OktaJwtPrincipal) securityContext;
jwtPrincipal.getClaim("your-claim-key");

Create a JAX-RS Application

A JAX-RS Application class defines the metadata and components associated with an application. Most JAX-RS implementations provide helper classes that scan your resources automatically but, because this example works with any implementation, you’ll configure them directly.

Create a class that extends from Application in src/main/java/com/okta/example/shiro/RestApplication.java:

package com.okta.example.shiro;

import org.apache.shiro.web.jaxrs.ShiroFeature;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;

@ApplicationPath("/") (1)
public class RestApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(ShiroFeature.class); (2)
        classes.add(SecureResource.class); (3)
        return classes;
    }
}
1 This application is mounted to /, all resource paths are relative to this one
2 Register Apache Shiro’s JAX-RS feature
3 Add the SecureResource we created in the previous step

Configure Apache Shiro to use OAuth 2.0

Apache Shiro can be configured in a few different ways: programmatically, using dependency injection with Spring and Guice, or using an "ini" file. To keep things focused, I’ll use a simple shiro.ini file located in src/main/resources:

[main]
# Define the Okta realm
oktaJwtRealm = com.okta.shiro.realm.OktaResourceServerRealm

# Configure your issuer
oktaJwtRealm.issuer = https://{yourOktaDomain}/oauth2/default

[urls]
# use the `authcBearer` filter to process Bearer tokens
/** = authcBearer
If you have resources that require anonymous access, use authcBearer[permissive]—just make sure all of your endpoints are annotated correctly!

Add a web.xml

You might be asking yourself, "really, a web.xml file?" Technically you don’t need one—you could instead configure the Maven War Plugin to not require a web.xml.

Or, just add an empty web.xml to src/main/webapp:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
</web-app>

Run the Secure REST Application

You could build the project with ./mvnw package. Simply grab the war file from the target directory, copy it to your favorite container, and start it up. Instead, we’re going to use the Jetty Maven Plugin. From the project directory, run:

./mvnw jetty:run

This command starts a server running on port 8000. Make a request using curl:

curl localhost:8000/ -v
< HTTP/1.1 401 Unauthorized
< Date: Thu, 09 Apr 2020 17:50:49 GMT
< WWW-Authenticate: Bearer realm="application"
< Content-Length: 0
< Server: Jetty(9.4.27.v20200227)

The server returned a 401 status code because we did not provide an access token. There are a few ways to get an access token; which option is right for you depends on where and how you access your REST application. Usually, the application that is invoking your REST API already has an access token. For example, a SPA mobile app, or another web app likely already has an authenticated user. For testing purposes, we will set up the OIDC Debugger.

Create an OAuth 2.0 Application

Login in to your Okta admin console. If you just created a new Okta account and have not logged in yet, follow the activation link in your inbox.

Make a note of the Org URL on the top right; I’ll refer to this as {yourOktaDomain} in the next section.

Once you are logged in, select ApplicationsAdd Application from the top menu. Then, select WebNext.

Give your application a name, something clever like: "Shiro JAX-RS Example."

Set the Login redirect URIs to https://oidcdebugger.com/debug

Check Implicit (Hybrid)

Click Done

Create new Okta Application for the OIDC Debugger

Make note of the Client ID, you will need this for the next step.

Get a Token with the OIDC Debugger

Head over to https://oidcdebugger.com/ and populate the form with the following values:

  • Authorize URI - {yourOktaDomain}/oauth2/default/v1/authorize

  • Client ID - {yourClientID} from the previous step

  • State - this is a test (this can be any value)

  • Response type - select token

  • Use defaults for all other fields

Press the Send Request button.

If you are using an incognito/private browser, this may prompt you to login again. Once the Success page loads, copy the Access token and create an environment variable:

export TOKEN=" <your-access-token-here>"

Now that you have a token, you can make another request to your JAX-RS server:

curl localhost:8000/ -H "Authorization: Bearer $TOKEN"
Current User: <your-email-address>

And just like that, you have made an authenticated request to your JAX-RS application!

Learn More About Secure Applications

In this tutorial, I’ve shown you how to secure a simple JAX-RS application with Apache Shiro and Okta. This same resource server technique can be used with other servlet based web applications too.

Check out these related blog posts to learn more about building secure web applications.

If you like this blog post and want to see more like it, follow @oktadev on Twitter, subscribe to our YouTube channel, or follow us on LinkedIn. As always, please leave a comment below if you have any questions.

Brian Demers is a Developer Advocate at Okta and a PMC member for the Apache Shiro project. He spends much of his day contributing to OSS projects in the form of writing code, tutorials, blogs, and answering questions. Along with typical software development, Brian also has a passion for fast builds and automation. Away from the keyboard, Brian is a beekeeper and can likely be found playing board games. You can find him on Twitter at @briandemers.