Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struts2 token interceptor: CSRF protection

I am trying to protect my web application from CSRF attacks by using struts token interceptor.

The problem I am facing right now is our JSP pages makes more than one call to server (While JSP is converted to JS a struts token is added to JS.But in this JS there are multiple Ajax request. I hope I am making myself clear.), because of token interceptor only first request to the server is getting validated. Other requests are getting invalidated because struts token is reset after each validation.

Is there a way I stop Struts from resetting the token every time it validates? IS there any other solutions to handle this in struts interceptor.

I am also looking at tomcatcsrfprotection module, I guess I will end up with same problem here also.

managepage.jsp:

<s:token />
<script type="text/javascript">
var strutsToken = "<s:property value="#session['struts.tokens.token']" />";
var requestParams = {mainAction: 'loadGroups','struts.token.name': 'token' , token:strutsToken};

Ext.Ajax.request({
              url: 'manageUserAccount.action',
              params: Ext.urlEncode(requestParams),
              disableCaching: true,
              success: this.actionCallback
              });



//loading widgets

var requestParams = {mainAction: 'loadusers','struts.token.name': 'token' , token:strutsToken};

Ext.Ajax.request({
              url: 'manageUserAccount.action',
              params: Ext.urlEncode(requestParams),
              disableCaching: true,
              success: this.actionCallback
              });

</script>

Struts.xml:

  <action name="manageUserAccountEdit" class="ManageUserAccountEditAction">
     <interceptor-ref name="csrf-protection" /> 
     <result name="success">/pages/manageUserAccount.jsp</result>
 </action>

I have just added minimum code so that understanding it will be easier.

like image 694
Mok Avatar asked May 07 '14 10:05

Mok


1 Answers

You can use the code in my answer for Unable to implement Struts 2 token interceptor with hyperlink to create an action that returns a token. You can use any of the results stream or json or dispatcher to return a token as a Ajax success callback result. You can find an example in jQuery Ajax - issue returning JSON value. Now you can use the token to make your Ajax requests. Each time you need to make a new request you should call a token action to get a new token. Use the token as a parameter to your request and put the token interceptor in front of your actions.

like image 77
Roman C Avatar answered Sep 20 '22 13:09

Roman C