DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Aggregating REST APIs Calls Using Apache Camel
  • Choosing a Library to Build a REST API in Java
  • Creating a Secure REST API in Node.js
  • Leveraging Salesforce Using Spring Boot

Trending

  • Optimizing Serverless Computing with AWS Lambda Layers and CloudFormation
  • Useful System Table Queries in Relational Databases
  • Is Big Data Dying?
  • How to Use AWS Aurora Database for a Retail Point of Sale (POS) Transaction System
  1. DZone
  2. Coding
  3. Java
  4. How to Use Apache Shiro and OAuth 2.0 to Build a Secure Application

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.

By 
Brian Demers user avatar
Brian Demers
·
Jul. 29, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
13.6K Views

Join the DZone community and get the full member experience.

Join For Free

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:

  • Java 8+
  • Apache Maven
  • A free Okta Account

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
 




x
19


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0"
3
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5
    <modelVersion>4.0.0</modelVersion>
6
 
          
7
    <groupId>com.okta.example</groupId>
8
    <artifactId>okta-shiro-jaxrs-example</artifactId>
9
    <version>1.0-SNAPSHOT</version>
10
    <packaging>war</packaging>
11
 
          
12
    <properties>
13
        <maven.compiler.source>1.8</maven.compiler.source>
14
        <maven.compiler.target>1.8</maven.compiler.target>
15
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
16
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
17
    </properties>
18
 
          
19
</project>


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 Applications → Add Application from the top menu. Then, select Web → Next.

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.

  • Build a Secure REST Application Using Jersey

  • Protecting a Spring Boot App with Apache Shiro

  • Java REST API Showdown

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.

mobile app Apache Shiro security authentication Build (game engine) Apache Maven Java (programming language) Spring Framework REST Web Protocols

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

Opinions expressed by DZone contributors are their own.

Related

  • Aggregating REST APIs Calls Using Apache Camel
  • Choosing a Library to Build a REST API in Java
  • Creating a Secure REST API in Node.js
  • Leveraging Salesforce Using Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!