How to set up CSRF token in JMeter script

31 May 2017
Mikolaj Staniewski
Frink_Cognifide_2016_HeaderImages_0117

Another blog in our 'how to' series for developers, this time for QA developers working on AEM 6.0 or any release since then. When Adobe released AEM 6.0 they wisely introduced CSRF token as a feature to protect sites from hackers and fraudsters. So, if you're working with this version of AEM, or any above 6.0, you'll now need to know how to set CSRF token up in JMeter script if you are using it.  


You need to do this as you login if you want to test on the authoring side. 


Firstly, look for where you send the POST request to j_security_check with a valid credential and just underneath it add an additional HTTP request with the configuration below:

  • Method: GET
  • Path: libs/granite/csrf/token.json
  • Check: Follow Redirects

    Under this HTTP request add JSON Extractor and set values:

    • Checked radio called: Main sample and sub-samples
    • Variable names: csrf-token
    • JSON Path expressions: $.token
    • Default Values: NOT_FOUND

        This configuration is shown on the screen shot below.


        screen1

        screen2

        What if it fails?

        This should work first time but, if not (it could be because of a timeout from the server or a  java.net.socetexeption etc.) all other requests requiring the CSRF signature will also be rejected and you will get 401 Forbidden errors. So check on the backend for a reason as to why those errors occurred before moving on.


        To avoid this, it is possible to add 'If control logic controller' to your test, just before the HTTP request mentioned above. Then you can check if the token has a proper value during your test run and, if not, send another request to get it. If you need use this solution, make sure it doesn't have a major impact on your tests.


        Our AEM performance tests archetype


        If you'd like to learn more on this, make sure to visit our GitHub to download the performance tests archetype for AEM. 

        Other References