Tuesday, November 15, 2011

Quick Web Security for Spring MVC based POCs

While developing POCs, often quite late we realize we have not paid attention to basic web app security features like
  • a login page or basic http auth
  • some way to specifiy mutiple users, each user having mutiple roles
  • role based access for some screens / URls in the web app
  • logout url
  • automatic redirection of non-authenticated user access to the login page 
Some of these features though quite trivial are required in the most bare of POCs, and spending development effort on this is many times not high priority
Hence the need to quicky provide about web app security features without writing a single line of code only through some basic spring security configuration.
Details as below:
1. Download spring security and put the jars in the build and runtime classpath
2. in web.xml add the following filter and filter-mapping entry
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
   
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
3. in web.xml, in the base spring application context, load a spring config file like security-beans.xml with following contents
     <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/existing-spring-contexts.xml,WEB-INF/security-beans.xml</param-value>
    </context-param>

contents of security-beans.xml
    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/mvc/admin/**" access="hasRole('ROLE_ADMIN')" />
        <intercept-url pattern="/mvc/general/**" access="hasRole('ROLE_SPITTER')" />
        <intercept-url pattern="/**" access="isFullyAuthenticated()" />
    </http>

    <user-service id="userService">
        <user name="all" password="all" authorities="ROLE_REGULAR_USER,ROLE_ADMIN" />
        <user name="gan" password="gan" authorities="ROLE_REGULAR_USER" />
        <user name="admin" password="admin" authorities="ROLE_ADMIN" />
    </user-service>


    <authentication-manager>
        <authentication-provider user-service-ref="userService" />
    </authentication-manager>

Explanation

Here the auto-config=true gives us a ready-made(stock) login page, which can be overriden with our own custom login page
login url: http://localhost:8081/MyWebAppContext/j_spring_security_login
logout url: http://localhost:8081/MyWebAppContext/j_spring_security_logout
userService bean allows us to specify sample userids, and their roles, accessible throughout our application through standard j2ee apis and also spring security tags on jsps
<security:authentication property="principal.username" />
<security:authorize access="hasRole('ROLE_ADMIN')">
<h2>Admin Area keep Off!</h2>
</security:authorize>

Through entry like <intercept-url pattern="/mvc/admin/**" access="hasRole('ROLE_ADMIN')" />
we can very welll control access to certain URLs in the web application for specific users and roles

Summary

Thus without writing a single line of code using spring security config we can impart quick web security to our POCs
Please refer spring security documentation for further details
 http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html

Rest Integration autobinding javascript objects with controller java objects

Often when developing REST services, the server rest controller implementations work on java objects and the REST clients usually javascript ajax calls work on javascript AJAX objects. Would'nt it be great to acheive automatic binding between the javascript and java objects, instead of writing explicit code to map to and from javascript and java objects. Below is a small sample giving example of just this, using Jersey REST controllers on server side and jquery ajax request on client side. Purposely chosen a POST request scenario instead of easier GET.

Under the hoods, on server side Jersey and Jackson provide the auto binding from incoming json object to java object

 REST controller with config

    @POST
    @Path("/directUpdate")
    @Produces(MediaType.TEXT_HTML)
    @Consumes(MediaType.APPLICATION_JSON)
    public void updatePartyInfo(Party input) throws IOException{
       
        System.out.println("input param party object"+input);

        Party party = service.getByPk(input.getPartyId());
        party.setName(input.getName());
        party.setAddress(input.getAddress());
        party.setTelephone(input.getTelephone());
        party.setDescription(input.getDescription());
        service.update(party);
       

        //redirecting to subsequent page
        servletResponse.sendRedirect("http://hostname:portnum/jqueryrest/partylist.html");

    }





jQuery Ajax request on client side

    function updateParty(){
        inputData = new Object();
        inputData.partyId = $("#partyId").val();
        inputData.name = $("#name").val();
        inputData.address = $("#address").val();
        inputData.telephone = $("#telephone").val();
        inputData.description = $("#description").val();
      
        jQuery.ajax ({
            url: 'http://hostname:portnum/jqueryrest/restful/party/directUpdate',
            type: "POST",
            processData: "false",
            data: JSON.stringify(inputData),
            dataType: "json",
            contentType: "application/json",
            success: function(){
                alert('Party update success');
            }
        });

    }

Monday, November 14, 2011

Android enable your existing web app

Androidify Your Web App

Ever since android and the mobile app market has started becoming popular, managers have started demanding, android based user interfaces onto existing web applications. As developers it is necessry to understand the various choices and pros and cons of each one clearly.
Lets say you have an existing web application which is developed with one of more traditional web frameworks, then for making this web app available as an android app, following are the various choices you have:

  1. Existing web app most likely runs in a javascript compliant modern browser. Most modern smart phones already have mature javascript enabled web browsers. Validate the browser version of your intended device and check the browsers compliance with respect to standards like ECMA (javascript), HTML5 support etc. You should be able to display the entire web app, as-it-is onto the smart phones browser, but, but but...the UI will not at all be optimized to the mobile screen, for one, the UI was built with desktop browsers in mind and the mobile app is a completely different ball game. So though most of the traditional web app UI might display, you will have issues like UI widgets will not render correctly, users will have to strain their eyes to see the text, the default zoom levels will be horrible, horizontal and vertical scrolling to see entire app, will make it a very painful user experience to say the least.
  2. You can change (switchable) css in your existing web app, so that it is a lot more optimized for mobile viewing, this means most of the presentation logic stays as is but only the css will need to be modified. Also you can resort to html metadata elements like the view port tag to adjust the default zoom levels for the mobile browser display. Inspite of these optimizations, the amount of data on screen for a mobile device can degrade the user experience.
  3. The next option comes at a bit more cost but really provides ideal mobile user experience. The choice is of developing a native android UI and having that communicate using REST (json or xml over http), with REST controllers on the server side. The REST controllers will need to developed in addition to any existing controllers and can be thin wrappers/delegators over existing controllers or services. REST controllers will return back json / xml, which will be gotten by the android UI and displayed suitably. In android if you think writing a http client(REST client) is a might tedious you can use a third-party library like Spring-Android, which will ease REST client development and provide auto-binding to android/java objects from json or xml.

    Typical code for issuing a REST-client call is given below to give you idea of how clean and simple it is to write REST client from native android using spring-android.
 
private Parties getParties(){
 RestTemplate restTemplate = new RestTemplate();     

 HttpHeaders requestHeaders = new HttpHeaders();
 requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));
 HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
 String url = "http://x.y.z.w:8081/jqueryrest/restful/party/listallEx";

 //invoke the url
 ResponseEntity<Parties> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Parties.class);
 Parties retList = (Parties)responseEntity.getBody();
 return retList;
}

The url, refers to a REST controller endpoint which returns a list of party object.

Sample jersey REST controller
 
        @GET
 @Path("/listallEx")
 @Produces("application/json")
 public Parties getAllEx(){
  return new Parties(service.getAll());
 }

Wednesday, November 9, 2011

Convert existing junit 4 testcases into perf tests in 2 minutes

1.

Have junitperf jar in your compile and runtime classpath http://www.clarkware.com/software/junitperf-1.9.1.zip

2.
add following code in a main method in ur junit class
public static void main(..) { int users = 4; int iterations = 5; JUnit4TestAdapter testCase = new JUnit4TestAdapter(MyOwnJunit.class); junit.framework.Test loadTest = new LoadTest(testCase, users, iterations); junit.textui.TestRunner.run(loadTest); }

3.

run junit as java program instead of junit
similar decorators can be used for performance testing just as for multi-threaded testing. This can be huge time saver to quickly test any code for concurrent access issues, that get reported. You can make these concurrent access unit tests as part of your CI as well.