Search code examples
web-servicesjerseyjaas

annotation based security in tomcat webapp


I want to achieve webservice security something like this (http://docs.oracle.com/cd/E24329_01/web.1211/e24983/secure.htm - example is for javaee)

But inside tomcat + jersey application. Is it possible to do so ?

As far as I can see, tomcat does have annotation-api which can work in this case. Unable to figure out how.

package samples.helloworld;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.annotation.Security.RolesAllowed;


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

   @GET
   @Path("sayHello")  
   @Produces("text/plain")
   @RolesAllows("ADMIN")
   public String sayHello() {
      return "Hello World!";
   }
}

Solution

  • As described in the link above, you should secure your Rest WebServices. Example of Web.xml

    <web-app>
        <servlet>
            <servlet-name>RestServlet</servlet-name>
            <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>RestServlet</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
        <security-constraint>
             <web-resource-collection>
                 <web-resource-name>Orders</web-resource-name>
                 <url-pattern>/orders</url-pattern>
                 <http-method>GET</http-method>
                 <http-method>POST</http-method>
             </web-resource-collection>
             <auth-constraint>
                 <role-name>admin</role-name> 
             </auth-constraint>
        </security-constraint>
            <login-config>
                <auth-method>BASIC</auth-method>
                <realm-name>default</realm-name>
            </login-config>
        <security-role>
            <role-name>admin</role-name>
        </security-role>
    </web-app>