Close

JAX-RS - Container Managed Basic Authentication

[Last Updated: Sep 20, 2017]

This example shows how to use container managed basic authentication in JAX-RS.

Since JAX-RS runs in a servlet container, we can implement container managed authentication by specifying <security-constraint> and <login-config> elements in web.xml. In an servlet based application, we usually use @ServletSecurity annotation to specify a security constraint.

Example

web.xml

src/main/webapp/WEB-INF/web.xml

<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
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
    <security-constraint>
        <web-resource-collection>
            <url-pattern>/employees/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>EMPLOYEE</role-name>
        </auth-constraint>
    </security-constraint>
    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>default</realm-name>
    </login-config>
</web-app>

Defining Users and Roles

Since we are going to use embedded Tomcat server, we have to define users in a local file:

src\main\resources\tomcat-users.xml

<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users>
    <role rolename="EMPLOYEE"/>
    <user username="joe" password="123" roles="EMPLOYEE"/>
</tomcat-users>

In Tomcat server environment, we will use the similar file under $CATALINA_BASE/conf/ folder.

Following is the mapping for the local users file with embedded Tomcat plugin in pom.xml

   <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
            <path>/</path>
            <tomcatUsers>src/main/resources/tomcat-users.xml</tomcatUsers>
        </configuration>
  </plugin>

A JAX-RS resource

@Path("/employees")
public class EmployeeResource {

  @GET
  public String getEmployees() {
      return "dummy employee list";
  }

  @GET
  @Path("{id}")
  public String getUser(@PathParam("id") String id) {
      return "dummy employee with id: " + id;
  }
}

Output

Accessing '/employees'

Enter user 'joe' and password '123':

Example Project

Dependencies and Technologies Used:

  • jersey-server 2.25.1: Jersey core server implementation.
  • jersey-container-servlet 2.25.1: Jersey core Servlet 3.x implementation.
  • JDK 1.8
  • Maven 3.3.9

JAX-RS Container Basic Authentication Select All Download
  • jaxrs-basic-authentication
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
        • webapp
          • WEB-INF
            • web.xml

    See Also