Securing REST web services

It is very easy to implement REST web services on a Jspresso backend. Starting from Jspresso CE 4.5.0 / Jspresso EE 4.3.0, It is very easy to secure the web service using the same JAAS authentication policy than the one that is installed on the frontend side to authenticate users.


The user credential are passed any other parameters, in a secured HTTPS request. Then the web service authenticates the user and the session is filled with the same piece of information than the ones that would be filled in a normal interactive login. No code duplication. No special authorisation handling. Just the one you are used to when developing using Jspresso.


For Jspresso pre-4.5.0 archetype-generated applications, there are a few lines to add in the core/src/main/dsl/backend.sjs file in order to bind the backend controller to the same JAAS login context name than the frontend controller. For anyone using a Jspresso 4.5.0+ archetype, it will already be there. Be careful when copy pasting the snippet below, don’t forget to change the value of loginContextName to reflect the JAAS context name of your application (it is generally your applicationn name).


    class: 'org.jspresso.framework.application.backend.AbstractBackendController',
    parent: 'abstractBackControllerBase',
    custom: [loginContextName: 'hrsample']


Then securing the web service is as simple as calling the performLogin(user, password) on the backend controller. As an example, here is the Employees web service declared in HRSample EE :


public EmployeeDto getEmployee(@PathParam("name") String name,
                               @QueryParam("user") String user,
                               @QueryParam("password") String password) {

 HibernateBackendController backendController =
                        (HibernateBackendController) getBackendController();

 if (backendController.performLogin(user, password)) {
   DetachedCriteria crit = EnhancedDetachedCriteria.forClass(Employee.class);
   crit.add(Restrictions.eq("name", name));
   Employee e = backendController
                  .findFirstByCriteria(crit, EMergeMode.MERGE_KEEP, Employee.class);
   if (e != null) {
     return new EmployeeDto(e);
   } else {
     throw new NotFoundException("Employee " + name + " not found");
 } else {
   throw new NotAuthorizedException(
     "Authentication failed for [" + user + "] to access Employee REST service"


In the example above, the user and password are passed as query parameters but it’s entirely up to you.

Categories: WebServices

Leave a Reply