Home > other >  How to deal with "HTTP ERROR 403 No valid crumb was included in the request" Jenkins?
How to deal with "HTTP ERROR 403 No valid crumb was included in the request" Jenkins?

Time:08-08

I try to abort Jenkins job build using python requests. This is my python code:

    crumb_value = (
        requests.get(f"https://{usr}:{psw}@<jenkins url>/crumbIssuer/api/json", verify=False)).json()["crumb"]
    jenkins_abort = requests.post(f"https://{usr}:{psw}@<job url>/stop",
                                 json={'Jenkins-Crumb': crumb_json}, verify=False)

So firstly I use Get request to get crumb value (this works correctly). Then I send a Post request to abort jenkins build, I include in it json file with proper crumb field name and it's value, but strangly I get output like this:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 403 No valid crumb was included in the request</title>
</head>
<body><h2>HTTP ERROR 403 No valid crumb was included in the request</h2>
<table>
<tr><th>URI:</th><td>/<job url>/stop</td></tr>
<tr><th>STATUS:</th><td>403</td></tr>
<tr><th>MESSAGE:</th><td>No valid crumb was included in the request</td></tr>
<tr><th>SERVLET:</th><td>Stapler</td></tr>
</table>
<hr><a href="https://eclipse.org/jetty">Powered by Jetty:// 9.4.43.v20210629</a><hr/>

</body>
</html>

I've read some stack overflow issues and think that I do what I'm supposed to but it doesn't work. I'll highly appreciate any suggestions on my problem!

CodePudding user response:

Why don't you consider using a Python library like api4jenkins so you don't have to worry about passing the Crumbs?

Since you are getting a Certificate validation error you can either upgrade your certificate to a CA-signed cert or disable it.

jenkins = Jenkins(url, username, password, ssl_verify=False)

Read more here.

CodePudding user response:

I've solved my issue. It turned out that you need to send Get request for crumb and Post request to abort build from same session. The code, that works for me:

session = requests.Session()
session.auth = (usr, psw)

crumb_json = (session.get(get_crumb_url(), verify=False)).json()

    jenkins_abort = session.post(get_current_build_url(), headers={'Jenkins-Crumb': f"{crumb_json['crumb']}"},
                                 json=crumb_json, verify=False)
  • Related