Using SecurityContext APIs to control access

We started off this chapter by discussing how an application authenticates a user who is trying to access a secured resource. When a client accesses a secured resource, the server identifies and validates the requester, and on successful authentication, the requester is allowed to get inside the application. During this process, the underlying security framework generates a javax.ws.rs.core.SecurityContext object, which holds security-related information pertaining to the requester. The JAX-RS framework allows you to access the SecurityContext object in the code in order to retrieve security-related information pertaining to the current request.

Some of the frequently used methods exposed by SecurityContext are given as follows:

  • getAuthenticationScheme(): This method returns the authentication scheme used for protecting resources, such as HTTP basic, HTTP digest, NTLM, and so on
  • getUserPrincipal(): This method returns the logged-in username
  • isSecure(): This returns true if the request is made through a secure channel (HTTPS)
  • isUserInRole(String role): This returns true if the logged-in user is in the role supplied as a parameter for this method
Please refer to the following API doc to learn more about SecurityContext:
http://docs.oracle.com/javaee/7/api/javax/ws/rs/core/SecurityContext.html.

You can access SecurityContext in the JAX-RS resource methods and call the appropriate APIs on it to perform the authorization of the requester. The following is an example demonstrating the usage of SecurityContext::isUserInRole(String). In this example, the system information is returned to the caller but only if the requested user (client) is in an admin role:

//Other imports are not shown for brevity 
import javax.ws.rs.core.Context; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response; 
import javax.ws.rs.core.SecurityContext;  
 
@Path("system") 
public class SystemResource { 
    @GET 
    @Path("info") 
    public Response getSystemInfo(@Context SecurityContext  
        securityContext) { 
        String adminGroup = "admin"; 
        if (securityContext.isUserInRole(adminGroup)) { 
             // getSystemInfo reads system info - not shown here 
            SystemInfo sysInfo=getSystemInfo(); 
            return Response.ok(sysInfo,  
                MediaType.APPLICATION_JSON).build(); 
        } else { 
            return  
                Response.status(Response.Status.FORBIDDEN).build(); 
        } 
    } 
} 
..................Content has been hidden....................

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