I'm developing a web site which allows the administrator to create users on RabbitMQ.
I checked the RabbitMQ api doc, and found an example to create user on windows/unix prompt. The command line seens like this:
curl -i -u ADMIN_USER: ADMIN_PASSW -H "content-type:application/json" -XPUT
{"password":"PASSW_WRITTEN","tags":"administrator"}
http://IP_ADRESS:PORT/api/users/USER_NAME
Here follows the link to the doc
http://hg.rabbitmq.com/rabbitmq-management/raw-file/rabbitmq_v3_4_1/priv/www/api/index.html
In the prompt, it works fine. But on a web site, I have no idea how to send this command.
Note I'm developping on Java Web with JSF, but any other web language example is welcome.
Thanks for any help.
After a long time searching on the internet, I finally found how to create users on RabbitMQ programmatically. Basically, you have to send a HTTP request with PUT or POST "status". Since I'm developing on Java Web, I could easily find a Java library to support me. I used Apache HTTP library, you can find it here:
http://hc.apache.org/downloads.cgi
So, my Java code it's posted below:
For libs, imports:
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.commons.codec.binary.Base64;
The code to create a new User:
// First, save your user/pw with permission to create new users.
// NOTE: this user is already created on RabbitMQ with permission to create new users
String enc = new String( Base64.encodeBase64( "USER_NAME_WITH_PERMISSION:PASS_W".getBytes() ) );
try{
HttpPut putCriaUsuario = new HttpPut( "http://RABBIT_MQ_IP:PORT/api/users/USER_NAME_TO_CREATE );
putCriaUsuario.addHeader( "Authorization", "Basic " + enc ); // RabbitMQ requires a user with create permission, create it mannually first
putCriaUsuario.addHeader( "content-type", "application/json" );
putCriaUsuario.setEntity( new StringEntity( "{\"password\":\"YOUR_PASS_WORD\",\"tags\":\"none\"}" ) );
client.execute( putCriaUsuario );
//After create, configure RabbitMQ permissions
HttpPut putConfiguraPermissoes = new HttpPut( "http://RABBIT_MQ_IP:PORT/api/permissions/QUEUE_NAME/USER_NAME_CREATED" );
putConfiguraPermissoes.addHeader( "Authorization", "Basic " + enc );
putConfiguraPermissoes.addHeader( "content-type", "application/json" );
putConfiguraPermissoes.setEntity( new StringEntity( "{\"configure\":\"^$\",\"write\":\".*\",\"read\":\".*\"}" ) ); // Permission you wanna. Check RabbitMQ HTTP API for details
client.execute( putConfiguraPermissoes );
}catch( UnsupportedEncodingException ex ){
ex.printStackTrace();
}catch( IOException ex ){
ex.printStackTrace();
}
This is Java, so it can be used on desktop application or Java Web. On other language follows the same logic, just with another libs. Hope it help us all. Fells happy for sharing knowledge!
for those who are facing a problem with granting permission this one works for me
HttpPut putConfiguraPermissoes = new HttpPut("http://127.0.0.1:15672/api/permissions/%2F/THE_NAME_OF_THE_NEW_USER" );
putConfiguraPermissoes.addHeader( "Authorization", "Basic " + enc );
putConfiguraPermissoes.addHeader( "content-type", "application/json" );
putConfiguraPermissoes.setEntity( new StringEntity( "{\"configure\":\".*\",\"write\":\".*\",\"read\":\".*\"}" ) );
CloseableHttpClient client2 = HttpClients.createDefault();
lient2.execute( putConfiguraPermissoes );
Related
var url = "https://web-site_name/page/?format=json&var_data-organization_dates&xlsexport=true";
var payload =
{
"login" : "login",
"password" : "pass",
};
var options =
{
"method" : "post",
"payload" : payload,
"followRedirects" : false
};
var login = UrlFetchApp.fetch("https://web-site_name/page/" , options);
var sessionDetails = login.getAllHeaders()['Set-Cookie'];
Logger.log(login.getAllHeaders());
here is the part of the code I try to use, to automate export of the data from web-site, i do have proper login and password and able to download file in json (opened in xsl) manually, I've got the address to the downloaded file in network in developer tools, but i have a problem on the first stage - when trying to authorize to the web-site - access denied. I've tried the code, given in answers on stackoverflow, but it still doesn't work.
How to make an url fetch request correctly, depends on the website you want to access and the authentication they uses
In the simplest case, your website requires HTTP basic authentification, in this case the correct syntax would be
var authHeader = 'Basic ' + Utilities.base64Encode(login + ':' + pass);
var options = {
headers: {Authorization: authHeader}
}
If your website uses a different authentication form, you might need to provide an access token.
In any case: the authentication credentials go into headers, not into payload!
payload is the data that you want to post = upload to the website.
If you want export data from the website - that is download data - you do not need a payload and the correct method would be get, not post. Btw., if the method is get, you do not need to specify it.
Please see here for more information and samples.
I'm currently working with Spreedly REST API which works with basic http authentication.
At first, I set my credentials this way:
webRequest.Credentials = new System.Net.NetworkCredential(user, password);
It worked well for many of the API resources including POSTing new gateways, GETing gateways, PUTing data on a gateway and even redacting a gateway.
I hit a wall when I tried to POST a new payment_method at their /v1/payment_methods.<format> resource.
The error I'm getting:
HTTP 422
{
"errors": [
{
"key": "errors.environment_key_parameter_required",
"message": "You must specify an environment_key parameter."
}
]
}
After verifying a lot of things, I tried it using curl based on their examples and it worked.
The issue seems to be in the way I set my credentials in the HttpWebRequest even though it's the same code I use for the other working resources.
I tried using the CredentialCache because I could specify "Basic" and it failed the same way:
CredentialCache cache = new CredentialCache();
cache.Add(webRequest.RequestUri, "Basic", new System.Net.NetworkCredential(user, password));
webRequest.Credentials = cache;
Here's what worked:
I created my own authorization HTTP header as suggested in https://stackoverflow.com/a/13956730/5869109 and it worked well:
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1")
.GetBytes(user + ":" + password));
webRequest.Headers.Add("Authorization", "Basic " + encoded);
I've downloaded a exampled that show the files in the "Shared with everyone" folder in my OneDrive for Bussiness. It's work fine!
But, when I try to create a Folder or File (without content) like this documentation the response became with a BadRequest .
The request goes like:
string requestUrl = String.Format(CultureInfo.InvariantCulture, "{0}/files", serviceInfo.ApiEndpoint);
// Prepare the HTTP request:
using (HttpClient client = new HttpClient())
{
Func<HttpRequestMessage> requestCreator = () =>
{
HttpRequestMessage request = new HttpRequestMessage( HttpMethod.Post, requestUrl);
request.Headers.Add("Accept", "application/json;odata.metadata=full");
request.Content = new StringContent(#"{'__metadata':{'type':'MS.FileServices.Folder'},Name:'TestFolder'}");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return request;
};
}
And the response is a BadRequest.
I think that my problem is in the "__metadata"'s json value. It´s is correct? Where can I find a working example implementing this operations?
Thanks in advance!
EDIT: Changing the API Endpoint from "/_api/web/getfolderbyserverrelativeurl('Documents')/files" to "_api/files" the error became to: "The property '__metadata' does not exist on type 'MS.FileServices.FileSystemItem'. Make sure to only use property names that are defined by the type."
I´m think I foward in this. But, I still continue with problems.
I am not sure if this can be of any help to you, as this pertains to oneDrive and not oneDrive for business.
Also the documentations are confusing :)
according to the documentation the request should be as follow:
POST https://apis.live.net/v5.0/me/skydrive
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json
{
"name": "My example folder"
}
if you can see that in the header there is authorization access token
I don't see that you sent to the server any access token. and that is why you had a bad request.
I am trying to below way to create a folder in SP and it's working for me. Hope it will work for you as well.
Create a folder using SharePoint Web API -
POST https://<Domain>.sharepoint.com/_api/web/folders
Accept: "application/json;odata=verbose"
Content-Type: "application/json"
{
"ServerRelativeUrl": "/Shared Documents/<Folder-Name>"
}
I have to create/update a jenkins job using its api because all of my jobs are using parameters which are also used by other scripts and I am trying to centralize the scripts so when i change it in one place, the change reflects in all.
currently, if someone changes the script, they they also have to manually edit the parameters of the jenkins job as well.
I saw the example of the Remote API for creating jobs and was able to successfully create test jobs but how can i edit an existing job besides deleting it and creating it again(which isnt an option as i have to maintain the build history).
You could use python like this:
from jenkinsapi.jenkins import Jenkins
jenkinsSource = 'http://10.52.123.124:8080/'
server = Jenkins(jenkinsSource, username = 'XXXXX', password = 'YYYYY')
myJob=server.get_job("__test")
myConfig=myJob.get_config()
print myConfig
new = myConfig.replace('<string>clean</string>', '<string>string bean</string>')
myJob.update_config(new)
in case anyone else is also looking for the same answer,
It appears the solution is far easier, all you have to do is update the config.xml and post the updated config.xml back to jenkins and your job will be updated.
You can also POST an updated config.xml to the URL which can fetch config.xml, to programmatically update the configuration of a job.
The fetch url pattern: $JENKINS_SERVER/job/$JOB_NAME/config.xml
detailed doc pattern: $JENKINS_SERVER/job/$JOB_NAME/api
example: https://ci.jenkins-ci.org/job/infra_atlassian-base/api/
http://asheepapart.blogspot.ca/2014/03/use-jenkins-rest-api-to-update-job.html
That little bit of scripting looks to be what you are looking for. Uses the REST API to get and set the config with some regex S&R in the middle.
Edit: Code below based on comment. It is copied directly from the blog so I take no credit for it.
# First, get the http://jenkins.example.com/job/folder-name/job/sample-job--template/configure looking like you want
read -s token
# type token from http://jenkins.example.com/user/$userName/configure
# Download the configuration XML for the template job (which will be our model template)
curl -v -u "bvanevery:$token" http://jenkins.example.com/job/folder-name/job/sample-job--template/config.xml > generic-config.xml
# My modules
declare modules=('module1' 'module2' 'module3')
# POST the updated configuration XML to Jenkins
for m in ${modules[#]}; do
echo "module $m";
sed "s/MODULE/$m/g" generic-config.xml > $m-config.xml;
curl -v -X POST --data-binary #$m-config.xml -u "bvanevery:$token" \
-H 'Content-Type: application/xml' \
"http://jenkins.example.com/job/folder-name/job/$m/config.xml" ;
done
For those using RestSharp, I found that I needed to make sure that:
The user ID performing the update had permission to do so under Manage > Global Security > Authorization Matrix
I had a current Jenkins Crumb token, required once CSRF (also under Manage > Security) is enabled.
Send the updated XML using a parameter of the Request object with the value of [ParameterType.RequestBody] (link)1 for the type argument.
private XmlDocument JobConfigGet()
{
Uri JobConfigURI = GetJenkinsURI("job/" + _args.JobName + "/config.xml", null);
RestClient restClient = new RestClient(JobConfigURI);
RestRequest restRequest = new RestRequest(Method.GET);
byte[] ua = Encoding.ASCII.GetBytes(Properties.Settings.Default.UserID + ":" + Properties.Settings.Default.UserPassword);
restRequest.AddHeader("authorization", "Basic " + Convert.ToBase64String(ua));
IRestResponse restResponse = restClient.Execute(restRequest);
if (restResponse.ResponseStatus != ResponseStatus.Completed || restResponse.StatusCode != HttpStatusCode.OK)
throw new Exception(string.Format("Unable to retrieve job config: {0}. Wrong ResponseStatus ({1}) or StatusCode ({2}) returned.\nURL: {3}", _args.JobName, restResponse.ResponseStatus.ToString(), restResponse.StatusCode.ToString(), restClient.BaseUrl.AbsoluteUri));
if (restResponse.ContentType != "application/xml")
throw new Exception("Unexpected data type returned for job config: " + _args.JobName + ". Expected 'application/xml'. Got: " + restResponse.ContentType + ".\nURL: " + restClient.BaseUrl.AbsoluteUri);
XmlDocument jobConfig = new XmlDocument();
jobConfig.LoadXml(restResponse.Content);
return jobConfig;
}
private void JobConfigUpdate(XmlDocument JobConfig, string JenkinCrumb)
{
// Update JobConfig XML as needed here.
Uri JobConfigURI = GetJenkinsURI("job/" + _args.JobName + "/config.xml", null);
RestClient restClient = new RestClient(JobConfigURI);
RestRequest restRequest = new RestRequest(Method.POST);
byte[] ua = Encoding.ASCII.GetBytes(Properties.Settings.Default.UserID + ":" + Properties.Settings.Default.UserPassword);
restRequest.AddHeader("authorization", "Basic " + Convert.ToBase64String(ua));
string[] crumbSplit = JenkinCrumb.Split(':');
restRequest.AddHeader(crumbSplit[0], crumbSplit[1]);
restRequest.AddParameter("text/xml", JobConfig.InnerXml, ParameterType.RequestBody);
IRestResponse restResponse = restClient.Execute(restRequest);
string resp = restResponse.Content;
}
curl -v -X POST https://jenkinsurl.fr:8443/job/jobname/config.xml --data-binary "#config.xml" -u "jenkinsusername:yourjenkinstoken" -H "Content-Type: application/xml"
I am developing mobile apps using rhodes. I want to access private repo of github. I am having only username and password.
How to get token of given username and password.
Once you have only login and password you can use them using basic auth. First of all, check if this code shows you json data of desired repo. Username and password must be separated by a colon.
curl -u "user:pwd" https://api.github.com/repos/user/repo
If succeeded you should consider doing this request from code.
import urllib2
import json
from StringIO import StringIO
import base64
username = "user#example.com"
password = "naked_password"
req = urllib2.Request("https://api.github.com/repos/user/repo")
req.add_header("Authorization", "Basic " + base64.urlsafe_b64encode("%s:%s" % (username, password)))
req.add_header("Content-Type", "application/json")
req.add_header("Accept", "application/json")
res = urllib2.urlopen(req)
data = res.read()
repository = json.load(StringIO(data))
You should use oauth instead: http://developer.github.com/v3/oauth/
Github users can create Personal Access Tokens at their application settings. You can use this token as an alternative to username/password in basic http authentication to call the API or to access private repositories on the github website.
Simply use a client that supports basic http authentication. Set the username equal to the token, and the password equal to x-oauth-basic. For example with curl:
curl -u <token>:x-oauth-basic https://api.github.com/user
See also https://developer.github.com/v3/auth/.
Send A POST request to /authorizations
With headers
Content-Type: application/json
Accept: application/json
Authorization: Basic base64encode(<username>:<password>)
But remember to take Two factor Authentication in mind
https://developer.github.com/v3/auth/#working-with-two-factor-authentication
Here You will receive a token which can be used for further request
Follow this guide at help.github.com. It describes how to find your api-token (it's under "Account Settings" > "Account Admin") and configuring git so it uses the token.
Here is the code to use GitHub Basic Authentication in JavaScript
let username = "*******";
let password = "******";
let auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var options = {
host: 'api.github.com',
path: '/search/repositories?q=google%20maps%20api',
method: 'GET',
headers: {
'user-agent': 'node.js',
"Authorization": auth
}
};
var request = https.request(options, function (res) {
}));