As recommended by Jenkins (>2.2xx) you may benefit by creating an API token for the user,
起因
客户反馈外部程序调用 jenkins 流水线遇到 403 授权问题,报错类似如下:
2021-05-17 06:47:32 UTC| urllib.error.HTTPError: HTTP Error 403: Forbidden
2021-05-17 06:47:32 UTC|
2021-05-17 06:47:32 UTC| During handling of the above exception, another exception occurred:
2021-05-17 06:47:32 UTC| Traceback (most recent call last):
2021-05-17 06:47:32 UTC| File "/opt/jenkins-integration/dao_jenkins.py", line 65, in run
2021-05-17 06:47:32 UTC| self._server.build_job(self._project_name)
2021-05-17 06:47:32 UTC| File "/usr/local/lib/python3.7/site-packages/jenkins/__init__.py", line 1051, in build_job
2021-05-17 06:47:32 UTC| self.build_job_url(name, parameters, token), b''))
2021-05-17 06:47:32 UTC| File "/usr/local/lib/python3.7/site-packages/jenkins/__init__.py", line 448, in jenkins_open
2021-05-17 06:47:32 UTC| e.code, e.msg)
2021-05-17 06:47:32 UTC| jenkins.JenkinsException: Error in request. Possibly authentication failed [403]: Forbidden
2021-05-17 06:47:32 UTC|
2021-05-17 06:47:32 UTC| During handling of the above exception, another exception occurred:
分析
日志提示写的很清楚了403,授权问题,客户表示账号密码登陆jenkins正常。
了解具体操作的过程中,客户表示jenkins版本从2.156升级到了2.222.4,那么可以肯定是版本变化导致的 api 调用有了变化。
解决
以及里面提到的jenkins官网介绍 https://www.jenkins.io/doc/book/system-administration/authenticating-scripted-clients/
To make scripted clients (such as wget) invoke operations that require authorization (such as scheduling a build), use HTTP BASIC authentication to specify the user name and the API token.
The API token is available in your personal configuration page. Click your name on the top right corner on every page, then click "Configure" to see your API token. (The URL $root/me/configure
is a good shortcut.) You can also change your API token from here.
Note that Jenkins does not do any authorization negotiation. i.e. it immediately returns a 403 (Forbidden) response instead of a 401 (Unauthorized) response, so make sure to send the authentication information from the first request (aka "preemptive authentication").
一句话概括:脚本调用客户端建议大家使用API token方式授权。
如何生成jenkins apitoken
这里多截一个图,说明如何生存 token
访问 URL $root/me/configure
如我本次的 http://10.23.3.91:8080/me/configure, configure,添加新token即可。
测试
先简单拿curl测试一下
curl -X POST -L --user guest:118112d81f685c79a086f755a19e95ead0 http://10.23.3.91:8080/view/etc/job/check-dip-env/build
流水线顺利执行。 客户实际环境也在生成并调用apitoken后,问题解决。
对比测试
curl -X POST -L --user guest:密码 http://10.23.3.91:8080/view/etc/job/check-dip-env/build
报错输出 Error 403 No valid crumb was included in the request
token故意打错,报错输出 Error 401 Unauthorized
文章评论