본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

스크립트 클라이언트 인증

원문 보기 위키 갱신

스크립트 클라이언트(예: wget)가 권한이 필요한 작업(예: 빌드 예약)을 호출하게 하려면 HTTP BASIC 인증을 사용해 사용자 이름과 API 토큰을 지정하세요. Jenkins는 권한 협상을 하지 않으므로 첫 요청부터 인증 정보를 보내는 프리엠프티브(preemptive) 인증을 사용해야 해요.

출처: Jenkins 문서

본문

스크립트 클라이언트(예: wget)가 권한이 필요한 작업(예: 빌드 예약)을 호출하게 하려면 HTTP BASIC 인증을 사용해 사용자 이름과 API 토큰을 지정하세요.

이전 버전의 Jenkins는 실제 비밀번호를 지정해야 했으며, 이는 보안 영역이 비밀번호 기반일 때만 사용할 수 있었어요(예: OpenID, Crowd, CAS 플러그인은 비밀번호 없이 인증하므로 비밀번호가 아예 없어요!). 실제 비밀번호 지정은 여전히 지원되지만, 비밀번호가 노출될 위험과 여러 곳에서 같은 비밀번호를 재사용하는 인간의 경향 때문에 권장되지 않아요.

API 토큰은 개인 구성 페이지에서 확인할 수 있어요. 모든 페이지의 오른쪽 위 모서리에 있는 이름을 클릭한 다음 "Security"를 클릭해 API 토큰을 확인하세요. ($root/me/security URL이 좋은 지름길이에요.) 여기서 API 토큰을 변경할 수도 있어요.

Jenkins는 권한 협상(authorization negotiation)을 하지 않는다는 점에 유의하세요. 즉 401(Unauthorized) 응답 대신 즉시 403(Forbidden) 응답을 반환하므로, 첫 요청부터 인증 정보를 보내야 해요(일명 "프리엠프티브 인증(preemptive authentication)").

curl이 있는 셸

curl 명령은 Linux, macOS, Windows, FreeBSD 등을 포함한 대부분의 운영 체제에서 사용할 수 있어요.

curl -X POST -L --user your-user-name:apiToken \
    https://jenkins.example.com/job/your_job/build

wget이 있는 셸

| | wget 명령은 Jenkins에 인증하려면 --auth-no-challenge 옵션이 필요해요. |

wget --auth-no-challenge \
    --user=user --password=apiToken \
    http://jenkins.example.com/job/your_job/build

cdancy/jenkins-rest를 사용한 Groovy 스크립트

cdancy/jenkins-rest 클라이언트는 REST API 접근을 크게 단순화해요. 다음 Groovy 코드는 Jenkins에 인증하고 일부 시스템 정보를 가져오는 방법을 보여줘요:

@Grab(group='com.cdancy', module='jenkins-rest', version='0.0.18')

import com.cdancy.jenkins.rest.JenkinsClient

JenkinsClient client = JenkinsClient.builder()
    .endPoint("http://127.0.0.1:8080") // Optional. Defaults to http://127.0.0.1:8080
    .credentials("user:apiToken") // Optional.
    .build()

println(client.api().systemApi().systemInfo())

추가 정보는 cdancy/jenkins-rest 위키를 참고하세요.

axios를 사용하는 Typescript 스크립트 예제

다음 코드는 작업을 만드는 방법을 보여줘요.

const credentials = `myusername:myapitoken`;
const baseJenkinsUrl = "http://myjenkins:8080";
async function getCrumb() {
    return axios({
      method: "get",
      url: baseJenkinsUrl + "/crumbIssuer/api/json",
      withCredentials: false,
    });
  }
getCrumb().then((response: any) => {
      let crumb = response.data;
     const base64Credentials = btoa(credentials);
    const authHeader = `Basic ${base64Credentials}`;
    // Create new job
    const requestConfig: AxiosRequestConfig = {
      method: "post",
      url: `${baseJenkinsUrl}/createItem?name=${jobName}`,
      headers: {
        Authorization: ***
        [crumb.crumbRequestField]: crumb.crumb,
        "Content-Type": "application/xml",
      },
      data: xmlconfig,
    };
    axios(requestConfig);
});

스크립트 클라이언트용 Perl LWP 예제

다음 Perl 예제는 "Trigger builds remotely" 토큰을 통해 Job을 시작하기 위해 LWP 모듈을 사용해요.

#
# Use LWP to run a Jenkins job
# set authorization_basic on the request object
# to make use of BASIC HTTP authorization, apparently
# already handling the preemptive part correctly this
# way.
#
use strict;
use warnings;

use LWP;

my $server = 'srvname';
my $srvurl = "http://$server/jenkins";
my $uagent = LWP::UserAgent->new;
my $req = HTTP::Request->new(
  GET => "$srvurl/job/test/build?token=theTokenConfiguredForThisJob&cause=LWP+Test"
);
$req->authorization_basic('username@mydomain.com', 'apiToken');
my $res = $uagent->request($req);

# Check the outcome of the response
print "Result: " . $res->status_line . "\n";
print $res->headers->as_string;
print "\n";
if (!$res->is_success) {
  print "Failed\n";
}
else {
  print "Success!\n";
  # print $res->content, "\n";
}

httpclient 4.3.x를 사용하는 Java 예제

이렇게 하면 httpclient 4.3이 프리엠프티브하게 인증을 발행하게 돼요.

import java.io.IOException;
import java.net.URI;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class JenkinsScraper {

    public String scrape(String urlString, String username, String password)
        throws ClientProtocolException, IOException {
        URI uri = URI.create(urlString);
        HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(username, password));
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);
        CloseableHttpClient httpClient =
            HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        HttpGet httpGet = new HttpGet(uri);
        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        HttpResponse response = httpClient.execute(host, httpGet, localContext);

        return EntityUtils.toString(response.getEntity());
    }

}

더 알아보기 (Learn more)