views:

97

answers:

2

Hi,

I have inherited some code in which I now have to add CSRF prevention and am trying to use the struts2 tokenSession interceptor to do this. I am adding a token to my form using the struts2 token tag like so:

<form id="updateObject" name="updateObject" action="<%=request.getContextPath()%>/prv/updateObject.action" method="POST">
    <fieldset class="x-fieldset">
        <legend>Update object - Action Required</legend>
        <div>...</div>
        <s:token />
        <s:hidden name="id" id="objectId" />
            more stuff here...
        <input type="submit" value="Update Object" onclick="javascript:return doUpdateObject('myAction');"/>
    </fieldset>
</form>

In my javascript function, I am adding/removing some validation rules (depending upon the action required, and submitting the form:

function doUpdateObject(action){
    actionPanel.registerAction(action); // this function places the action name in an in-scope variable
    doUpdateObjectValidationSetup(action); // this function adds/removes jquery validation rules depending upon the action

    if($("#updateObject").valid()){
        $("form#updateObject").submit();
    }
    return false;
}

I have intercepted the request and a token is being added, however the struts2 tokenSession interceptor is returning invalid.token. The code works as expected without this interceptor. (struts2 xml file not posted - will post the relevant section if required). I have also used the tokenSession interceptor in other pages which use a basic html submit button (i.e. not going via javascript or jquery) and this also works as expected. What is making the token invalid?

N.B. The project I have inherited uses a strange mixture of standard html, struts2 tags, ExtJS and JQuery. I will clean this up at some point but at the moment I just need to get the tokenSession interceptor working asap in the code as-is (as I have to apply a similar fix to several hundred pages...).

Any help/pointers/tips/etc greatly appreciated!

Regards,

John

A: 

Are you sure you are not generating two submits ? (Look into your web server logs)

If so, perhaps it's because of this:

onclick="javascript:return doUpdateObject('myAction');".

That is not correct, the pseudo protocol javascript: should be used only in urls (ej href="...") not in event handlers. Replace it with onclick="return doUpdateObject('myAction')".

I doubt the problem is caused by this, though.

leonbloy
Thanks, but no, two submits are not generated - as I said, I have intercepted the request to check the parameters and only one request is being sent. I've removed the 'javascript:' though.
John
A: 

This is now working with no changes! Just did a complete re-build, cache clean, reboot, etc. No idea what caused the original problem. Sorry for wasting time.

John

John