Rest with Java EE 6 , Security , Backbone.js

67
REST with JAX-RS, Security, Java EE 6 Carol McDonald

Transcript of Rest with Java EE 6 , Security , Backbone.js

Page 1: Rest with Java EE 6 , Security , Backbone.js

REST with JAX-RS, Security, Java EE 6

Carol McDonald

Page 2: Rest with Java EE 6 , Security , Backbone.js

Agenda

• REST Primer• RESTful Design and API Elements• Building a Simple Service

• Security

• Q & A

Page 3: Rest with Java EE 6 , Security , Backbone.js

REpresentational State Transfer

Client State1

Client State2

REST Web Service

Get http://www.depot.com/parts

Response XML data =REpresentational State

Transfer

The URL identifies the resourceClick on the url (resource) in page (hypermedia)

html page is transferred to the browser REpresentational State transfer occurs

Page 4: Rest with Java EE 6 , Security , Backbone.js

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> XML, JSON...

• Use verbs to exchange application state and representation

Page 5: Rest with Java EE 6 , Security , Backbone.js

Request: GET http://localhost:8080/RestfulCustomer/webresources/model.customer/1

Status: 200 (OK)

Time-Stamp: Fri, 14 Dec 2012 02:19:34 GMT

Received: {"name":"Jumbo Eagle Corp","state":"FL","customerId":1,"addressline1":"111 E. Las Olivas Blvd","addressline2":"Suite 51","city":"Fort Lauderdale","phone":"305-555-0188","fax":"305-555-0189","email":"[email protected]","creditLimit":100000}

method resource

representation

Page 6: Rest with Java EE 6 , Security , Backbone.js

Rest Uniform Interface:Every thing is a Resource

Every resource has an id, URI is the idhttp://company.com/customers/123456

Page 7: Rest with Java EE 6 , Security , Backbone.js

Every Resource has an Id

http://company.com/customers/123456

Resource Collection name

Primary key

http://company.com/customers/123456/orders/12http://example.com/orders/2007/11http://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.

Page 8: Rest with Java EE 6 , Security , Backbone.js

Rest Standard Interface:Use Standard HTTP Methods

• ExampleGET /store/customers/123456

Page 9: Rest with Java EE 6 , Security , Backbone.js

Use Standard Methods:

• /orders– GET - list all orders– POST - submit a new order

/orders/{order-id}> GET - get an order representation> PUT - update an order> DELETE - cancel an order

/orders/average-sale– GET - calculate average sale

• /customers– GET - list all customers– POST - create a new customer

/customers/{cust-id}> GET - get a customer representation> DELETE- remove a customer

/customers/{cust-id}/orders– GET - get the orders of a customer

Order CustomerMgmt Example

http://www.infoq.com/articles/rest-introduction

Page 10: Rest with Java EE 6 , Security , Backbone.js

Use Standard HTTP Methods

• HTTP Get, Head> Should not modify anything > Cache-able

With Correct use of Last-Modified and ETag

• Idempotency:

> PUT, DELETE, GET, HEAD can be repeated and the results are the same

Page 11: Rest with Java EE 6 , Security , Backbone.js

Link things together

• Hypermedia

• As

• The

• Engine

• Of

• Application

• State

HATEOAS

© Availity, LLC | All rights reserved.

Page 12: Rest with Java EE 6 , Security , Backbone.js

Link Things Together

<prop self="http://example.com/orders/101230"> <customer ref="http://example.com/customers/bar"> <product ref="http://example.com/products/21034"/> <amount value="1"/></order>

• 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:

Page 13: Rest with Java EE 6 , Security , Backbone.js

Example

© Availity, LLC | All rights reserved.

http://www.infoq.com/articles/webber-rest-workflow

Page 14: Rest with Java EE 6 , Security , Backbone.js

Example

© Availity, LLC | All rights reserved.

Page 15: Rest with Java EE 6 , Security , Backbone.js

Multiple Representations

• Offer data in a variety of formats, for different needs> XML> JSON> (X)HTML

• Support content negotiation> Accept header

GET /fooAccept: application/json

> URI-basedGET /foo.json

> Response header> Content-Type application/xml

Page 16: Rest with Java EE 6 , Security , Backbone.js

Request: http://localhost:8080/RestfulCustomer/webresources/application.wadl

Status: 200 (OK)

Time-Stamp: Fri, 14 Dec 2012 03:11:50 GMT

Received:

<?xml version="1.0" encoding="UTF-8"?>        <resources base="http://localhost:8080/RestfulCustomer/webresources/">            <resource path="model.customer">                <method id="findAll" name="GET">                    <response>                        <representation mediaType="application/xml"/>                        <representation mediaType="application/json"/>                    </response>                </method>

content negotiation

Page 17: Rest with Java EE 6 , Security , Backbone.js

Stateless Communications

• HTTP protocol is stateless

• Everything required to process a request contained in the request> No client session on the server> Eliminates many failure conditions

• application state kept on Client • Service responsible for resource state

Page 18: Rest with Java EE 6 , Security , Backbone.js

Rest Common Patterns: Container, ItemServer in control of URI

• Container – a collection of items

• List catalog items: GET /catalog/items• Add item to container: POST /catalog/items

> with item in request> URI of item returned in HTTP response header> e.g. http://host/catalog/items/1

• Update item: PUT /catalog/items/1 > with updated item in request

Good example: Atom Publishing Protocol

Page 19: Rest with Java EE 6 , Security , Backbone.js

Common Patterns: Map, Key, ValueClient in control of URI

• List key-value pairs: GET /map• Put new value to map: PUT /map/{key}

> with entry in request> e.g. PUT /map/dir/contents.xml

• Read value: GET /map/{key}• Update value: PUT /map/{key}

> with updated value in request

• Remove value: DELETE /map/{key}

• Good example: Amazon S3

Page 20: Rest with Java EE 6 , Security , Backbone.js

Rest Key Benefits

• Server side> Uniform Interface> Cacheable> Scalable> Easy failover

• Client side> Easy to experiment in browser> Broad programming language support> Choice of data formats

Page 21: Rest with Java EE 6 , Security , Backbone.js

Agenda

• REST Primer• RESTful Design and API Elements with JAX-RS• Building a Simple Service

• Status

• Q & A

Page 22: Rest with Java EE 6 , Security , Backbone.js

JAX-RS: Clear mapping to REST concepts

• High level, Declarative> Uses @ annotation in POJOs

• Jersey – reference implementation of JSR 311Download it from http://jersey.dev.java.netComes with Glassfish, Java EE 6Tools support in NetBeans

Page 23: Rest with Java EE 6 , Security , Backbone.js

Resources

• Resource class> POJO, No required interfaces

• ID provided by @Path annotation> Relative to deployment context> Annotate class or “sub-resource locator” method

@Path("orders/{id}")public class OrderResource { @Path("customer") CustomerResource getCustomer(...) {...}}

http://host/ctx/orders/12

http://host/ctx/orders/12/customer

Page 24: Rest with Java EE 6 , Security , Backbone.js

Request Mapping

• Annotate resource class methods with standard method> @GET, @PUT, @POST, @DELETE, @HEAD

• annotations on parameters specify mapping from request data

• Return value mapped to http response

@Path("orders/{order_id}")public class OrderResource { @GET Order getOrder(@PathParam("order_id") String id) { ... }}

Page 25: Rest with Java EE 6 , Security , Backbone.js
Page 26: Rest with Java EE 6 , Security , Backbone.js

Multiple RepresentationsStatic and dynamic content negotiation

• Annotate methods or classes > @Produces matches Accepts header> @Consumes matches Content-Type header

@GET@Consumes("application/json")@Produces({"application/xml","application/json"})String getOrder(@PathParam("order_id") String id) { ...}

Page 27: Rest with Java EE 6 , Security , Backbone.js

Multiple Representations: JAX-RS consuming

@Path("/items/")@ConsumeMime(“application/xml”)public class ItemsResource {

@GET ItemsConverter get(@QueryParam("start")

int start) {...

}

@Path("{id}/") ItemResource getItemResource(@PathParam("id")Long id){ ... }

}

http://host/catalog/items/?start=0

http://host/catalog/items/123

Page 28: Rest with Java EE 6 , Security , Backbone.js

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

Page 29: Rest with Java EE 6 , Security , Backbone.js

Multiple Representations: producing a 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+"/")).build(); }}

Use Response classto build “created”response

Page 30: Rest with Java EE 6 , Security , Backbone.js

Uniform interface: HTTP request and response

C: POST /items HTTP/1.1C: Host: host.comC: Content-Type: application/xmlC: Content-Length: 35C: C: <item><name>dog</name></item>

S: HTTP/1.1 201 CreatedS: Location: http://host.com/employees/1234S: Content-Length: 0

Page 31: Rest with Java EE 6 , Security , Backbone.js

Link Things Together• UriInfo provides information about the request URI and the

route to the resource• 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);

Page 32: Rest with Java EE 6 , Security , Backbone.js

Agenda

• REST Primer

• RESTful Design and API Elements

• Building a Simple Service

• Deployment Options• Status

Page 33: Rest with Java EE 6 , Security , Backbone.js

Example RESTful Catalog

Page 34: Rest with Java EE 6 , Security , Backbone.js

URIs and Methods:

/items– GET - list all items– POST – add item to catalog

/items/{id}> GET - get an item representation> PUT - update an item> DELETE – remove an item

Item Catalog Example

http://www.infoq.com/articles/rest-introduction

Page 35: Rest with Java EE 6 , Security , Backbone.js

Methods

@Path(“/items”)class ItemsResource { @GET public List<Item> findAll() { ... } @POST Response create(Item) { ... } @PUT @Path("{id}") public void editp(Item entity) {} @GET @Path("{id}") public Item find(@PathParam("id")

Integer id) { ... }

}Java method name is not significantThe @HTTP method is the method

Page 36: Rest with Java EE 6 , Security , Backbone.js

RESTful Catalog

DB

Registration Application

JAX-RS class

javascript client

JSON class

Entity Class

Item

ItemsResource

Javascript client, JAX-RS, JSON, JPA

Page 37: Rest with Java EE 6 , Security , Backbone.js

Item Entity JAXB annotated @Entity@Table(name = "ITEM")@XmlRootElementpublic class Item implements Serializable { @Id private Integer id; ... }

Page 38: Rest with Java EE 6 , Security , Backbone.js

XML

<item uri="http://localhost/Web/resources/items/1/"> <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>

Page 39: Rest with Java EE 6 , Security , Backbone.js

JSON

{ "@uri":"http://host/catalog/resources/items/1/", "name":"Friendly Cat", "description":"This black and white colored cat is super friendly.", "id":"1", "imageurl":"http://localhost:8080/CatalogService/images/anthony.jpg" }

Page 40: Rest with Java EE 6 , Security , Backbone.js

Resource Classes

> Items Resource retrieves updates a collection of Item entities

> /items – URI for a list of Items> /item/1 – URI for item 1

DB

JAX-RS class

Dojo client

Entity Class

Item

ItemsResource

Page 41: Rest with Java EE 6 , Security , Backbone.js

Get Items

@Path("/items/")public class ItemsResource {

@GET @Produces("application/json") public List<Item> get(){ CriteriaQuery cq = getEntityManager(). getCriteriaBuilder().createQuery(); cq.select(cq.from(Item)); return getEntityManager().createQuery (cq).getResultList(); }

Performs JPAQuery, returns listof entities

JAXB class

responds with JSON

responds to the URI http://host/catalog/items/

responds to HTTP GET

Page 42: Rest with Java EE 6 , Security , Backbone.js

JQuery Client

var rootURL = "http://localhost:8080/catalog/resources/item";

// Retrieve item list

function findAll() {    

$.ajax({        

type: 'GET',        

url: rootURL,        

dataType: "json",        

success: renderList     });

}function renderList(data) {     var list =data;    

$('#itemList li').remove();    

$.each(list, function(index, item) {        

$('#itemList').append('<li><a href="#" data-identity="' + item.id + '">'+item.name+'</a></li>');

    });

}

Page 43: Rest with Java EE 6 , Security , Backbone.js

Backbone.js client

© Availity, LLC | All rights reserved.

Page 44: Rest with Java EE 6 , Security , Backbone.js

MVC

© Availity, LLC | All rights reserved.

Page 45: Rest with Java EE 6 , Security , Backbone.js

Backbone.sync maps CRUD requests  to REST

© Availity, LLC | All rights reserved.

Save (new) → create → HTTP POST   /urlFetch → read → GET   /url/idSave → update → PUT   /url/idDestroy → delete → DELETE   /url/id

Page 46: Rest with Java EE 6 , Security , Backbone.js

backbone Client

window.Item = Backbone.Model.extend({

urlRoot: "resources/items",

defaults: {

id: null,

name: "",

description: "",

imageurl: null

}

});

window.ItemCollection = Backbone.Collection.extend({

model: Item,

url: "resources/items"

});

Page 47: Rest with Java EE 6 , Security , Backbone.js

Agenda

• REST Primer

• RESTful Design and API Elements

• Building a Simple Service

• Security

• Q & A

Page 48: Rest with Java EE 6 , Security , Backbone.js

Securing your REST Web Service

• Authentication for Identity Verification• Authorizaton• Encryption

Page 49: Rest with Java EE 6 , Security , Backbone.js

Authentication: Configure web.xml

<login-config> <auth-method>BASIC</auth-method> <realm-name>admin</realm-name> </login-config>

Page 50: Rest with Java EE 6 , Security , Backbone.js

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

Page 51: Rest with Java EE 6 , Security , Backbone.js

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

Page 52: Rest with Java EE 6 , Security , Backbone.js

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

Page 53: Rest with Java EE 6 , Security , Backbone.js

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

Page 54: Rest with Java EE 6 , Security , Backbone.js

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> 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

Page 55: Rest with Java EE 6 , Security , Backbone.js

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

LDAPrealm

Page 56: Rest with Java EE 6 , Security , Backbone.js

Authentication: map roles to realm file

realm

Page 57: Rest with Java EE 6 , Security , Backbone.js

Authorization Annotations @Path("/customers") @RolesAllowed({"ADMIN", "CUSTOMER"}) public class CustomerResource { @GET @Path("{id}") @Produces("application/xml") public Customer getCustomer(@PathParam("id") int id) {...} @RolesAllowed("ADMIN") @POST @Consumes("application/xml") public void createCustomer(Customer cust) {...} @PermitAll @GET @Produces("application/xml") public Customer[] getCustomers() {} }

roles permitted to execute operation

any authenticated user

Page 58: Rest with Java EE 6 , Security , Backbone.js

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

Page 59: Rest with Java EE 6 , Security , Backbone.js

JAX-RS Security Context

@Path("/customers") public class CustomerService { @GET @Produces("application/xml") public Customer[] getCustomers(@Context

SecurityContext sec) { if (sec.isSecure() && !sec.isUserInRole("ADMIN")){ logger.log(sec.getUserPrincipal() + " accessed customer database."); } ... } }

Determine the identity of the user

check whether user belongs to a certain role

Page 60: Rest with Java EE 6 , Security , Backbone.js

Java EE 6

• JAX-RS is part of Java EE 6• Gradle dependencies are easy

apply plugin: 'war'

dependencies {

testCompile 'org.glassfish.extras:glassfish-embedded-all:3.0.1'

providedCompile 'org.glassfish.extras:glassfish-embedded-all:3.0.1’

}

Page 61: Rest with Java EE 6 , Security , Backbone.js

Java EE 6 security

• Service/Façade• Declarative (@RolesAllowed) • Programmatic

• Web Controller • New annotations for authentication & authorization • @ServletSecurity @HttpConstraint , @HttpMethodConstraint

• @WebFilter @DeclareRoles @RunAsPresentation

• Transport Layer • CONFIDENTIAL, INTEGRAL, NONE• ServletSecurity.TransportGuarantee

@WebServlet(name="UnderwritingServlet",   urlPatterns={"/UnderwritingServlet"})

@ServletSecurity(@HttpConstraint(transportGuarantee=ServletSecurity.TransportGuarantee.CONFIDENTIAL),

))

© Availity, LLC | All rights reserved.

Page 62: Rest with Java EE 6 , Security , Backbone.js

CDI

• Bean discovery and wiring

public class ItemController {

@Inject private CatalogService catalogService ;

© Availity, LLC | All rights reserved.

Page 63: Rest with Java EE 6 , Security , Backbone.js

Bean Validation

public class Address { @NotNull @Size(max=30, message="longer than {max} characters") private String street1; ... @NotNull @Valid private Country country;}

public class Country { @NotNull @Size(max=30) private String name; ...}

© Availity, LLC | All rights reserved.

Page 64: Rest with Java EE 6 , Security , Backbone.js

Servlet 3.0

• Ease of Development @WebServlet(urlPatterns=“/foo”, name=”MyServlet”, asyncSupported=true)

• @WebFilter("/secured/*")• Asynchronous Servlet

> Support Comet applications

• Security enhancements

© Availity, LLC | All rights reserved.

Page 65: Rest with Java EE 6 , Security , Backbone.js

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

Page 66: Rest with Java EE 6 , Security , Backbone.js

For More Information

• Reference Implementation• http://jersey.java.net/

• Java EE 6 tutorial• http://docs.oracle.com/javaee/6/tutorial/doc/

• Backbone.js JAX-RS example• http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-

1-getting-started/

• JAX-RS Comet example• http://www.oracle.com/technetwork/systems/articles/cometslideshow-

139170.html

Page 67: Rest with Java EE 6 , Security , Backbone.js

For More Information• RESTful Java with JAX-RS