Java Reference
In-Depth Information
method. You get access to a SecurityContext instance by injecting it into a field, setter
method, or resource method parameter using the @Context annotation.
Let's examine this security interface with an example. Let's say we want to have a security
log of all access to a customer database by users who are not administrators. Here is how it
might look:
@Path ( "/customers" )
public
public class
class CustomerService
CustomerService {
@GET
@Produces ( "application/xml" )
public
public Customer [] getCustomers ( @Context SecurityContext sec ) {
if ( sec . isSecure () && ! sec . isUserInRole ( "ADMIN" )) {
logger . log ( sec . getUserPrincipal () +
" accessed customer database." );
}
...
}
}
In this example, we inject the SecurityContext as a parameter to our getCustomer() JAX-
RS resource method. We use the method SecurityContext.isSecure() to determine
whether or not this is an authenticated request. We then use the method SecurityCon-
text.isUserInRole() to find out if the caller is an ADMIN or not. Finally, we print out to our
audit log.
With the introduction of the filter API in JAX-RS 2.0, you can implement the SecurityCon-
text interface and override the current request's SecurityContext via the Container-
RequestContext.setSecurityContext() method. What's interesting about this is that you
can implement your own custom security protocols. Here's an example:
import
import javax.ws.rs.container.ContainerRequestContext
javax.ws.rs.container.ContainerRequestContext ;
import
import javax.ws.rs.container.ContainerRequestFilter
javax.ws.rs.container.ContainerRequestFilter ;
import
import javax.ws.rs.container.PreMatching
javax.ws.rs.container.PreMatching ;
import
import javax.ws.rs.core.SecurityContext
javax.ws.rs.core.SecurityContext ;
import
import javax.ws.rs.core.HttpHeaders
javax.ws.rs.core.HttpHeaders ;
@PreMatching
public
public class
class CustomAuth
CustomAuth implements
implements ContainerRequestFilter {
protected
protected MyCustomerProtocolHandler customProtocol = ...;
public
public void
void filter ( ContainerRequestContext requestContext ) throws
throws IOException
{
Search WWH ::




Custom Search