Parsing the XML Response of a SignOn Request to Obtain the CSRF Name and Value

In this section:

This section provides code examples that demonstrate how to parse the XML response of a SignOn request to obtain the Cross-Site Request Forgery (CSRF) name and value. The CSRF name and value can then be sent to subsequent POST requests.


Top of page

x
Java Example

In this section:

import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.xml.sax.SAXException;
/**
* @author 
 *
*/
public class runReport
{
    /**
     * @param args
     * @throws IOException 
     * @throws HttpException 
     * @throws SAXException 
     * @throws ParserConfigurationException 
     * @throws URISyntaxException 
     */
    public static void main(String[] args) throws HttpException, IOException, ParserConfigurationException, SAXException, URISyntaxException
    {
        String request = "http://localhost:8080/ibi_apps/rs/ibfs";
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(request);
        method.addParameter("IBIRS_action", "signOn");
        method.addParameter("IBIRS_userName", "admin");
        method.addParameter("IBIRS_password", "admin");
        client.executeMethod(method);
        Header[] cookies = null;
        InputStream rstream = null;
        rstream = method.getResponseBodyAsStream();
        cookies = method.getResponseHeaders("Set-Cookie");
        /* parse rstream XML for csrf token */
        SAXParserFactory factory = SAXParserFactory.newInstance();
       SAXParser parser = factory.newSAXParser();
       SaxHandler handler   = new SaxHandler();
       parser.parse(rstream, handler);
       String csrfName = SaxHandler.results[0];
       String csrfValue = SaxHandler.results[1];
       System.out.println("csrfName = " + csrfName);
       System.out.println("csrfValue = " + csrfValue);
        String request2 = "http://localhost:8080/ibi_apps/rs/ibfs/WFC/Repository/Tests/car_param.fex";
        PostMethod method_report = new PostMethod(request2);
        method_report.addParameter("IBIRS_action","run");
        method_report.addParameter("COUNTRY","ENGLAND");
        method_report.addParameter("CAR","JAGUAR");
        method_report.addParameter("MODEL","XJ12L AUTO");
        method_report.addParameter(csrfName,csrfValue);
        // cookies is defined as Header[] in the Signing-On to WebFOCUS example
        for(int h=0; h<cookies.length; h++){
        System.out.println(cookies[h]);
        method_report.addRequestHeader(cookies[h].getName(), cookies[h].getValue());
        }
        // client is defined as HttpClient in the Signing-On to WebFOCUS example
        int statusCode2 = client.executeMethod(method_report);
        InputStream rstream2 = null;
        rstream2 = method_report.getResponseBodyAsStream();
        File tempfile = new File("c:\\temp\\Report.htm");
        FileOutputStream fos = new FileOutputStream(tempfile);
        PrintWriter out=new PrintWriter(fos);
        BufferedReader br2 = new BufferedReader(new InputStreamReader(rstream2));
        String line2;
        String newOutput = null;
        while ((line2 = br2.readLine()) != null) {
        newOutput = line2;
        out.println(newOutput);
        System.out.println(line2);
        }
        // bring up the HTML report in the default browser
        URI xtempfile = new URI ("file:/c:/temp/Report.htm");
        Desktop.getDesktop().browse(xtempfile);
        br2.close();
        out.close();
    }
}


x
XML Parser Class

The XML Parser class is called SaxHandler and is in a separate class file

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SaxHandler extends DefaultHandler {
          
       static String[] results = new String[2];
                     
           public void startElement(String uri, String localName, String qName, Attributes attributes)
           throws SAXException {
               if (qName.equals("entry")) {
                            String keyName = attributes.getValue("key");
                            if (keyName.equals("IBI_CSRF_Token_Name")) {
                                  String tokenNameKeyValue = 
                                  attributes.getValue("value");
                                  System.out.println("key value is " +  
                                  tokenNameKeyValue);
                                  results[0] = tokenNameKeyValue;
                            }
                            if (keyName.equals("IBI_CSRF_Token_Value")) {
                                  String tokenValueKeyValue = 
                                  attributes.getValue("value");
                                  System.out.println("key value is " + 
                                  tokenValueKeyValue)
                                  results[1] = tokenValueKeyValue;
                            }
               }
           }
  
}

Top of page

x
Visual Basic .NET Example

In this section:

Imports System.Net
Imports System.Text
Imports System.IO
Module Module1
    Sub Main()
        Dim cookies As New CookieContainer
        Dim webStream As Stream
        Dim webResponse As String = ""
        Dim request As HttpWebRequest
        Dim response As HttpWebResponse
        Dim postData As String
        Dim csrf(2) As String
        request = WebRequest.Create("http://localhost:8080/ibi_apps/rs/ibfs")
        request.Method = "POST"
        postData = "IBIRS_action=signOn&IBIRS_userName=admin&IBIRS_password=admin"
        request.CookieContainer = cookies
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
        request.ContentType = "application/x-www-form-urlencoded"
        request.ContentLength = byteArray.Length
        Dim dataStream As Stream = request.GetRequestStream()
        dataStream.Write(byteArray, 0, byteArray.Length)
        dataStream.Close()
        response = request.GetResponse()
        webStream = response.GetResponseStream()
        Dim webStreamReader As New StreamReader(webStream)
        While webStreamReader.Peek >= 0
            webResponse = webStreamReader.ReadToEnd()
        End While
        csrf = XMLParse.XMLParseCSRF.doParseXML(webResponse)
        Console.WriteLine("csrf token name is " + csrf(0))
        Console.WriteLine("csrf key value is " + csrf(1))
        Console.ReadKey()
        Dim request2 As HttpWebRequest
        Dim response2 As HttpWebResponse
        Dim webStream2 As Stream
        Dim webResponse2 As String = ""
        request2 = WebRequest.Create("http://localhost:8080/ibi_apps/rs/ibfs/WFC/Repository/Tests/car_param.fex")
        request2.Method = "POST"
        'cookies is defined as CookieContainer in the Signing-On to WebFOCUS example
        request2.CookieContainer = cookies
        postData = "IBIRS_action=run&COUNTRY=ENGLAND&CAR=JAGUAR&MODEL=XJ12L%20AUTO" + "&" + csrf(0) + "=" + csrf(1)
        Dim byteArray2 As Byte() = Encoding.UTF8.GetBytes(postData)
        request2.ContentType = "application/x-www-form-urlencoded"
        request2.ContentLength = byteArray2.Length
        Dim dataStream2 As Stream = request2.GetRequestStream()
        dataStream2.Write(byteArray2, 0, byteArray2.Length)
        dataStream2.Close()
        response2 = request2.GetResponse()
        webStream2 = response2.GetResponseStream()
        'Write to disk
        Dim fs As New FileStream("c:\temp\output.htm", FileMode.Create)
        Dim read As Byte() = New Byte(255) {}
        Dim count As Integer = webStream2.Read(read, 0, read.Length)
        While count > 0
            fs.Write(read, 0, count)
            count = webStream2.Read(read, 0, read.Length)
        End While
        'Close everything
        fs.Close()
        webStream2.Close()
        Process.Start("c:\temp\output.htm")
    End Sub
End Module


x
XML Parser Function

The XML Parser function is called doParseXML and is located in a separate class file named XMLParseCSRF.vb, which is located in a separate project for reusability.

Imports System.IO
Imports System.Xml
Public Class XMLParseCSRF
    Public Shared Function doParseXML(inResponse As String) As String()
        Dim results(2) As String
        Dim m_xmlr As XmlTextReader = New XmlTextReader(New StringReader(inResponse))
        While m_xmlr.Read()
            If (m_xmlr.NodeType = XmlNodeType.Element) Then
                If m_xmlr.Name = "entry" Then
                    Dim keyName As String = m_xmlr.GetAttribute("key")
                    If (keyName = "IBI_CSRF_Token_Name") Then
                        Dim tokenKeyNameValue As String = m_xmlr.GetAttribute("value")
                        Console.WriteLine("tokenKeyName value is " + tokenKeyNameValue)
                        results(0) = tokenKeyNameValue
                    End If
                    If (keyName = "IBI_CSRF_Token_Value") Then
                        Dim tokenValueKeyValue As String = m_xmlr.GetAttribute("value")
                        Console.WriteLine("tokenValueKey value is " + 
                        tokenValueKeyValue)
                        results(1) = tokenValueKeyValue
                    End If
                End If
            End If
        End While
        'close the reader
        m_xmlr.Close()
        Return results
    End Function
End Class

Information Builders