Skip to content

Instantly share code, notes, and snippets.

@jcefoli
Created September 24, 2019 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcefoli/62455688775a5b33f498185931b38319 to your computer and use it in GitHub Desktop.
Save jcefoli/62455688775a5b33f498185931b38319 to your computer and use it in GitHub Desktop.
Kick Jenkins Job With CSRF Protection Enabled [Powershell REST Request]
# Force TLS 1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Basic Auth Credentials
$user = 'changeme'
$pass = 'insecure-password'
# Handle Basic Auth (Hacky in Powershell)
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
# Create Header Object; Add Basic Auth
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "$basicAuthValue")
# REST Request to retrieve the crumb
$crumb = (Invoke-RestMethod -Uri 'https://jenkins-host/jenkins/crumbIssuer/api/json' -Headers $headers).crumb
# Add Crumb to Header
$headers.Add("Jenkins-Crumb", $crumb)
# REST Request to Kick Job
$response = Invoke-RestMethod 'https://jenkins-host/jenkins/job/Job-Name?token=token' -Method Post -Headers $headers -ContentType 'application/json'
#Note: There are no response headers or response body... You can't even see the response status code. This seems to be a limitation to Invoke-RestMethod
@vishpatel20
Copy link

I tried this with my own credentials and it seems that I am not able to retrieve the crumb and the error is invalid operation. I have CRSF enabled. Could you help me debug my script?

@jcefoli
Copy link
Author

jcefoli commented Oct 12, 2023

Hmm, this is rather dated, and I no longer work with Jeninks. It's possible something changed in a newer version. Give this documentation a try: https://medium.com/@rathourarvi/remote-access-to-your-jenkins-using-rest-api-3d0c0bdb48a

@vishpatel20
Copy link

thanks for the documentation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment