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



public interface SecurityContext {
     * Returns a <code></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();


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



<web-app xmlns=""
                   " version="3.1">


A JAX-RS resource

public class EmployeeResource {

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

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


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