Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Like this presentation? Why not share!

Like this? Share it with your network

Share

Secure REST with JAX-RS

on

  • 38,424 views

Build Secure RESTful web services

Build Secure RESTful web services

Statistics

Views

Total Views
38,424
Views on SlideShare
38,228
Embed Views
196

Actions

Likes
46
Downloads
1,136
Comments
0

14 Embeds 196

http://www.slideshare.net 88
http://owen.com 73
http://wjhwsh.blogspot.com 10
http://localhost 9
http://sysdecom-projects.com 3
http://wjhwsh.blogspot.co.uk 2
http://192.168.6.52:8080 2
http://wjhwsh.blogspot.cz 2
https://twitter.com 2
http://wjhwsh.blogspot.de 1
http://wjhwsh.blogspot.it 1
http://wildfire.gigya.com 1
http://static.ak.facebook.com 1
http://www.slideee.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Representational State Transfer (REST) is a style of software architecture for distributed systems such as the World Wide Web. The term was introduced in the doctoral dissertation of Roy Fielding in 2000, and has since come into widespread use in the networking community. An important concept in REST is the existence of resources, each of which can be referred to using a global identifier, that is, a URI. In order to manipulate these resources, components of the network, clients and servers, communicate using a standardized interface such as HTTP and exchange representations of these resources.
  • What Are RESTful Web Services? Representational State Transfer (REST) is a software application architecture modeled after the way data is represented, accessed, and modified on the web. In the REST architecture, data and functionality are considered resources, and these resources are accessed using Uniform Resource Identifiers (URIs), typically links on the web. The resources are acted upon by using a set of simple, well-defined operations. The REST architecture is designed to use a stateless communication protocol, typically HTTP. In the REST architecture, clients and servers exchange representations of resources using a standardized interface and protocol. These principles encourages REST applications to be simple, lightweight, and have high performance. RESTful web services are web applications built upon the REST architecture. They: expose resources (data and functionality) through web URIs use the four main HTTP methods to create, retrieve, update, and delete resources RESTful web services typically map the four main HTTP methods to the so-called CRUD actions: create, retrieve, update, and delete. The following table shows a mapping of HTTP methods to these CRUD actions.
  • REST is a set of principles that define how Web standards, such as HTTP and URIs, are supposed to be used (which often differs quite a bit from what many people actually do). The promise is that if you adhere to REST principles while designing your application, you will end up with a system that exploits the Web’s architecture to your benefit. In summary, the five key principles are: * Give every “thing” an ID * Link things together * Use standard methods * Resources with multiple representations * Communicate statelessly Let’s take a closer look at each of these principles.
  • Everything that should be identifiable should obviously get an ID — on the Web, there is a unified concept for IDs: The URI. URIs make up a global namespace, and using URIs to identify your key resources means they get a unique, global ID. an Order resource might be composed of order items, an address and many other aspects that you might not want to expose as individually identifiable resources. Taking the idea of identifying everything that is worth being identified further leads to the creation of resources that you usually don’t see in a typical application design: A process or process step, a sale, a negotiation, a request for a quote — these are all examples of “things” that merit identification. Use URIs to identify everything that merits being identifiable, specifically, all of the “high-level” resources that your application provides, whether they represent individual items, collections of items, virtual and physical objects, or computation results. examples of URIs you might come up with: http://example.com/customers/1234 http://example.com/orders/2007/10/776654 http://example.com/orders/2007/11 http://example.com/products?color=green
  • Everything that should be identifiable should obviously get an ID — on the Web, there is a unified concept for IDs: The URI. URIs make up a global namespace, and using URIs to identify your key resources means they get a unique, global ID. an Order resource might be composed of order items, an address and many other aspects that you might not want to expose as individually identifiable resources. Taking the idea of identifying everything that is worth being identified further leads to the creation of resources that you usually don’t see in a typical application design: A process or process step, a sale, a negotiation, a request for a quote — these are all examples of “things” that merit identification. Use URIs to identify everything that merits being identifiable, specifically, all of the “high-level” resources that your application provides, whether they represent individual items, collections of items, virtual and physical objects, or computation results. examples of URIs you might come up with: http://example.com/customers/1234 http://example.com/orders/2007/10/776654 http://example.com/orders/2007/11 http://example.com/products?color=green
  • REST is a set of principles that define how Web standards, such as HTTP and URIs, are supposed to be used (which often differs quite a bit from what many people actually do). The promise is that if you adhere to REST principles while designing your application, you will end up with a system that exploits the Web’s architecture to your benefit. In summary, the five key principles are: * Give every “thing” an ID * Link things together * Use standard methods * Resources with multiple representations * Communicate statelessly Let’s take a closer look at each of these principles.
  • you can rely on being able to retrieve a representation using GET. Because GET’s semantics are defined in the specification, you can be sure that you have no obligations when you call it — this is why the method is called “safe”. GET supports very efficient and sophisticated caching, so in many cases, you don’t even have to send a request to the server. You can also be sure that a GET is idempotent — if you issue a GET request and don’t get a result, you might not know whether your request never reached its destination or the response got lost on its way back to you. The idempotence guarantee means you can simply issue the request again.
  • The uniform interface also enables every component that understands the HTTP application protocol to interact with your application. Examples of components that benefit from this are generic clients such as curl and wget, proxies, caches, HTTP servers, gateways, even Google/Yahoo!/MSN, and many more. To summarize: For clients to be able to interact with your resources, they should implement the default application protocol (HTTP) correctly, i.e. make use of the standard methods GET, PUT, POST, DELETE.
  • Idempotence is also guaranteed for PUT (which basically means “update this resource with this data, or create it at this URI if it’s not there already”) and for DELETE (which you can simply try again and again until you get a result — deleting something that’s not there is not a problem). POST, which usually means “create a new resource”, can also be used to invoke arbitrary processing and thus is neither safe nor idempotent.
  • REST is a set of principles that define how Web standards, such as HTTP and URIs, are supposed to be used (which often differs quite a bit from what many people actually do). The promise is that if you adhere to REST principles while designing your application, you will end up with a system that exploits the Web’s architecture to your benefit. In summary, the five key principles are: * Give every “thing” an ID * Link things together * Use standard methods * Resources with multiple representations * Communicate statelessly Let’s take a closer look at each of these principles.
  • If you look at the product and customer links in this document, you can easily imagine how an application that has retrieved it can “follow” the links to retrieve more information. the links can point to resources that are provided by a different application, a different server, or even a different company on another continent — because the naming scheme is a global standard, all of the resources that make up the Web can be linked to each other. the service provides a set of links to the client enabling the client to move the application from one state to the next by following a link. links are an extremely useful way to make an application dynamic. Use links to refer to identifiable things (resources) wherever possible. Hyperlinking is what makes the Web the Web Addressability and connectedness. Resources have their representations, but providing representations of resources would be useless if you could not address them. In REST, every resource must have at least one address, that is, one URI. To address the resource, you simply specify the URI. This concept is called "addressability". By publishing your web application, you introduce many different URIs that are connected to each other. Because of that connectedness, the only URI you need to give to your clients is one URI called the "bootstrap URI".
  • REST is a set of principles that define how Web standards, such as HTTP and URIs, are supposed to be used (which often differs quite a bit from what many people actually do). The promise is that if you adhere to REST principles while designing your application, you will end up with a system that exploits the Web’s architecture to your benefit. In summary, the five key principles are: * Give every “thing” an ID * Link things together * Use standard methods * Resources with multiple representations * Communicate statelessly Let’s take a closer look at each of these principles.
  • Using HTTP content negotiation, a client can ask for a representation in a particular format: GET /customers/1234 HTTP/1.1 Host: example.com Accept: application/vnd.mycompany.customer+xml if a client “knows” both the HTTP application protocol and a set of data formats, it can interact with any RESTful HTTP application in the world in a very meaningful way. Provide multiple representations of resources for different needs. a server that can consume data in specific formats does not care about the particular type of client, provided it follows the application protocol. significant benefit of having multiple representations of a resource in practice: If you provide both an HTML and an XML representation of your resources, they are consumable not only by your application, but also by every standard Web browser —information in your application becomes available to everyone who knows how to use the Web. You can turn your application’s Web UI into its Web API — everything that can be done via the UI should also be doable via the API. useful way to get a better Web interface for both humans and other applications.
  • REST is a set of principles that define how Web standards, such as HTTP and URIs, are supposed to be used (which often differs quite a bit from what many people actually do). The promise is that if you adhere to REST principles while designing your application, you will end up with a system that exploits the Web’s architecture to your benefit. In summary, the five key principles are: * Give every “thing” an ID * Link things together * Use standard methods * Resources with multiple representations * Communicate statelessly Let’s take a closer look at each of these principles.
  • REST mandates that state be either turned into resource state, or kept on the client. In other words, a server should not have to retain some sort of communication state for any of the clients it communicates with beyond a single request. The most obvious reason for this is scalability — the number of clients interacting would seriously impact the server’s footprint if it had to keep client state. (Note that this usually requires some re-design — you can’t simply stick a URI to some session state and call it RESTful.) But there are other aspects that might be much more important: The statelessness constraint isolates the client against changes on the server as it is not dependent on talking to the same server in two consecutive requests. A client could receive a document containing links from the server, , the server could be shut down, — and if the client follows one of the links it has received from the server, it won’t notice Statelessness. Statelessness means that a web application is not responsible for keeping any information about the state of its clients. REST does not encompass the concept of HTTP sessions. The client is responsible for tracking its own actions (if it needs to). The service maintains its resources and provides a uniform interface to the clients.
  • Use an annotation to mark the methods that you want the runtime to to call to service the http request. Can either put http method in the annotation or in the method
  • From Göteborg Callista
  • The @ConsumeMime annotation is used to specify which MIME types a resource class, method, or MessageBodyReader can accept. If @ConsumeMime is applied at the class level, all the response methods accept the specified MIME types by default. If @ConsumeMime is applied at the method level, it overrides any @ConsumeMime annotations applied at the class level. @ProduceMime annotation is used to specify the MIME types a resource or MessageBodyWriter can produce and send back to the client. If @ProduceMime is applied at the class level, all the methods in a resource can produce the specified MIME types by default. If it is applied at the method level, it overrides any @ProduceMime annotations applied at the class level.
  • Multiple parameters may be extracted from the URI using the PathParam or QueryParam annotations Query parameters are extracted from the request URI query parameters, and are specified by using the javax.ws.rs.QueryParam annotation in the method parameter arguments. URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation. URI parameters are specified using the javax.ws.rs.PathParam annotation in the method parameter arguments.
  • Query parameters are extracted from the request URI query parameters, and are specified by using the QueryParam annotation in the method parameter arguments. URI parameters are extracted from the request URI, and the parameter names correspond to the URI Template variable names specified in the @Path class-level annotation. URI parameters are specified using the @PathParam annotation in the method parameter arguments.
  • @QueryParam and @PathParam can only be used on the following types: ■ all primitive types except char ■ all wrapper classes of primitive types except Character ■ String ■ any class with the static method valueOf(String) ■ any class with a constructor that takes a single String as a parameter ■ List , where T matches the already listed criteria
  • The HTTP specification defines what HTTP response codes should be on a successful request. For example, GET should return 200, OK and PUT should return 201, CREATED. You can expect JAX-RS to return the same default response codes. Sometimes, however, you need to specify your own response codes, or simply to add specific headers or cookies to your HTTP response. JAX-RS provides a Response class for this.
  • The uniform interface also enables every component that understands the HTTP application protocol to interact with your application. Examples of components that benefit from this are generic clients such as curl and wget, proxies, caches, HTTP servers, gateways, even Google/Yahoo!/MSN, and many more. To summarize: For clients to be able to interact with your resources, they should implement the default application protocol (HTTP) correctly, i.e. make use of the standard methods GET, PUT, POST, DELETE.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • REST is a set of principles that define how Web standards, such as HTTP and URIs, are supposed to be used (which often differs quite a bit from what many people actually do). The promise is that if you adhere to REST principles while designing your application, you will end up with a system that exploits the Web’s architecture to your benefit. In summary, the five key principles are: * Give every “thing” an ID * Link things together * Use standard methods * Resources with multiple representations * Communicate statelessly Let’s take a closer look at each of these principles.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.
  • To obtain an container managed EntityManager instance, inject the entity manager into the application component: @PersistenceContext EntityManager em; you don't need any cm lifecycle methods With a container-managed entity manager, an EntityManager instance's persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction, these components usually need access to a single persistence context. This occurs when an EntityManager is injected into the application components via the javax.persistence.PersistenceContext annotation. The persistence context is automatically propagated with the current JTA transaction, and EntityManager references that are mapped to the same persistence unit provide access to the persistence context within that transaction. By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.

Secure REST with JAX-RS Presentation Transcript

  • 1. Secure REST with JAX-RS Carol McDonald, Java Architect
  • 2. Agenda
    • REST Primer
    • 3. RESTful Design and API Elements
    • 4. Building a Simple Service
    • 5. Security
    • 6. Q & A
  • 7. REpresentational State Transfer
    • Get
    • 8. http://www.depot.com/parts
    Response XML data = REpresentational State Transfer
        • The URL identifies the resource
        • 9. HTTP GET method operates on the resource
        • 10. html page is transferred to the browser
          • REpresentational State transfer
        • The page ( application state ) is stored on the client (browser)
        • 11. Click on the link (resource) in page ( hypermedia )
          • New state transfer occurs
  • 12. REST Tenets
    • Resources ( nouns )
      • Identified by a URI , For example:
        • http://www.parts-depot.com/parts
    • Methods ( verbs ) to manipulate the nouns
      • Small fixed set:
        • GET, PUT, POST, DELETE
          • Read, Update, Create, Delete
    • Representation of the Resource
      • data and state transferred between client and server
      • 13. XML, JSON ...
    • Use verbs to exchange application state and representation
  • 14. HTTP Example Request GET /music/artists/beatles/recordings HTTP/1.1 Host: media.example.com Accept: application/xml Response HTTP/1.1 200 OK Date: Tue, 08 May 2007 16:41:58 GMT Server: Apache/1.3.6 Content-Type: application/xml; charset=UTF-8 <?xml version=&quot;1.0&quot;?> <recordings xmlns=&quot;…&quot;> <recording>…</recording> … </recordings> Method Resource Representation State transfer
  • 15. REST in Five Steps*
    • Everything is a Resource
    • 16. All Resources expose a standard interface
    • 17. Link things together
    • 18. Multiple representations
    • 19. Stateless communications
    Uniform Interface
  • 20. Everything is a Resource Every resource has an id, URI is the id
    • Everything is a Resource
    • a Resource has an Identifier
      • http://company.com/customers/123456
  • 21. Every Resource has an Id http://company.com/customers/123456 Resource Collection name Primary key http://company.com/customers/123456/orders/12 http://example.com/orders/2007/11 http://example.com/products?color=green URI is the id, Every resource has a URI
    • URIs identify :
      • items, collections of items, virtual and physical objects, or computation results.
  • 22. REST in Five Steps*
    • Give everything an ID
    • 23. All Resources expose a standard interface
      • use Standard methods: GET,PUT,POST,DELETE
    • Link things together
    • 24. Multiple representations
    • 25. Stateless communications
    Uniform Interface
  • 26. Use Standard HTTP Methods
    • Example
        • GET /store/customers/123456
  • 27. Use Standard Methods:
    • /orders
      • GET - list all orders
      • 28. POST - submit a new order
    • /orders/{order-id}
      • GET - get an order representation
      • 29. PUT - update an order
      • 30. DELETE - cancel an order
    • /orders/average-sale
      • GET - calculate average sale
    • /customers
      • GET - list all customers
      • 31. POST - create a new customer
    • /customers/{cust-id}
      • GET - get a customer representation
      • 32. DELETE- remove a customer
    • /customers/{cust-id}/orders
      • GET - get the orders of a customer
    Order Customer Mgmt Example http://www.infoq.com/articles/rest-introduction
  • 33. Use Standard HTTP Methods
    • HTTP Get, Head
      • Should not modify anything
      • 34. Cache-able
        • With Correct use of Last-Modified and ETag
    • Idempotency:
      • PUT, DELETE, GET, HEAD can be repeated and the results are the same
  • 35. REST in Five Steps*
    • Give everything an ID
    • 36. Use standard methods
    • 37. Link things together
    • 38. Multiple representations
    • 39. Stateless communications * Inspired by Stefan Tilkov: http://www.innoq.com/blog/st/presentations/2008/2008-03-13-REST-Intro--QCon-London.pdf
  • 40. Link Things Together
    • Representations contain links to other resources
    • 41. Service provides links in response to the Client
      • Enables client to move the application from one state to the next by following a link
    Representations contain links to other resources: <prop self=&quot; http://example.com/orders/101230 &quot;> <customer ref=&quot; http://example.com/customers/bar &quot;> <product ref=&quot; http://example.com/products/21034 &quot;/> <amount value=&quot;1&quot;/> </order>
  • 42. REST in Five Steps*
    • Give everything an ID
    • 43. Use standard methods
    • 44. Link things together
    • 45. Multiple representations
    • 46. Stateless communications * Inspired by Stefan Tilkov: http://www.innoq.com/blog/st/presentations/2008/2008-03-13-REST-Intro--QCon-London.pdf
  • 47. Multiple Representations
    • Offer data in a variety of formats, for different needs
      • XML
      • 48. JSON
      • 49. (X)HTML
    • Support content negotiation
      • Accept header GET /foo Accept: application/json
      • 50. URI-based GET / foo.json
  • 51. content negotiation Multiple Representations Content-type HTTP header Accept HTTP header Request GET /music/artists/beatles/recordings HTTP/1.1 Host: media.example.com Accept : application/xml Response HTTP/1.1 200 OK Date: Tue, 08 May 2007 16:41:58 GMT Server: Apache/1.3.6 Content-Type : application/xml; charset=UTF-8 <?xml version=&quot;1.0&quot;?> <recordings xmlns=&quot;…&quot;> <recording>…</recording> … </recordings> Format Representation
  • 52. REST in Five Steps*
    • Give everything an ID
    • 53. Use standard methods
    • 54. Link things together
    • 55. Multiple representations
    • 56. Stateless communications * Inspired by Stefan Tilkov: http://www.innoq.com/blog/st/presentations/2008/2008-03-13-REST-Intro--QCon-London.pdf
  • 57. Stateless Communications
    • HTTP protocol is stateless
    • 58. Everything required to process a request contained in the request
      • No client session on the server
      • 59. Eliminates many failure conditions
    • application state kept on Client
    • 60. Service responsible for resource state
  • 61. Common Patterns: Container, Item Server in control of URI
    • Container – a collection of items
    • 62. List catalog items: GET /catalog/items
    • 63. Add item to container: POST /catalog/items
      • with item in request
      • 64. URI of item returned in HTTP response header
      • 65. e.g. http://host/ catalog/items/1
    • Update item: PUT /catalog/items/1
      • with updated item in request
    Good example: Atom Publishing Protocol
  • 66. Common Patterns: Map, Key, Value Client in control of URI
    • List key-value pairs : GET /map
    • 67. Put new value to map: PUT /map/{key}
      • with entry in request
      • 68. e.g. PUT /map/dir/contents.xml
    • Read value: GET /map/{key}
    • 69. Update value: PUT /map/{key}
      • with updated value in request
    • Remove value: DELETE /map/{key}
    • 70. Good example: Amazon S3
  • 71. Key Benefits
    • Server side
      • Uniform Interface
      • 72. Cacheable
      • 73. Scalable
      • 74. Easy failover
    • Client side
      • Easy to experiment in browser
      • 75. Broad programming language support
      • 76. Choice of data formats
      • 77. bookmarkable
  • 78. Agenda
    • REST Primer
    • 79. RESTful Design and API Elements with JAX-RS
    • 80. Building a Simple Service
    • 81. Status
    • 82. Q & A
  • 83. JAX-RS: Clear mapping to REST concepts
    • High level, Declarative
      • Uses @ annotation in POJOs
    • Jersey – reference implementation of JSR 311
        • Download it from http://jersey.dev.java.net
        • 84. Comes with Glassfish, Java EE 6
        • 85. Tools support in NetBeans
  • 86. Resources
    • Resource class
      • POJO, No required interfaces
    • ID provided by @Path annotation
      • Relative to deployment context
      • 87. Annotate class or “ sub-resource locator” method
    http://host/ctx/orders/12 http://host/ctx/orders/12/customer @Path( &quot;orders/{id}&quot;) public class OrderResource { @Path(&quot;customer&quot;) CustomerResource getCustomer(...) {...} }
  • 88. Request Mapping
    • Annotate resource class methods with standard method
      • @GET , @PUT , @POST , @DELETE , @HEAD
    • annotations on parameters specify mapping from request data
    • 89. Return value mapped to http response
    @Path(&quot;orders/ {order_id} &quot;) public class OrderResource { @GET Order getOrder( @PathParam (&quot; order_id &quot;) String id) { ... } }
  • 90.  
  • 91. Multiple Representations Static and dynamic content negotiation
    • Annotate methods or classes
      • @Produces matches Accepts header
      • 92. @Consumes matches Content-Type header
    @GET @Consumes(&quot;application/json&quot;) @Produces({&quot;application/xml&quot;,&quot;application/json&quot;}) String getOrder(@PathParam(&quot;order_id&quot;) String id) { ... }
  • 93. Multiple Representations : JAX-RS consuming
    • Annotated method parameters extract client request information
      • @PathParam extracts information from the request URI
      • 94. @QueryParam extracts information from the request URI query parameters
    http://host/catalog/items/ 123 http://host/catalog/items/ ?start=0
  • 95. Multiple Representations : JAX-RS consuming http://host/catalog/items/?start=0 http://host/catalog/items/123 @Path(&quot;/items/&quot;) @ConsumeMime(“application/xml”) public class ItemsResource { @GET ItemsConverter get( @QueryParam (&quot;start&quot;) int start ) { ... } @Path( &quot;{id}/&quot; ) ItemResource getItemResource( @PathParam (&quot;id&quot;)Long id ){ ... } }
  • 96. Multiple Representations : Supported Types
    • JAX-RS can automatically (un)-marshall between HTTP request/response and Java types
    • “Out-of-the-box” support for the following
      • text/xml, application/xml, application/json – JAXB class
      • 97. */* – byte[]
      • 98. text/* – String
      • 99. application/x-www-form-urlencoded - MultivaluedMap<String, String>
    response
  • 100. Multiple Representations @Post @ConsumeMime(“application/x-www-form-urlencoded”) @ProduceMime(“application/xml”) public JAXBClass updateEmployee( MultivalueMap<String, String> form) { ... Converted to a map for accessing form's field converted to XML
  • 101. Multiple Representations : producing a response Use Response class to build “created”response @Path(“/items”) class Items { @POST @ProduceMime(“application/xml”) Response create(Ent e) { // persist the new entry, create URI return Response.created ( uriInfo.getAbsolutePath(). resolve(uri+&quot;/&quot;)).build(); } }
  • 102. Uniform interface: HTTP request and response C: POST /items HTTP/1.1 C: Host: host.com C: Content-Type: application/xml C: Content-Length: 35 C: C: <item><name>dog</name></item> S: HTTP/1.1 201 Created S: Location: http://host.com/employees/1234 S: Content-Length: 0
  • 103. Response Codes and Custom Responses
    • JAX-RS returns default response codes
      • GET returns 200 OK
      • 104. PUT returns 201 CREATED
    • See
      • http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
    200 OK 201 Created 202 Accepted 203 Non-Authoritative Information 204 No Content 205 Reset Content 206 Partial Content 207 Multi-Status 226 IM Used . . .
  • 105. JAX-RS provides Response class @PUT public Response putUser( @PathParam(“id”) int id) { if (!id.equals(userid) ) return Response .status(409).entity( &quot;userids differ&quot;).build();
      • JAX-RS provides Response class:
        • to specify response codes, to add onto the response
    • can construct more sophisticated return result
    • 106. Can build responses for redirects, errors, ok, setting headers, etc
  • 107. WebApplicationException Example @GET public Employee getEmployee( @PathParam(“id”) int id) { if (!doesEmployeeExist(id)) throw new WebApplicationException( new Throwable(&quot;Resource for &quot; + uriInfo.getAbsolutePath() + &quot; does not exist.&quot;), 404); Response: HTTP Status 404 -
    • Use it when the method has a return type
    • 108. Simple error indicator
  • 109. Link Things Together
    • UriInfo provides information about the request URI and the route to the resource
    • 110. UriBuilder provides facilities to easily build URIs for resources
    @Context UriInfo info ; OrderResource r = ... UriBuilder b = info.getBaseUriBuilder(); URI u = b.path(OrderResource.class).build(r.id);
  • 111. Statelessness: JAX-RS
    • The default component lifecycle is per-request
      • A new instance created for every request
      • 112. Reduces concurrency issues
    • HTTP session life-cycle is not supported
      • On server side Developer must model state
        • As resource state in the representations
  • 113. Agenda
    • REST Primer
    • 114. RESTful Design and API Elements
    • 115. Building a Simple Service
    • 116. Deployment Options
    • 117. Status
  • 118. Example RESTful Catalog
  • 119. Example RESTful Catalog Service Catalog Database Web container (GlassFish™) + REST API Browser (Firefox) HTTP
  • 120. URIs and Methods:
    • /items
      • GET - list all items
      • 121. POST – add item to catalog
    • /items/{id}
      • GET - get an item representation
      • 122. PUT - update an item
      • 123. DELETE – remove an item
    Item Catalog Example http://www.infoq.com/articles/rest-introduction
  • 124. Methods Java method name is not significant The @HTTP method is the method @Path(“/items”) class ItemsResource { @GET Items get() { ... } @POST Response create(Item) { ... } } class ItemResource { @GET Item get(...) { ... } @PUT void update(...) { ... } @DELETE void delete(...) { ... } }
  • 125. RESTful Catalog
        • Dojo client, JAX-RS, JAXB, JPA
    DB Registration Application JAX-RS class Dojo client JAXB class Entity Class ItemsConverter Item ItemsResource
  • 126. Entity Classes
    • Use JPA to map/retrieve data from the database as entities
    • 127. expose entities as RESTful resources
      • entity = resource identified by URL
    http://host/catalog/items/123 public class Item { int id; String name; String descr; String url; } @Entity @Id Item ID NAME DESC URL
  • 128. Converter Classes
    • JAXB to convert the domain objects (JPA entities ) into XML and/or JSON .
    DB JAX-RS class Dojo client JAXB class Entity Class ItemsConverter Item ItemsResource
  • 129. ItemConverter JAXB annotated @XmlRootElement(name = &quot;item&quot;) public class ItemConverter { private Item entity; private URI uri; @XmlAttribute public URI getUri() { return uri; } @XmlElement public Long getId() { return (expandLevel > 0) ? entity.getId() : null; } ... }
  • 130. XML <item uri=&quot;http://localhost/Web/resources/items/1/&quot; > <description> black cat is nice</description> <id>1</id> <imagethumburl>/images/anth.jpg</imagethumburl> <name>not Friendly Cat</name> <price>307.10</price> <productid>feline01</productid> </item>
  • 131. JSON { &quot;@uri&quot;:&quot;http://host/catalog/resources/items/1/&quot;, &quot;name&quot;:&quot;Friendly Cat&quot;, &quot;description&quot;:&quot;This black and white colored cat is super friendly.&quot;, &quot;id&quot;:&quot;1&quot;, &quot;imageurl&quot;:&quot; http://localhost:8080/CatalogService/images/anthony.jpg &quot; }
  • 132. ItemsConverter JAXB annotated @XmlRootElement(name = &quot;items&quot;) public class ItemsConverter { private Collection<ItemConverter> items; private URI uri; @XmlAttribute public URI getUri() { return uri; } @XmlElement public Collection<ItemConverter> getItem() { ... return items; } }
  • 133. XML <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <items uri=&quot;http://localhost/Web/resources/items/&quot;> <item uri=&quot;http://localhost/Web/resources/items/1/&quot; > <description> black cat is nice</description> <id>1</id> <imagethumburl>/images/anth.jpg</imagethumburl> <name>not Friendly Cat</name> <price>307.10</price> <productid>feline01</productid> </item> <item . . . </item> </items>
  • 134. JSON { &quot;@uri&quot;:&quot;http://host/catalog/resources/items/&quot;, &quot; item &quot;:[ {&quot;@uri&quot;:&quot;http://host/catalog/resources/items/1/&quot;, &quot;name&quot;:&quot;Friendly Cat&quot;, &quot;description&quot;:&quot;This black and white colored cat is super friendly.&quot;, &quot;id&quot;:&quot;1&quot;, &quot;imageurl&quot;:&quot;http://localhost:8080/CatalogService/images/anthony.jpg&quot;}, {&quot;@uri&quot;:&quot;http://host/catalog/resources/items/2/&quot;, &quot;name&quot;:&quot;Fluffy Cat&quot;, &quot;description&quot;:&quot;A great pet for a hair stylist! &quot;id&quot;:&quot;2&quot;, &quot;imageurl&quot;:&quot;http://localhost:8080/CatalogService/images/bailey.jpg&quot;} ] }
  • 135. Resource Classes
      • Items Resource retrieves updates a collection of Item entities
      • 136. /items – URI for a list of Items
      • 137. Item resource retrieves or updates one Item entity
      • 138. /item/1 – URI for item 1
    DB JAX-RS class Dojo client JAXB class Entity Class ItemsConverter Item ItemsResource
  • 139. Get Items @Path(&quot;/items/&quot;) public class ItemsResource { @Context protected UriInfo uriInfo; @GET @Produces (&quot;application/json&quot;) public ItemsConverter get(){ return new ItemsConverter( getEntities(), uriInfo.getAbsolutePath()); } Performs JPA Query, returns list of entities JAXB class responds with JSON responds to the URI http://host/catalog/items/ responds to HTTP GET
  • 140. Get Item @Path(&quot;/items/&quot;) public class ItemsResource { @Path(&quot;{id}/&quot;) public ItemResource getItemResource( @PathParam (&quot;id&quot;) Long id) { return new ItemResource (id, context); } } public class ItemResource { @GET @Produces ( &quot;application/json&quot;) public ItemConverter get() { return new ItemConverter(getEntity(), context.getAbsolutePath(), expandLevel); } JAXB class http://host/catalog/items/123
  • 141. Agenda
    • REST Primer
    • 142. RESTful Design and API Elements
    • 143. Building a Simple Service
    • 144. Security
    • 145. Q & A
  • 146. Securing your REST Web Service
    • Authentication for Identity Verification
    • 147. Authorizaton
    • 148. Encryption
  • 149. Authentication: Configure web.xml <login-config> <auth-method>BASIC</auth-method> <realm-name>admin</realm-name> </login-config>
  • 150. Authentication: Configure web.xml <login-config> <auth-method>BASIC</auth-method> <realm-name>admin</realm-name> </login-config>
    • Login-config:
      • defines how HTTP requests should be authenticated
    • Auth-method:
      • BASIC, DIGEST, or CLIENT_CERT. corresponds to Basic, Digest, and Client Certificate authentication, respectively.
    • Realm-name:
      • Name for database of users and groups that identify valid users of a web application
    realm
  • 151. Authentication: Configure web.xml <security-constraint> <web-resource-collection> <url-pattern>/secure/*</url-pattern> <http-method>POST</http-method> </web-resource-collection> ...
    • security constraint
      • defines access privileges to a collection of resources
    • url-pattern:
      • URL pattern you want to secure
    • Http-method:
      • Methods to be protected
  • 152. Authentication: Configure web.xml <security-constraint> ... <auth-constraint> <description>only let admin login </description> <role-name>admin</role-name> </auth-constraint>
    • auth-constraint:
      • names the roles authorized to access the URL patterns and HTTP methods declared by this security constraint
  • 153. Encryption: Configure web.xml <security-constraint> ... <user-data-constraint> <description>SSL</description> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint>
    • user-data-constraint: NONE, INTEGRAL, or CONFIDENTIAL
      • how the data will be transported between client and server
  • 154. Authentication: Configure web.xml <security-role> <role-name>admin</role-name> </security-role>
    • security-role:
      • lists all of the security roles used in the application
      • 155. For every <role-name> used in <auth-constraints> must define a corresponding <security-role>
    • http://java.sun.com/javaee/5/docs/tutorial/doc/bncas.html
  • 156. Authentication: map roles to realm <sun-web-app> <security-role-mapping> <role-name>admin</role-name> <principal-name> admin </principal-name> </security-role-mapping> </sun-web-app>
    • security-role-mapping:
      • Assigns security role to a group or user in Application Server realm
    • Realm:
      • database of users and groups that identify valid users of a web application (FILE, LDAP
    LDAP realm
  • 157. Authentication: map roles to realm file realm
  • 158. Authorization Annotations @Path(&quot;/customers&quot;) @RolesAllowed({&quot;ADMIN&quot;, &quot;CUSTOMER&quot;}) public class CustomerResource { @GET @Path(&quot;{id}&quot;) @Produces(&quot;application/xml&quot;) public Customer getCustomer(@PathParam(&quot;id&quot;) int id) {...} @RolesAllowed(&quot;ADMIN&quot;) @POST @Consumes(&quot;application/xml&quot;) public void createCustomer(Customer cust) {...} @PermitAll @GET @Produces(&quot;application/xml&quot;) public Customer[] getCustomers() {} } roles permitted to execute operation any authenticated user
  • 159. JAX-RS Security Context public interface SecurityContext { public Principal getUserPrincipal(); public boolean isUserInRole(String role); public boolean isSecure(); public String getAuthenticationScheme(); } Determine the identity of the user check whether user belongs to a certain role whether this request was made using a secure channel
  • 160. JAX-RS Security Context @Path(&quot;/customers&quot;) public class CustomerService { @GET @Produces(&quot;application/xml&quot;) public Customer[] getCustomers(@Context SecurityContext sec ) { if ( sec.isSecure () && ! sec.isUserInRole (&quot;ADMIN&quot;)){ logger.log( sec.getUserPrincipal () + &quot; accessed customer database.&quot;); } ... } } Determine the identity of the user check whether user belongs to a certain role
  • 161. Java EE 6
    • JAX-RS is part of Java EE 6
    • 162. Applications deployed in a Java EE 6 Web container will have access to additional resources:
      • Resources @Resources
      • 163. EJB @EJB
      • 164. ...
    • Stateless session EJBs as resource classes
    • 165. More portable deployment with Servlet 3.0
  • 166. Agenda
    • REST Primer
    • 167. RESTful Design and API Elements
    • 168. Building a Simple Service
    • 169. Deployment Options
    • 170. Status
  • 171. Summary
    • REST architecture is gaining popularity
      • Simple, scalable and the infrastructure is already in place
    • JAX-RS (JSR-311) provides a high level declarative programming model
      • http://jersey.dev.java.net
  • 172. For More Information
    • Reference Implementation
      • http://jersey.dev.java.net/
    • Marc's Blog
      • http://weblogs.java.net/blog/mhadley/
    • Paul's Blog
      • http://blogs.sun.com/sandoz/
    • http://java.sun.com/javaee/5/docs/tutorial/doc/bncas.html
    • 173. Carol's Blog
      • http://weblogs.java.net/blog/caroljmcdonald/
  • 174. For More Information
    • RESTful Java with JAX-RS
  • 175.
    • Presenter’s Name
      • [email_address]
    Carol McDonald Java Architect http://weblogs.java.net/blog/caroljmcdonald/