Jenkins - Authenticating scripted clients

在啟用Jenkins Security設定後,不管是web操作還是透過script client形式都必須要認證才更夠使用。本篇文章主要分享我有使用到的script client的認證方式。

Get API Token

使用scripted client存取Jenkins時,為了安全考量,Jenkins官方建議用API token取代真實密碼。取得API Token方式很簡單,假設你的scripted client所使用的user名稱為build,請先使用build登入Jenkins;接著到使用者設定畫面中的API Token點擊Show API Token,就能看到以下畫面:


假如要變更可以點擊Change API Token。

我分享我有使用到的部分,如果有增加會更新:

Java - HttpClient 4.1.3

我使用到的是HttpPost去通知Jenkins build,做法就是把使用者與密碼設定為Basic Authorization的Header:

	private void setupAuthorizationHeader(HttpPost httpPost, String id, String passwd){
		String token = id + ":" + passwd;
		String header = Base64.encodeBase64String(token.getBytes(StandardCharsets.UTF_8)).trim();
		httpPost.addHeader("Authorization", "Basic " + header);
	}
這裡我只列出重要部分的程式碼,client code就不放了。

CURL

curl -X GET --user "build:d1d26b55cec0378450abd1a2df8d3e99"  http://192.168.0.1:8080//job/Test/lastSuccessfulBuild/artifact/installer.exe

Ant

Ant部分我以built-in的get做為範例:

<get dest="${basedir}"	src="http://192.168.0.1:8080//job/Test/lastSuccessfulBuild/artifact/installer.exe" username="build" password="d1d26b55cec0378450abd1a2df8d3e99"/>

Wget

wget --auth-no-challenge --http-user=build --http-password=d1d26b55cec0378450abd1a2df8d3e99 http://192.168.0.1:8080//job/Test/lastSuccessfulBuild/artifact/installer.exe