I’m using external API in Script Runner (Jira Data Center).
I have groovy scrip which I run from the console:
final url = "remote link"
final String username = "xxx user"
final String password = "xxx password"
final json = """
{
"xxx": "x",
"yyy": "y",
"zzz": 1111
}
"""
String token = null
//getting csrf-token. GET returns token in Headers
try
{
final URL get = new URL(url)
final HttpURLConnection connection = (HttpURLConnection) get.openConnection()
connection.setRequestMethod("GET")
connection.doOutput = true
connection.setRequestProperty('Content-Type', 'application/json')
connection.setRequestProperty('Accept', 'application/json')
String authString = "${username}:${password}"
String authStringEncoded = authString.bytes.encodeBase64().toString()
connection.setRequestProperty('Authorization', "Basic ${authStringEncoded}")
connection.setRequestProperty('x-csrf-token', 'fetch')
connection.connect()
def res = connection.getResponseCode();
if(res.equals(200) || res.equals(201))
{
token = connection.getHeaderField('x-csrf-token')
}
connection.disconnect()
}
catch(Exception ex)
{
log.error(ex.message)
}
if (token == null){
return
}
//POST
try{
final URL post = new URL(url)
final HttpURLConnection connection = (HttpURLConnection) post.openConnection()
connection.setRequestMethod("POST")
connection.doOutput = true
connection.setRequestProperty('Content-Type', 'application/json')
connection.setRequestProperty('Accept', 'application/json')
String authString = "${username}:${password}"
String authStringEncoded = authString.bytes.encodeBase64().toString()
connection.setRequestProperty('Authorization', "Basic ${authStringEncoded}")
//token
connection.setRequestProperty('x-csrf-token', token)
connection.getOutputStream().write(json.getBytes("UTF-8"))
connection.connect()
def postRC = connection.getResponseCode();
log.warn(postRC)
if(postRC.equals(200))
{
log.info(connection.getInputStream().getText());
}
connection.disconnect()
}
catch(Exception ex1)
{
log.error(ex1.message)
}
POST method returns an error 401: CSRF token verification failed.
I suspect that after closing the GET connection, the token becomes invalid and I can't use it in the POST request. Does anyone know how to solve this problem?
UPD. I found a solution. In this case, I had to use the HttpClient class instead of the HttpURLConnection class
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.