google Analytics

Thursday, September 23, 2010

REST Authentication and Authorization example

Authentication and Authorization in JAX-RS
REST Authentication and Authorization example

Folder Structure

 

example Programe
=============================================================
 

package com.test;
import java.net.URI;
import java.net.URISyntaxException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import org.jboss.resteasy.annotations.Form;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
/**
 *
 * @author NathA1
Spring will use any class annotated with the @Controller annotation as
a Controller in Spring MVC support
The @Produces is used to map a client request and match it up to the client's Accept header.
The Accept HTTP header is sent by the client and defines the media types the client prefers to
receive from the server
 */
@RolesAllowed({"admin","tomcat"})
@Controller
@Path(ProductsResource.CONTACTS_URL)
public class ProductsResource
{
   public static final String CONTACTS_URL = "/products";
   @Autowired
   ProductService service;

   @RolesAllowed("admin")
   @GET
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data")
   public Products getAll()
   {
      return service.getAll();
   }

   @PermitAll
   @PUT
   @POST
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data")
   public Response saveProduct(@Context UriInfo uri, Product product)
         throws URISyntaxException
   {
       System.out.println("Inside -->> saveProduct");
      service.save(product);
      URI newURI = UriBuilder.fromUri(uri.getPath()).path(product.getLongName()).build();
      return Response.created(newURI).build();
   }

   @RolesAllowed("tomcat")
   @GET
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data/{shortName}")
   public Product get(@PathParam("shortName") String shortName)
   {
      return service.getProduct(shortName);
   }

   @PermitAll
   @POST
   @PUT
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
   @Produces(MediaType.TEXT_HTML)
   public ModelAndView saveContactForm(@Form Product product)
         throws URISyntaxException
   {
       System.out.println("Inside -->> saveContactForm");
      service.save(product);
      return viewAll();
   }
  

   @PermitAll
   @GET
   @Produces(MediaType.TEXT_HTML)
   public ModelAndView viewAll()
   {
      // forward to the "contacts" view, with a request attribute named
      // "contacts" that has all of the existing contacts
      return new ModelAndView("products", "products", service.getAll());
   }
}
/**
 * END OF PROGRAM
 * =======================================================================
package com.test;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
When a class is annotated with a @XmlRootElement annotation, RESTEasy
will select the JAXBXmlRootElementProvider. This provider handles basic marhaling and and
unmarshalling of custom JAXB entities
@author Anish Nath
 *
 */

@XmlRootElement
public class Products
{
   private Collection<Product> products;
   public Products()
   {
      this.products = new ArrayList<Product>();
   }
   public Products(Collection<Product> products)
   {
      this.products = products;
   }
   /**
    *  @XmlElement annotation to embed other JAXB-annotated classes.
    * @return
    */
   @XmlElement(name="product")
   public Collection<Product> getProducts()
   {
      return products;
   }
   public void setProducts(Collection<Product> product)
   {
      
      this.products = product;
   }
}

/**
 * END OF PROGRAM
 * =======================================================================
 */
package com.test;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Service;
/**
 *
 * Anish Nath
The @Service annotation marks classes that implement a part of the business
logic of the application
 *
 */
@Service
public class ProductService
{
   private Map<String, Product> productMap = new ConcurrentHashMap<String, Product>();
   public void save(Product product)
   {
       productMap.put(product.getShortName(), product);
   }
   public Product getProduct(String shortName)
   {
      return productMap.get(shortName);
   }
   public Products getAll()
   {
      return new Products(productMap.values());
   }
}

/**
 * END OF PROGRAM
 * =======================================================================
 */
 Web.xml
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/products/*</url-pattern>
    </servlet-mapping>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>product creation</web-resource-name>
            <url-pattern>/products</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>
        <role-name>admin</role-name>
    </security-role>

</web-app>

==========================================================================
springmvc-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    ">
    <context:component-scan base-package="com.test" />
    <context:annotation-config />
    <import resource="classpath:springmvc-resteasy.xml" />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>


==========================================================================================
tomcat-users.xml
<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users>
  <role rolename="manager"/>
  <role rolename="tomcat"/>
  <role rolename="admin"/>
  <role rolename="role1"/>
  <user password="tomcat" roles="tomcat,role1" username="both"/>
  <user password="tomcat" roles="tomcat" username="tomcat"/>
  <user password="admin" roles="admin,manager" username="admin"/>
  <user password="tomcat" roles="role1" username="role1"/>
</tomcat-users>
===========================================================================================

spring rest services
spring rest example

RESTfull web service Example
restlet spring security
RestEasy with EJB Integration Example
RESTEasy and Spring MVC

ANish

1 comment: