You are previewing RESTful Java with JAX-RS.

RESTful Java with JAX-RS

Cover of RESTful Java with JAX-RS by Bill Burke Published by O'Reilly Media, Inc.
O'Reilly logo

Authentication and Authorization in JAX-RS

To enable authentication, you need to modify the WEB-INF/web.xml deployment descriptor of the WAR file your JAX-RS application is deployed in. Authorization is enabled through XML or by applying annotations to your JAX-RS resource classes. To see how all this is put together, let’s do a simple example. We have a customer database that allows us to create new customers by posting an XML document to the JAX-RS resource located at the URI /customers. We want to secure our customer service so that only administrators are allowed to create new customers. Let’s look at a full XML-based implementation of this example:

<?xml version="1.0"?>
<web-app>
   <servlet>
      <servlet-name>JAXRS</servlet-name>
      <servlet-class>
    org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
      </servlet-class>
      <init-param>
         <param-name>
            javax.ws.rs.Application
         </param-name>
         <param-value>
            com.restfully.shop.services.ShoppingApplication
         </param-value>
      </init-param>
   </servlet>

   <servlet-mapping>
      <servlet-name>Rest</servlet-name>
      <url-pattern>/*</url-pattern>
   </servlet-mapping>

   <security-constraint>
      <web-resource-collection>
         <web-resource-name>customer creation</web-resource-name>
         <url-pattern>/customers</url-pattern>
         <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>jaxrs</realm-name>
    </login-config>

    <security-role> ...

The best content for your career. Discover unlimited learning on demand for around $1/day.