{{announcement.body}}
{{announcement.title}}

How to Use Apache Shiro and OAuth 2.0 to Build a Secure Application

DZone 's Guide to

How to Use Apache Shiro and OAuth 2.0 to Build a Secure Application

This article demonstrates how to use Apache Shiro and OAuth 2.0 to create a secure Maven-based account with Okta.

· Java Zone ·
Free Resource

For those unfamiliar, Apache Shiro—a Java Security framework—performs authorization, authentication, and session management (along with many other functions) to help build more secure applications.

This post will show you how to use JAX-RS to build a simple Java REST application. JAX-RS is a set of interfaces so you’ll need to pick your implementation. In this post, we’ll be using Jersey—but you can use whatever implementation you prefer and none of these APIs are Jersey specific. 

In OAuth 2.0, REST services are usually resource servers. In simple terms, they authenticate using an access token sent in the Authorization HTTP header, formatted as Authorization: Bearer <access-token>.

For this tutorial you will need:

Create a New JAX-RS project

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
 






Next, add the dependencies:

Java
 




xxxxxxxxxx
1
57


1
  <dependencies>
2
        <dependency>
3
            <groupId>com.okta.shiro</groupId>
4
            <artifactId>okta-shiro-plugin</artifactId>
5
            <version>0.1.0</version>
6
        </dependency>
7
        <dependency>
8
            <groupId>javax.ws.rs</groupId>
9
            <artifactId>javax.ws.rs-api</artifactId>
10
            <version>2.1.1</version>
11
        </dependency>
12
        <dependency>
13
            <groupId>org.apache.shiro</groupId>
14
            <artifactId>shiro-jaxrs</artifactId>
15
            <version>1.5.3</version>
16
        </dependency>
17
        <dependency>
18
            <groupId>org.apache.shiro</groupId>
19
            <artifactId>shiro-servlet-plugin</artifactId>
20
            <version>1.5.3</version>
21
            <scope>runtime</scope>
22
        </dependency>
23
 
          
24
        <!-- logging -->
25
        <dependency>
26
            <groupId>org.slf4j</groupId>
27
            <artifactId>jcl-over-slf4j</artifactId>
28
            <version>1.7.30</version>
29
            <scope>runtime</scope>
30
        </dependency>
31
        <dependency>
32
            <groupId>ch.qos.logback</groupId>
33
            <artifactId>logback-classic</artifactId>
34
            <version>1.2.3</version>
35
            <scope>runtime</scope>
36
        </dependency>
37
 
          
38
        <!-- JAX-RS, runtime only dependencies -->
39
        <dependency>
40
            <groupId>org.glassfish.jersey.containers</groupId>
41
            <artifactId>jersey-container-servlet</artifactId>
42
            <version>2.30.1</version>
43
            <scope>runtime</scope>
44
        </dependency>
45
        <dependency>
46
            <groupId>org.glassfish.jersey.core</groupId>
47
            <artifactId>jersey-server</artifactId>
48
            <version>2.30.1</version>
49
            <scope>runtime</scope>
50
        </dependency>
51
        <dependency>
52
            <groupId>org.glassfish.jersey.inject</groupId>
53
            <artifactId>jersey-hk2</artifactId>
54
            <version>2.30.1</version>
55
            <scope>runtime</scope>
56
        </dependency>
57
    </dependencies>


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

XML
 




xxxxxxxxxx
1
14


1
  <build>
2
        <plugins>
3
            <plugin>
4
                <groupId>org.eclipse.jetty</groupId>
5
                <artifactId>jetty-maven-plugin</artifactId>
6
                <version>9.4.27.v20200227</version>
7
                <configuration>
8
                    <httpConnector>
9
                        <port>8000</port>
10
                    </httpConnector>
11
                </configuration>
12
            </plugin>
13
        </plugins>
14
    </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

Java
 




xxxxxxxxxx
1
20


1
package com.okta.example.shiro;
2
 
          
3
import org.apache.shiro.authz.annotation.RequiresAuthentication;
4
 
          
5
import javax.ws.rs.GET;
6
import javax.ws.rs.Path;
7
import javax.ws.rs.Produces;
8
import javax.ws.rs.core.Context;
9
import javax.ws.rs.core.SecurityContext;
10
 
          
11
@Path("/") 
12
@Produces({"plain/text"}) 
13
public class SecureResource {
14
 
          
15
    @GET 
16
    @RequiresAuthentication 
17
    public String showUser(@Context SecurityContext securityContext) { 
18
        return "Current User: " + securityContext.getUserPrincipal().getName(); 
19
    }
20
}


  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 requestsRequire Authentication!
  4. Inject the current user’s security context
  5. 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:

Java
 




xxxxxxxxxx
1


1
OktaJwtPrincipal jwtPrincipal = (OktaJwtPrincipal) securityContext;
2
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:

Java
 




xxxxxxxxxx
1
19


1
package com.okta.example.shiro;
2
 
          
3
import org.apache.shiro.web.jaxrs.ShiroFeature;
4
import javax.ws.rs.ApplicationPath;
5
import javax.ws.rs.core.Application;
6
import java.util.HashSet;
7
import java.util.Set;
8
 
          
9
@ApplicationPath("/") 
10
public class RestApplication extends Application {
11
 
          
12
    @Override
13
    public Set<Class<?>> getClasses() {
14
        Set<Class<?>> classes = new HashSet<>();
15
        classes.add(ShiroFeature.class); 
16
        classes.add(SecureResource.class); 
17
        return classes;
18
    }
19
}


  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:

Java
 




xxxxxxxxxx
1
10


1
[main]
2
# Define the Okta realm
3
oktaJwtRealm = com.okta.shiro.realm.OktaResourceServerRealm
4
 
          
5
# Configure your issuer
6
oktaJwtRealm.issuer = https://{yourOktaDomain}/oauth2/default
7
 
          
8
[urls]
9
# use the `authcBearer` filter to process Bearer tokens
10
/** = 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
 




xxxxxxxxxx
1


1
<?xml version="1.0" encoding="UTF-8"?>
2
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
3
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
5
         version="3.1">
6
</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:

Shell
 




xxxxxxxxxx
1


1
./mvnw jetty:run


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

Shell
 




xxxxxxxxxx
1


 
1
curl localhost:8000/ -v


Java
 




xxxxxxxxxx
1


 
1
< HTTP/1.1 401 Unauthorized
2
< Date: Thu, 09 Apr 2020 17:50:49 GMT
3
< WWW-Authenticate: Bearer realm="application"
4
< Content-Length: 0
5
< 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

Application settingsMake 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:

Shell
 




xxxxxxxxxx
1


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


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

Shell
 




xxxxxxxxxx
1


 
1
curl localhost:8000/ -H "Authorization: Bearer $TOKEN"
2
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.

Topics:
apache maven, apache shiro, java, jax rs, jersey, oauth 2

Published at DZone with permission of Brian Demers , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}