问题
I'm trying to use the Jenkins json API and cannot get the authentication to work.
setup:
- Jenkins security:
Jenkin’s own user database
- access:
Matrix-gebaseerde beveiliging
- CORS via Jenkins CORS plugin
- using username/api token of a registered user
tried:
var username = "username";
var apiToken = "apiToken";
// username / api-token on url (basic authentication)
$.ajax({
url: "http://"+username+":"+apiToken+"@host:port/job/test/api/json",
method: "GET"
});
// username / api-token supplied using jQuery's username/password properties
$.ajax({
url: "http://host:port/job/test/api/json",
method: "GET",
username: username,
password: apiToken
});
// username / api-token by setting "Authorization" header directly
$.ajax({
url: "http://host:port/job/test/api/json",
method: "GET",
headers: {
"Authorization": "Basic " + btoa(username + ":" + apiToken)
}
});
All these attempts result in the same result: response: 403 Forbidden
回答1:
I have had some success with this. Note: I had to add two add_header lines to our nginx proxy config...
add_header Access-Control-Allow-Origin 'http://localhost:9001';
add_header Access-Control-Allow-Credentials 'true';
Then I can do this in Jenkins. It seems to not need any user/pass/token as long as my browser is authorised in another tab (shares the same session/cookie).
$.ajax({
url:'https://myserver.com/job/MYJOB/lastBuild/api/json',
method: 'GET',
xhrFields: {
withCredentials: true
}
}).done(function(data) {
console.log(data);
}).fail(function() {
console.error(arguments);
});
回答2:
In response to @nick providing the answer:
I've used Jenkins Cors Filter Plugin to add the CORS headers which are needed:
Access-Control-Allow-Origins: http://mydomain
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Authorization
The solution of @nick requires you to be authenticated in the same browser.
To provide credentials via the REST call I've added an "Authorization" header
like this:
$.ajax({
url:'https://myserver.com/job/MYJOB/lastBuild/api/json',
method: 'GET',
headers: {'Authorization': 'Basic ' + btoa('username:apitoken')}
}).done(function(data) {
console.log(data);
}).fail(function() {
console.error(arguments);
});
The apitoken
can be retrieved via the configuration of the specific user to use in Jenkins itself.
来源:https://stackoverflow.com/questions/33508417/jenkins-json-rest-api-with-cors-request-using-jquery