Securing JAX-RS RESTful services Miroslav Fuksa (software developer) Michal Gajdoš (software developer)
The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle s products remains at the sole discretion of Oracle. 2
Program Agenda Introduction to JAX-RS and Security Declarative Security and Entity Filtering Client Security OAuth 1 OAuth 2 3
Introduction to JAX-RS and security 4
Introduction RESTful Web Services Representation State Transfer Using HTTP methods GET, POST, DELETE... representations (HTML, JSON, XML), URI, caching, stateless JAX-RS: Java API for RESTful Services JAX-RS 2.0 (JSR 339): Java EE 7, released in May 2013 Reference implementation: Jersey 2 5
Introduction @Path("student") public class StudentResource { @Produces("application/json") @GET @Path("{id}") public Student get(@pathparam("id") String id) { return StudentService.getStudentById(id); } http://my-univeristy.com/api/student/ GET http://my-univeristy.com/api/student/adam } @POST public Student post(student student) { return StudentService.addStudent(student); } POST http://my-univeristy.com/api/student 6
Introduction JAX-RS 2.0 JAX-RS 2.0 (JSR 339, part of Java EE 7, released in May 2013) Client API Asynchronous processing Filters Interceptors 7
Introduction Security Authentication HTTP Basic Authentication (BASE64 encoded username and password SSL) HTTP Digest Authentication (password is used only for signature, MD5) Authorization 8
Servlet Container Security Secure JAX-RS services using Servlet Container <security-constraint> <web-resource-collection> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>basic</auth-method> <realm-name>my-realm</realm-name> </login-config> 9
Servlet Container Security Secure JAX-RS services using Servlet Container <security-constraint> <web-resource-collection> <url-pattern>/student/*</url-pattern> <http-method>post</http-method> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint> </security-constraint> <security-constraint> <web-resource-collection> <url-pattern>/student/*</url-pattern> <http-method>get</http-method> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> <role-name>user</role-name> </auth-constraint> </security-constraint> http://my-univeristy.com/api/students/{id} 10
Servlet Container Security Secure JAX-RS services using Servlet Container Advantages Independent on JAX-RS implementation managed by servlet container Disadvantages only for servlet containers fragile, verbose, bad maintenance Pre-matching filters 11
Pre-matching filters PUT http://my-univeristy.com/api/student Pre-matching filter POST http://my-univeristy.com/api/student 12
JAX-RS Security Context javax.ws.rs.core.securitycontext public interface SecurityContext { public Principal getuserprincipal(); public boolean isuserinrole(string role); public boolean issecure(); public String getauthenticationscheme(); } 13
JAX-RS Security Context Secure method programmatically using SecurityContext @Path("student") public class StudentResource { @Context private SecurityContext securitycontext; } @GET @Path("{id}") public Student get(@pathparam("id") String id) { if (!securitycontext.isuserinrole("admin")) { throw new WebApplicationException( You don t have privileges to access this resource.", 403); } return StudentService.getStudentById(id) } 14
Authorization in Jersey 2.x: Security annotations 15
Authorization Security annotations. Means in Jersey 2.x Define the access to resources based on the user groups. Security annotations from javax.annotation.security package. @PermitAll, @DenyAll, @RolesAllowed SecurityContext RolesAllowedDynamicFeature. 16
Authorization Security annotations. Example: Register RolesAllowedDynamicFeature. @ApplicationPath( api ) public class MyApplication extends ResourceConfig { public MyApplication() { packages( my.application ); } } register(rolesalloweddynamicfeature.class); 17
Authorization Security annotations. Example: Define access restrictions on Resource. @Path("/resource") @PermitAll public class Resource { @GET public String get() { return "GET"; } } @RolesAllowed("admin") @POST public String post(string content) { return content; } 18
Authorization in Jersey 2.x: Entity Filtering Feature 19
Feature: Entity Filtering Idea and Motivation Exposing only part of domain model for input/output. Reduce the amount of data exchanged over the wire. Define own filtering rules based on current context. Resource method. Assign security access rules to properties. Faster prototyping and development. One model and one place for defining the rules. 20
Feature: Entity Filtering Means in Jersey 2.3+ / MOXy 2.5.0 @EntityFiltering meta-annotation. Create filtering annotations to define context. Create filtering annotations with custom meaning to define context. Security annotations from javax.annotation.security package. @PermitAll, @DenyAll, @RolesAllowed SecurityContext 21
Feature: Entity Filtering Putting it all together. Define dependencies on extension and media modules. Register SecurityEntityFilteringFeature in Jersey Application. Annotate Resources and Domain Model with security annotations. Enjoy! 22
Feature: Entity Filtering Example: Goal. Have: JAX-RS Application with security user roles. Want: Define access to resources. Restrict access to entities / entity members for different user roles. 23
Feature: Entity Filtering Example: Register Providers in JAX-RS Application. @ApplicationPath( api ) public class MyApplication extends ResourceConfig { public MyApplication() { packages( my.application ); } } register(securityentityfilteringfeature.class); 24
Feature: Entity Filtering Example: Model. public class RestrictedEntity { public class RestrictedSubEntity { } private String simplefield; private String denyall; private RestrictedSubEntity mixed; // getters and setters } private String managerfield; private String userfield; // getters and setters 25
Feature: Entity Filtering Example: Annotated Domain Model. public class RestrictedEntity { public String getsimplefield() {... } @DenyAll public String getdenyall() {... } @RolesAllowed({"manager", "user"}) public RestrictedSubEntity getmixed() {} } public class RestrictedSubEntity { @RolesAllowed("manager") public String getmanagerfield() {... } @RolesAllowed("user") public String getuserfield() {... } } 26
Feature: Entity Filtering Example: JAX-RS Un-Restricted Resource. @Path("unrestricted-resource") @Produces("application/json") public class UnrestrictedResource { } @GET public RestrictedEntity getrestrictedentity() {... } 27
Feature: Entity Filtering Example: JAX-RS Restricted Resource. @Path("restricted-resource") @Produces("application/json") public class RestrictedResource { @GET @Path( denyall") @DenyAll public RestrictedEntity denyall() {... } } @GET @Path("rolesAllowed") @RolesAllowed({"manager"}) public RestrictedEntity rolesallowed() {... } 28
JAX-RS Client Security 29
Client Security SSL with JAX-RS support JAX-RS 2.0 defines support for SSL configuration javax.ws.rs.client.clientbuilder KeyStore, TrustStore, SSLContext Jersey provides SslConfigurator to create SSLContext 30
Client Security SslConfigurator SslConfigurator sslconfig = SslConfigurator.newInstance().trustStoreFile("./truststore_client").trustStorePassword("pwds65df4").keyStoreFile("./keystore_client").keyPassword("sf564fsds"); SSLContext sslcontext = sslconfig.createsslcontext(); Client client = ClientBuilder.newBuilder().sslContext(sslContext).build(); 31
Client Security Http Authentication ClientRequestFilter and ClientResponseFilter Jersey HttpAuthenticationFeature Basic, Digest, Universal HttpAuthenticationFeature basicauth = HttpAuthenticationFeature.basic("username,"12345"); Client client = ClientBuilder.newBuilder().register(basicAuth).newClient(); Student michal = client.target("http://my-university.com/student/michal").request().get(student.class); 32
OAuth 1 33
OAuth: introduction username/password Service Provider Resource owner Consumer 34
OAuth Motivation I want to give an access to my account to consumer (3 rd party application) Give Consumer my password Revoking access Password change Limit access (different authorization rules) Trust 35
OAuth: introduction username/password Service Provider Resource owner Consumer 36
OAuth Motivation OAuth No resource owner s password sharing Resource owner can revoke an access at any time Limited access User friendly process of issuing tokens (Authorization Process/Flow) 37
OAuth1 Details IETF OAuth 1.0 (RFC 5849) Previous community version 1.0 and 1.0a Signatures added to requests (HMAC-SHA1, RSA-SHA1) based on secret keys Authorization process (flow) Process of granting access to the consumer Authenticated requests Consumer calls REST APIs using OAuth signatures 38
OAuth1: Authorization flow 3 Service Provider 2 Resource owner 4 1 5 Consumer 1 Request Token 2 Authorization Request 3 Resource owner authorization 4 Authorization Response 5 Access Token 39
OAuth1: Authenticated requests Service Provider Resource owner Consumer Access Token 40
OAuth1 Summary Secure Signatures Secret keys (consumer secret, request and access token secret) nonce, timestamp Complex for implementation 41
OAuth 2 42
OAuth 2 Introduction WRAP (Web Resource Authorization Protocol) OAuth 2.0 (IETF, RFC 6749), released in October 2012 Not backward compatible, framework (not protocol) Does not require signatures (bearer token), SSL Authorization flows Authorization Code Grant (refresh token) Implicit Grant (eg. Javascript client), Resource Owner Password Credentials Grant (user name + password), Client Credentials Grant (client app authentication) 43
OAuth 2 Compared to OAuth 1 Easier implementation OAuth 1.0a is not easy to implement Security questions no signature and no secret keys (risk of exposing tokens) SSL usage of authorization flows with limited security 44
OAuth Jersey and OAuth OAuth 1.0a: client and server OAuth 2: client (Authorization Code Grant) Client OAuth support: Authorization Flow: standalone utility Authenticated requests (Features => Filters) 45
OAuth 2 Demo server application that uses JAX-RS client to get and show Google tasks of any user that authorizes the application 46
Resources Securing JAX-RS Resources https://jersey.java.net/documentation/latest/security.html#d0e8866 Entity Filtering in Jersey https://jersey.java.net/documentation/latest/entity-filtering.html https://github.com/jersey/jersey/tree/master/examples/entity-filtering OAuth specification http://tools.ietf.org/html/rfc5849 http://tools.ietf.org/html/rfc6749 OAuth 2 sample https://github.com/jersey/jersey/tree/master/examples/oauth2-client-google-webapp Jersey http://jersey.java.net 47
Questions & Answers 48