REST API returns 'XSRF check failed' when adding attachment to an issue

MR2001 June 13, 2016

I am using JIRA v6.4.11

I am trying to add an attachment to an (existing) issue using VBA and the REST API. The code below returns however "XSRF check failed".

Note that I can create issues using a similar approach, no errors.

Please advise.

Private Sub Test()  Dim oJiraService As MSXML2.XMLHTTP60
  Const STR_BOUNDARY As String = "abc123-xyz123"
  Dim sUrl As String, sRest As String, sIssueNumber As String
  Dim sFileDataStr As String, sPath As String, sStatus As String
  
  Set oJiraService = New MSXML2.XMLHTTP60
  sUrl = "https://alphajira01.am1.gac-can.com:1234/"
  sIssueNumber = "AMC-7861"
  
  sPath = "C:\Temp\test1.txt"
  sFileDataStr = "--" & STR_BOUNDARY & "--" & vbCrLf & _
      "Content-Disposition: form-data; name=""file"";Filename = """ & Mid$(sPath, InStrRev(sPath, "\") + 1) & """" & vbCrLf & _
      "Content-Type: application/octet-stream" & vbCrLf & _
       vbCrLf & GetFileBytes(sPath) & vbCrLf & "--" & _
       STR_BOUNDARY & "--"
  
  With oJiraService
    .Open "POST", sUrl & "rest/api/2/issue/" & sIssueNumber & "/attachments", False
    .setRequestHeader "X-Atlassian-Token", "nocheck"
    .setRequestHeader "Content-Type", "multipart/form-data; boundary=" & STR_BOUNDARY
    .setRequestHeader "Authorization", "Basic " & EncodeBase64("theuser" & ":" & "mypassword")
    .send stringToByteArray(sFileDataStr)
    '.send sData
    sRest = .responseText
    sStatus = .Status & " | " & .statusText
  End With
  
  Set oJiraService = Nothing
end sub 
 
 
Public Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)
  Dim objXML As MSXML2.DOMDocument
  Dim objNode As MSXML2.IXMLDOMElement
  Set objXML = New MSXML2.DOMDocument
  Set objNode = objXML.createElement("b64")
  objNode.DataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = objNode.text
  
  Set objNode = Nothing
  Set objXML = Nothing
End Function
 
Public Function GetFileBytes(ByVal fPath As String) As String
    Fnum = FreeFile
    Dim bytRtnVal() As Byte
    If LenB(Dir(fPath)) Then ''// Does file exist?
        Open fPath For Binary Access Read As Fnum
        ReDim bytRtnVal(LOF(Fnum) - 1&) As Byte
        Get Fnum, , bytRtnVal
        Close Fnum
    Else
        Err.Raise 53
    End If
    GetFileBytes = byteArrayToString(bytRtnVal)
    Erase bytRtnVal
End Function
 
Public Function byteArrayToString(bytArray() As Byte) As String
    Dim sAns As String
        sAns = StrConv(bytArray, vbUnicode)
    byteArrayToString = sAns
 End Function
 
Public Function stringToByteArray(srcTxt As String) As Byte()
    stringToByteArray = StrConv(srcTxt, vbFromUnicode)
End Function

1 answer

0 votes
MR2001 June 20, 2016

Resolved. Added an extra header:

With oJiraService      
    .setRequestHeader "Origin", "https://alphajira01.am1.gac-can.com:1234/" 
   etc..

Suggest an answer

Log in or Sign up to answer