JAX-RS - Injecting SecurityContext with @Context annotation

[Updated: Sep 20, 2017, Created: Sep 20, 2017]

The SecurityContext interface provides access to security related information. An instance of SecurityContext can be injected into a JAX-RS resource class field or method parameter using the @Context annotation.

The SecurityContext interface


package javax.ws.rs.core;

import java.security.Principal;

public interface SecurityContext {
    ......
    /**
     * Returns a <code>java.security.Principal</code> object containing the
     * name of the current authenticated user. If the user
     * has not been authenticated, the method returns null.
     */
    public Principal getUserPrincipal();

    /**
     * Returns a boolean indicating whether the authenticated user is included
     * in the specified logical "role".
     */
    public boolean isUserInRole(String role);

    /**
     * Returns a boolean indicating whether this request was made
     * using a secure channel, such as HTTPS.
     */
    public boolean isSecure();

    /**
     * Returns the string value of the authentication scheme used to protect
     * the resource. If the resource is not authenticated, null is returned.
     */
    public String getAuthenticationScheme();
}

Example

In this example we will implement container managed authentication by specifying <security-constraint> and <login-config> elements in web.xml.

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>

A JAX-RS resource

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

  @GET
  public String getEmployees(@Context SecurityContext securityContext) {
      return "dummy employee list.  user: " + securityContext.getUserPrincipal().getName();
  }

  @GET
  @Path("{id}")
  public String getUser(@PathParam("id") String id,
                        @Context SecurityContext securityContext) {
      return "dummy employee with id: " + id + ". User: " + securityContext.getUserPrincipal();
  }
}

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

Injecting SecurityContext Example Select All Download
  • jaxrs-basic-authentication-with-security-context
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
        • webapp
          • WEB-INF

See Also