How to request for the crumb issuer for Jenkins

前端 未结 8 1291
孤城傲影
孤城傲影 2020-12-08 05:09

I want to use the Jenkins Remote API, and I am looking for safe solution. I came across Prevent Cross Site Request Forgery exploits and I want to use it, but I

8条回答
  •  渐次进展
    2020-12-08 05:21

    This Python function gets the crumb, and additionally uses the crumb to post to a Jenkins endpoint. This is tested with Jenkins 2.46.3 with CSRF protection turned on:

    import urllib.parse
    import requests
    
    def build_jenkins_job(url, username, password):
        """Post to the specified Jenkins URL.
    
        `username` is a valid user, and `password` is the user's password or
        (preferably) hex API token.
        """
        # Build the Jenkins crumb issuer URL
        parsed_url = urllib.parse.urlparse(url)
        crumb_issuer_url = urllib.parse.urlunparse((parsed_url.scheme,
                                                    parsed_url.netloc,
                                                    'crumbIssuer/api/json',
                                                    '', '', ''))
    
        # Get the Jenkins crumb
        auth = requests.auth.HTTPBasicAuth(username, password)
        r = requests.get(crumb_issuer_url, auth=auth)
        json = r.json()
        crumb = {json['crumbRequestField']: json['crumb']}
    
        # POST to the specified URL
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        headers.update(crumb)
        r = requests.post(url, headers=headers, auth=auth)
    
    username = 'jenkins'
    password = '3905697dd052ad99661d9e9f01d4c045'
    url = 'http://jenkins.example.com/job/sample/build'
    build_jenkins_job(url, username, password)
    

提交回复
热议问题