Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a JAX-RS REST service have authentication handled by annotations?

I have a REST api written with JAX-RS, and I need to add authentication to it. So far all the information I've been able to find about it has suggestions for doing it via spring, which I'm not using. Is there something already existing, or would it be easy to write, something that will let me annotate either a method, or the entire class which would force auth headers to be present?

I'm using tomcat6 and jersey, if that matters.

Something like:

@Path("api")
public class Api {
    @GET
    @AuthenticationRequired
    public Response getInfo(...) {...}
}
like image 679
Daenyth Avatar asked Mar 13 '12 19:03

Daenyth


2 Answers

I think you want import javax.annotation.Security.RolesAllowed;

The annotation itself looks like this

@Path("/helloworld")
@RolesAllowed({"ADMIN", "ORG1"})
public class helloWorld {

@GET
@Path("sayHello")  
@Produces("text/plain")
@RolesAllowed("ADMIN")
public String sayHello() {
   return "Hello World!";
}
}
like image 183
derdc Avatar answered Sep 23 '22 16:09

derdc


I would manage security at the container level. Here's a good writeup if you happen to be using Apache CXF:

http://cxf.apache.org/docs/secure-jax-rs-services.html

And here's an example for Glassfish:

http://www.butonic.de/2010/06/18/a-simple-jax-rs-security-context-example-in-glassfish/

Here's one more link, which discusses JSR 250 annotations (e.g. @RolesAllowed):

http://www-01.ibm.com/support/knowledgecenter/SSEQTP_8.5.5/com.ibm.websphere.base.doc/ae/twbs_jaxrs_impl_securejaxrs_annotations.html

like image 24
paulsm4 Avatar answered Sep 21 '22 16:09

paulsm4