Using the javax.annotation.security annotations to control access

The javax.annotation.security annotations available with Java EE simplify the coding effort for adding authentication and authorization checks for an application. The Jersey framework allows you to use the following javax.annotation.security annotations, on the JAX-RS resource class or methods, to control the access, based on the user role:

  • javax.annotation.security.DenyAl: With this, no roles can invoke the annotated resource class or method
  • javax.annotation.security.PermitAll: With this, all the security roles are allowed to invoke the annotated resource method(s)
  • javax.annotation.security.RolesAllowed: This specifies the list of roles permitted to access the method(s) in an application
The security annotation support that we discussed in this section is brought into the RESTful web service resources via the Jersey framework, and you may not find it working in the same way with other implementations of JAX-RS.

To use the preceding annotations in your JAX-RS resource class or methods, you need to register the following dynamic feature provider offered by the Jersey framework:
org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature.

The following code snippet uses a subclass of javax.ws.rs.core.Application to register the RolesAllowedDynamicFeature provider:

//Other imports are removed for brevity 
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature; 
 
@javax.ws.rs.ApplicationPath("webresources") 
public class ApplicationConfig extends Application { 
    @Override 
    public Set<Class<?>> getClasses() { 
        Set<Class<?>> resources = new java.util.HashSet<>(); 
        //Rest of the code goes here 
        resources.add(RolesAllowedDynamicFeature.class); 
        return resources; 
    } 
} 

Let's see how to use the security annotation with a JAX-RS service to prevent unauthorized access. The following code snippet uses the @RolesAllowed security annotation to restrict access to the resource method. This example uses @RolesAllowed("admin") on the resource method to let only the users that have an admin role to access this API at runtime:

import javax.annotation.security.RolesAllowed; 
 
@GET 
@Path("security") 
@RolesAllowed("admin") 
public Response getSystemInfo() { 
    // getSystemInfo reads system info 
    //method definition is not shown here to save space 
    SystemInfo sysInfo=getSystemInfo(); 
    return Response.ok(sysInfo, 
        MediaType.APPLICATION_JSON).build(); 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.50.87