Insights Hub How to handle Invalid CSRF Token error?

2023-03-03T15:32:39Z
Applications

Summary


Details

When you are trying to submit any POST request or you are trying to submit an HTML form in your MindSphere hosted application.

You may get the below error message.

<errors xmlns:atom="http://www.w3.org/2005/Atom">
<error logref="6247ea3c5fd74d08a8e3383dfdc48719">
<message>MindSphere Gateway error: Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.</message>
</error>
</errors>

Solution

You have to use the XSRF-TOKEN cookie which is generated by MindSphere.

You can find the cookie XSRF-TOKEN in the developer tool as shown in the below screenshot.


You have to get that  XSRF-TOKEN and pass that into the header or in the form hidden field.

Example code in NodeJs (JavaScript)

  • get the XSRF-TOKEN cookie and assign it to the variable.

    app.use(function (req, res, next) {
      res.locals.csrftoken = req.cookies["XSRF-TOKEN"];
      next();
    });

    • get the cookie variable and pass that to the render/Html page

      app.get("/", function (req, res) {  
        let objData = {
           csrfTokenFromServer: res.locals.csrftoken
         };
        res.render("home_page", objData);
      });

      • now pass that cookie variable to the form hidden input filed value with the name attributes as _csrf  

        <form action = "/result" method = "POST">
         <input type="hidden" value="<%= csrfTokenFromServer;%>" name="_csrf" />
        </form>

        Once you pass the XSRF-TOKEN cookie in your form your error will be resolved. 

        Notes

         For any questions or support in this matter, contact us through the support center.

        KB Article ID# PL8536723

        Contents

        SummaryDetails

        Associated Components

        3rd Party Application