用于触发Jenkins作业的PowerShell命令引发身份验证错误

l5tcr1uw  于 2022-11-02  发布在  Jenkins
关注(0)|答案(2)|浏览(153)
$Auth = "admin:password"
$JenkinsURL = "http://$Auth@172.24.235.27:8080/"
$JobName = "TestItem1"
$JobToken = "token"
$FullURL = "$JenkinsURL/job/$JobName/build?token=$JobToken"
Invoke-WebRequest -UseBasicParsing $FullURL

以上是用于触发Jenkins作业的PowerShell代码。但在执行此代码时,我遇到了“需要身份验证”错误。但来自curl的相同命令工作正常。
我不确定我是否遗漏了URL中的某些内容,或者遗漏了一些Jenkins插件来提供从PowerShell的访问。

w7t8yxp5

w7t8yxp51#

您收到验证错误的原因是您需要将验证转换为base 64字符串。如果您没有在Jenkins中启用CSRF,则可以使用以下脚本。

$UserName = "admin"
$Password = "password"
$API_URL = "jenkinsservername"
$JobName = "TestItem1"
$JobToken = "token"
$header = @{}
$Params = @{}
$header.Add('Authorization', 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$(${UserName}):$(${Password})")))
$Params['uri'] = "http://jenkinsservername/$JobName/build?token=$JobToken"
$Params['Method'] = 'Post'
$Params['Headers'] = $header
Invoke-RestMethod @Params

但是,如果您在Jenkins中启用了CSRF,则使用以下脚本

$UserName = "admin"
$Password = "password"
$API_URL = "jenkinsservername"
$JobName = "TestItem1"
$JobToken = "token"
$header = @{}
$header.Add('Authorization', 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$(${UserName}):$(${Password})")))
$Params = @{uri = "http://${API_URL}:${API_Port}/crumbIssuer/api/json";
        Method = 'Get';
        Headers = $header;}
$API_Crumb = Invoke-RestMethod @Params
write-host $API_Crumb
$h.Add('Jenkins-Crumb', $API_Crumb.crumb)
$Params['uri'] = "http://jenkinsservername/$JobName/build?token=$JobToken"
$Params['Method'] = 'Post'
$Params['Headers'] = $header
Invoke-RestMethod @Params
30byixjq

30byixjq2#

@Mike正确地描述了在使用CSRF时使用Jenkins API的说明。但我想补充的是,在创建面包屑时,会话和cookie也会被考虑在内。
对我有效的代码如下:

$UserName = "admin"
$Password = "password"
$API_URL = "jenkinsservername"
$JobName = "TestItem1"
$JobToken = "token"
$header = @{}
$header.Add('Authorization', 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$(${UserName}):$(${Password})")))
$Params1 = @{uri = "http://${API_URL}:${API_Port}/crumbIssuer/api/json";
            Method = 'Get';
            SessionVariable = 'Session';
            Headers = $header;}
$API_Crumb = Invoke-RestMethod @Params1
write-host $API_Crumb
$header.Add('Jenkins-Crumb', $API_Crumb.crumb)
$Params2 = @{}
$Params2['uri'] = "http://jenkinsservername/$JobName/build?token=$JobToken"
$Params2['Method'] = 'Post'
$Params2['Headers'] = $header
Invoke-RestMethod @Params2 -WebSession $Session

另外,如果工作在文件夹中,则URI会有所不同。例如,如果MyJob在MyFolder中,则URI会是:

http://jenkinsservername/job/MyFolder/job/MyJob/build?token=JobToken

您可以在为作业分配令牌的位置看到此路径

相关问题