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
3. in web.xml, in the base spring application context, load a spring config file like security-beans.xml with following contents

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()" />

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

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


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>

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


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

No comments: