Posts Tagged ‘Velocity’

Spring Security – Remember Me

Thursday, February 4th, 2010

Yesterday I implemented my login form using Spring Security. One thing I added was the ability to check a checkbox so a user would stay logged in for a certain period even if he closes his browser. You’re probably familiar with the idea.

In Spring this is done using the RememberMeAuthenticationFilter. And when you use the basic implementation, like I did, it’s based on a cookie and an in memory ‘cache’ for holding the key value in the cookie that’s linked to the user. For now, that suites my needs.

My applicationContext-security.xml looks like this (btw, I’m using Spring 3.0.0.RELEASE):

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="
             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
             http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <http>
        <intercept-url pattern="/static/**" filters="none"/>
        <intercept-url pattern="/favicon.ico" filters="none"/>
        <intercept-url pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern="/**" access="ROLE_USER"/>
        <form-login always-use-default-target='false' login-processing-url="/login" default-target-url="/" authentication-failure-url="/" />
        <remember-me/>
        <logout logout-url="/logout"/>
    </http>

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN"/>
                <user name="user" password="user" authorities="ROLE_USER"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>

    <global-method-security secured-annotations="enabled" jsr250-annotations="enabled"/>

</beans:beans>

As you can see, I didn’t yet setup my authentication provide as it should, but that’s OK for now. The important thing is the <remember-me> tag. That’s all it takes to implement a basic Remember Me implementation. Additionally, as one can stay logged in even after closing his browser, you need to provide some way to logout. So I putted the <logout> tag in as well.

Now, I’m using Velocity as my render engine. When a user is logged in, I don’t want to show any longer the login form, but some message like ‘welcome user x – log out’. I started using the variables that are exposed on the session in my velocity templates. To be able to do that, I had to expose my session variables to my model:

    <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
        <property name="cache" value="true"/>
        <property name="prefix" value=""/>
        <property name="suffix" value=".vm"/>
        <property name="exposeSessionAttributes" value="true"/>
    </bean>

So, that lets me write this in my velocity template:

<span>#springMessage('welcome')&nbsp;$SPRING_SECURITY_CONTEXT.authentication.getName().</span>

The problem with that is that we can’t rely on the session as we don’t know their is actually a session created and secondly, if the SecurityContext is set on the session. Logging in into the application using the Remember Me logic, this looks not be the case. The reasoning behind it is that the session is only used for holding status between different requests, not for rendering data to the view. The user info will off course be put on the session, but in our case, it happens too late in the process.

So, how do we solve this ?
Well, the solution appears to be easy (once you know it :-) ). We adapt our view resolver like this:

    <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
        <property name="cache" value="true"/>
        <property name="prefix" value=""/>
        <property name="suffix" value=".vm"/>
        <property name="exposeSessionAttributes" value="true"/>
        <property name="attributes">
            <map>
                <entry key="authentication">
                    <bean class="com.idevelop.kizhi.web.util.AuthenticatedUserDetails"/>
                </entry>
            </map>
        </property>
    </bean>

Meaning that we add a bean AuthenticatedUserDetails to our model and it will be accessible with the key authentication. The AuthenticatedUserDetails class is nothing more than a class that accesses info from the SecurityContext in a nice manner for our velocity template. It looks like this:

public class AuthenticatedUserDetails {
    /**
     * Get the user name of the logged in user.
     *
     * @return the user name of the user
     */
    public static String getPrincipal() {
        Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (obj instanceof UserDetails) {
            return ((UserDetails) obj).getUsername();
        } else {
            return null;
        }
    }
}

And now in our velocity template, we can write the following as we exposed our bean to our model:

<span>#springMessage('welcome')&nbsp;$authentication.principal.</span>

For completeness, this is how the login form looks like:

#* @vtlvariable name="authentication" type="com.idevelop.kizhi.web.util.AuthenticatedUserDetails" *#
#* @vtlvariable name="SPRING_SECURITY_LAST_EXCEPTION" type="org.springframework.security.authentication.BadCredentialsException" *#
#* @vtlvariable name="SPRING_SECURITY_LAST_USERNAME" type="java.lang.String" *#
<div class="login">
    #if(!$authentication.principal)
        <form id="logInForm" method="POST" action="/login">
            <div class="header"><p>#springMessage('loginHeader').</p></div>

            #if ($SPRING_SECURITY_LAST_EXCEPTION)
                <div class="error"><p>#springMessage($SPRING_SECURITY_LAST_EXCEPTION.message)</p></div>
            #end

            <div class="fields">
                <p>
                    <label for="j_username" class="formLabel">
                        #springMessage('userName'):
                    </label>
                    <input class="text medium-field" type="text" id="j_username" name="j_username" tabindex="1"
                           value="$!SPRING_SECURITY_LAST_USERNAME" size="30"/>
                    <br/>
                </p>

                <p>
                    <label for="j_password" class="formLabel">
                        #springMessage('password'):
                    </label>
                    <input type="password" name="j_password" id="j_password" tabindex="2" size="30"/>
                    <br/>
                </p>

                <p>
                    <label for="_spring_security_remember_me" class="checkboxLabel">
                        <input type='checkbox' name='_spring_security_remember_me' id="_spring_security_remember_me"
                               tabindex="3" value="true"/>
                        #springMessage('rememberMe')
                    </label>
                    <br/>
                </p>
            </div>
            <div class="buttons">
                <p>
                    <input id="login" class="button" type="submit" value="#springMessage('login')" tabindex="4"/>
                </p>
            </div>
        </form>
        <div class="forgotPassword">
            <a href="#" target="_parent">#springMessage('forgotPassword')</a>
        </div>
    #end
</div>

And that’s how it’s done. Once you know it, it’s peanuts, but it took me quite some googling before finding this out. I hope this post wins you some time.

My web stack: Spring MVC + Velocity + jQuery

Tuesday, February 2nd, 2010

The last few weeks I have been exploring what’s living in the web development world. I looked at frameworks like Wicket, GWT & JSF but they couldn’t convince me.

For me, Web development is about generating HTML pages. And I like to do that in a transparent way. I.e. web pages should be able to be developed and maintained by… web developers. It happens a lot that web developers are involved in the project for creating and designing the look and feel of a website. But then, the jpg files (or if you are lucky, you already get a html page..) are hand over to the developer who can start modifying and hacking it into a JSP page or try to programmatically reproduce the HTML page. And face it, that just doesn’t work. The programmer knows HTML, but he’ll never be damn good at it. He struggles, fights with his rendering, but for some reason that stupid DIV won’t stay on its place. He’s loosing the battle. The web developer has to come over and help the Java developer. The web developer sees what a mess the Java developer made of his beautifully designed page and gets frustrated. The Java developer is already frustrated of all the time he lost in rendering a stupid HTML page.. you get the picture. So why not use the knowledge of the web developers? They are creative wizards, they know how to implement their designs in valid XHTML with DIV’s instead of tables etc.. And they just happen to be damn good at it.

That being said, what is out there that does match my needs?

I really like Velocity. Starting from the visual design a web developer makes his html page and then can cut into pieces himself. These pieces can be put into velocity templates and the only thing the Java developer has to do is merging the dynamic content and labels into it by replacing the static placeholders with variables and some for loops and stuff like that. Maintaining is also easy: the templates still look and feel like plain html and both the web developer and java developer can easy adapt the templates. So IMHO, a win-win situation.

And what about front end logic? I don’t like the magic of frameworks like GWT and Wicket. As long they do what you expect them to do, they are very handy. But once something doesn’t work as you expect, or something won’t render/behave in IE or Firefox like it should, you can start debugging and hacking to get it right. Secondly, I like to separate my view from my logic. That way, the GUI guys can do their thing without being annoyed of all the javascript in the html page. jQuery is the answer. Once the HTML page is loaded into the browser, the jQuery code attaches itself on the different DOM objects. So the glueing is done at runtime and not at design time. The only drawback is that it might seem harder to maintain the javascript as long the design of HTML page isn’t finalized. But isn’t that always the case? jQuery has also a very nice and powerful syntax. The $() notation uses CSS selectors and a fluent interface which makes it very pleasant to work with. And not to forget, jQuery is designed as a wrapper. I.e. it wraps the IE and Firefox javascript objects so one has not to worry about browser specific code. That’s something we all can appreciate :)

At the backend, I go for Spring MVC. In my opinion they implemented the MVC pattern very elegantly. To be honest, I never looked into Spring MVC before (I knew that it existed but that was it..) and started writing a web framework myself based on my .NET web development experience. So I came up with a DispatcherServlet (indeed, I even had the same name :) ), had some URL resolving/generating filter logic and a Page object that served as Controller. Thank god I stumbled on Spring MVC while googling for an other Spring issue. I would have came up with the same stuff, but it would never have been as complete and solid as Spring MVC already is. So what do I really like? Well, being able to use variables in URL patterns is a powerful thing. Or the fact one can render the same request in different ways depending on e.g. the extension of the request. And they have different view templates for e.g. JSON, Velocity, XSLT..

And what about Security? Well, for me there is only one option: Spring Security (formerly known as Acegi Security). It is very complete and easy to set up. And off course, it integrates nicely into the Spring application context, which I couldn’t miss anymore.

To complete my stack overview, on the Data layer, I choose Hibernate above JPA. IMHO, pure JPA is not useable in decent project. One almost always end up using Hibernate specific things, so I prefer to go Hibernate all the way from the beginning.

And that’s it. And what about Ajax I hear you think? Well, that’s covered. jQuery has a very good Ajax support and on the backend site, it’s just a matter of writing appropriate controllers and render the model into XHTML or JSON.