Quick blox - Signature generation issue - ios

I am trying to use this link to get described response:
{
"session": {
"application_id": 2,
"created_at": "2012-04-03T07:34:48Z",
"device_id": null,
"id": 743,
"nonce": 1308205278,
"token": "0e7bc95d85c0eb2bf052be3d29d3df523081e87f",
"ts": 1333438438,
"updated_at": "2012-04-03T07:34:48Z",
"user_id": null
}
}
But now it say application not found:
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>No application found</error>
</errors>
Can't go ahead to test another requests. This is a shell script I used for getting curl request:
timestamp=`date +%s`
body="application_id=HIDDENAPPLICATIONIDHERE&auth_key=HIDDENAUTHKEYHERE&nonce=2342546&timestamp=$timestamp"
signature=`echo -n $body | openssl sha -hmac HIDDENSECRETHERE`
body=$body"&signature="$signature
#echo $body
#echo $signature
#exit 0
curl -X POST \
-H "QuickBlox-REST-API-Version: 0.1.0" \
-d $body \
https://api.quickblox.com/session.xml
So there some info regrding this maybe I've created shell script to a wrong way:
HMAC-SHA function of the body of the request, with a key auth_secret.
Request body is formed as the sorted (sorting alphabetically, as
symbols, not as bytes) by increase the string array 'parameter=value',
separated with the symbol "&". For the parameters passed as a
user[id]=123 is used just such a line of user[id]=123
Also I've prepped a Swift project how to generate signature and get session, but still has the same error with no application found.
Any recommendation? Thanks

Please verify Application ID parameter because server return:
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>No application found</error>
</errors>
For example generate signature (Java):
Random random = new Random();
String nonce = Integer.toString(random.nextInt());
long time = System.currentTimeMillis() / 1000;
String timestamp = Long.toString(time);
String signature;
String str = "application_id=" + applicationId + "&" + "auth_key=" + authKey + "&" + "nonce="
+ nonce + "&" + "timestamp=" + timestamp + "&" + "user[login]=" + adminLogin + "&" + "user[password]="
+ adminPassword;
signature = UtilsMethods.calculateHMAC_SHA(str, authSecret);
calculateHMAC_SHA:
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public static String calculateHMAC_SHA(String data, String key) throws SignatureException {
String result = null;
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
byte[] digest = mac.doFinal(data.getBytes());
StringBuilder sb = new StringBuilder(digest.length * 2);
String s;
for (byte b : digest) {
s = Integer.toHexString(0xFF & b);
if (s.length() == 1) {
sb.append('0');
}
sb.append(s);
}
result = sb.toString();
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}

Related

How to use `StaplerResponse rsp` in `AsyncResourceDisposer.doStopTracking()`

I'm trying to remove (stop tracking) trackig item from Jenkins AsyncResourceDisposer (${JENKINS_URL}/administrativeMonitor/AsyncResourceDisposer) via groovy scripts (${JENKINS_URL}/script).
According to the Javadoc and source code
// Javadoc
#Restricted(value=org.kohsuke.accmod.restrictions.DoNotUse.class)
public org.kohsuke.stapler.HttpResponse doStopTracking(#QueryParameter
int id,
org.kohsuke.stapler.StaplerResponse rsp
)
// source code
#Restricted(DoNotUse.class)
#RequirePOST
public HttpResponse doStopTracking(#QueryParameter int id, StaplerResponse rsp) {
...
}
I'd like to know how to add org.kohsuke.stapler.StaplerResponse rsp in doStopTracking(int id, org.kohsuke.stapler.StaplerResponse rsp):
import org.jenkinsci.plugins.resourcedisposer.AsyncResourceDisposer
AsyncResourceDisposer disposer = AsyncResourceDisposer.get()
disposer.backlog.each {
disposer.doStopTracking( it.id, <what should I put here> )
}
Current I can get the item id, and the other informaitons like below:
import org.jenkinsci.plugins.resourcedisposer.AsyncResourceDisposer
AsyncResourceDisposer disposer = AsyncResourceDisposer.get()
String url = Jenkins.instance.rootUrl + disposer.url
disposer.getBacklog().each { item ->
println "\n${item.id} : \t${url}/stopTracking/?id=${item.id} : \t${item.class.simpleName} : \n" +
"\t${item.getLastState().getDisplayName()} : \n" +
"\t${item.getDisposable().node} : ${item.getDisposable().path}\n" +
"\t${item.toString()}"
}
If I'm go to the url "${url}/stopTracking/?id=${item.id}" in browser (login first), the item can be removed after click RETRY USING POST (as below)
So... I'm using the API call curl -H <crumbIssues> -X POST <url> by passed the disposer.doStopTracking(int, org.kohsuke.stapler.StaplerResponse) (still really wants know how to use it)
Before running the following script, Strict Crumb Issuers Plugin is necessary to be installed and configured (or setup -Dhudson.security.csrf.DefaultCrumbIssuer.EXCLUDE_SESSION_ID=true) due to SECURITY-626 : Improved CSRF protection since:
obtain a crumb using the /crumbIssuer/api URL will now fail to perform actions protected from CSRF unless the scripts retain the web session ID in subsequent requests.
Here is details:
import org.jenkinsci.plugins.resourcedisposer.AsyncResourceDisposer
import org.jenkinsci.plugins.strictcrumbissuer.StrictCrumbIssuer
AsyncResourceDisposer disposer = AsyncResourceDisposer.get()
StrictCrumbIssuer issuer = jenkins.model.Jenkins.instance.crumbIssuer
String jenkinsCrumb = "${issuer.crumbRequestField}:${issuer.crumb}"
String url = Jenkins.instance.rootUrl + disposer.url
disposer.getBacklog().each { item ->
println "\n ~~> removeing ${item.id} : "
[ 'bash', '-c', 'curl -s ' +
'-u <user>:<token> ' +
'-X POST ' +
"-H \"Content-Type: application/json\" " +
"-H \"Accept: application/json\" " +
"-H \"${jenkinsCrumb}\" " +
"${url}/stopTracking/?id=${item.id} "
].execute().with{
def stdout = new StringBuffer()
def stderr = new StringBuffer()
it.waitForProcessOutput( stdout, stderr )
println "EXIT CODE: ${it.exitValue()}"
println "ERROR: ${stderr}"
println "OUTPUT: ${stdout}"
}
}
Although, I still have a question... As we know that if the groovy script running in ${JENKINS_URL}/script, which means the "runner" is the administrator, so, how I can remove the specific user authorication '-u <user>:<token>' (by using the jenkins administrator authorication) in curl ?

Jenkins Docker container - 403 no valid crumb was included in the request

I'm setting up my Jenkins server, and on simple requests in the web interface, like creating a folder, a pipeline, a job, etc., I periodically get the following error:
HTTP ERROR 403
Problem accessing /job/Mgmt/createItem. Reason:
No valid crumb was included in the request
The server is using the Jenkins/Jenkins container, orchestrated by Kubernetes on a cluster on AWS created with kops. It sits behind a class ELB.
Why might I be experiencing this? I thought the crumb was to combat certain CSRF requests, but all I'm doing is using the Jenkins web interface.
Enabling proxy compatibility may help to solve this issue.
Go to Settings -> Security -> Enable proxy compatibility in CSRF Protection section
Some HTTP proxies filter out information that the default crumb issuer uses to calculate the nonce value. If an HTTP proxy sits between your browser client and your Jenkins server and you receive a 403 response when submitting a form to Jenkins, checking this option may help. Using this option makes the nonce value easier to forge.
After a couple of hours of struggling, I was able to make it work with curl:
export JENKINS_URL=http://localhost
export JENKINS_USER=user
export JENKINS_TOKEN=mytoken
export COOKIE_JAR=/tmp/cookies
JENKINS_CRUMB=$(curl --silent --cookie-jar $COOKIE_JAR $JENKINS_URL'/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)' -u $JENKINS_USER:$JENKINS_TOKEN)
echo $JENKINS_CRUMB
curl --cookie $COOKIE_JAR $JENKINS_URL/createItem?name=yourJob --data-binary #jenkins/config.xml -H $JENKINS_CRUMB -H "Content-Type:text/xml" -u $JENKINS_USER:$JENKINS_TOKEN -v
when calling the http://JENKINS_SERVER:JENKINS_PORT/JENKINS_PREFIX/crumbIssuer/api/json you receive a header ("Set-Cookie") to set a JSESSIONID, so you must supply it in the upcoming requests you issue,
the reason is that jenkins test for valid crumb in this manner: comparing the crumb you send in the request with a crumb it generates on the server side (using your session id),
you can see it in jenkins code: scroll down to method:
public boolean validateCrumb(ServletRequest request, String salt, String crumb)
it means you HAVE to include a session in the next requests (after fetching the crumb)!
so the curl --cookie must be used as ThiagoAlves stated in his solution
i use java so i used this next tester (HTTPClient would be prefered, but i wanted a simple java only example):
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
public class JobRunner
{
String jenkinsUser = "tester";
String jenkinsPassword = "1234"; // password or API token
String jenkinsServer = "localhost";
String jenkinsPort = "8080";
String jenkinsPrefix = "/jenkins";
String jSession = null;
String crumb = null;
HttpURLConnection connection = null;
String responseBody = "";
public void openConnection(String requestMethod, String relativeURL) throws Exception
{
// prepare the authentication string
String authenticationString = jenkinsUser + ":" + jenkinsPassword;
String encodedAuthenticationString = Base64.getEncoder().encodeToString(authenticationString.getBytes("utf-8"));
// construct the url and open a connection to it
URL url = new URL("http://" + jenkinsServer + ":" + jenkinsPort + jenkinsPrefix + relativeURL);
connection = (HttpURLConnection) url.openConnection();
// set the login info as a http header
connection.setRequestProperty("Authorization", "Basic " + encodedAuthenticationString);
// set the request method
connection.setRequestMethod(requestMethod);
}
public void readResponse() throws Exception
{
// get response body and set it in the body member
int responseCode = connection.getResponseCode();
switch (responseCode)
{
case 401:
System.out.println("server returned 401 response code - make sure your user/password are correct");
break;
case 404:
System.out.println("server returned 404 response code - make sure your url is correct");
break;
case 201:
case 200:
System.out.println("server returned " + responseCode + " response code");
InputStream responseBodyContent = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(responseBodyContent));
String currentLine;
while ((currentLine = bufferedReader.readLine()) != null)
{
responseBody = responseBody + currentLine + "\n";
}
break;
default:
System.out.println("server returned error response code: " + responseCode);
break;
}
}
public void setSessionCookie() throws Exception
{
jSession = connection.getHeaderField("Set-Cookie");
System.out.println("jSession: " + jSession);
}
public void disconnect() throws Exception
{
if(connection!=null)
{
connection.disconnect();
connection = null;
responseBody = "";
}
}
public void getCrumb() throws Exception
{
try
{
openConnection("GET", "/crumbIssuer/api/json");
readResponse();
setSessionCookie();
int crumbIndex = responseBody.indexOf("crumb\":\"");
if(crumbIndex!=-1)
{
int crumbIndexEnd = responseBody.indexOf("\",\"", crumbIndex);
crumb = responseBody.substring(crumbIndex + "crumb\":\"".length(), crumbIndexEnd);
System.out.println(crumb);
}
}
finally
{
disconnect();
}
}
public void runJob() throws Exception
{
try
{
openConnection("POST", "/job/test/build");
connection.setDoOutput(true);
connection.setRequestProperty("Cookie", jSession);
connection.setRequestProperty("Jenkins-Crumb", crumb);
readResponse();
System.out.println("Post response: " + responseBody);
}
finally
{
disconnect();
}
}
public static void main(String[] args)
{
JobRunner jobRunner = new JobRunner();
try
{
jobRunner.getCrumb();
jobRunner.runJob();
}
catch (Exception err)
{
err.printStackTrace();
}
}
}

OAuth 1.0 A Invalid Signature when requesting request token (SalesForce/JIRA Integration)

I've been trying my darndest to avoid asking a question. I'm recieving an invalid signature error when trying to request a request token from JIRA from within Salesforce. The response I'm getting is:
08:15:24:201 USER_DEBUG [30]|DEBUG|
oauth_problem=signature_invalid
&oauth_signature=RaOPaBPznmS7aDUuJN1pOclcyHWP4uRYYx4j%2F%2BdtKB1SD4l1JcCCys3P3RAa8P7377MwLsIMBtkHfL62jaXr5LV30RndjVUSlCsVl3h47CvinHgDtTMwWGukQJXhOmSsLPvccCqD7qsRmiQnnjSJCwd9YKJEi2cxNcwMqhnceqAwJdzn3RD%2FBBeNpf3G97wqWhJx%2FtyEhQGk35OTu00fhtw%2BIX025STN3iiGNbyANlmoImAGWqAJeqJOPUVva7TR2OAInysL9%2BHmYkQTOcb7a9sn5rRWUqE4Jua6EoVyPgzJnSgZ4pFEIMzU0eTWQqhSFdQwOdnoq5EQU8W%2BPJM8uA%3D%3D
&oauth_signature_base_string=POST%26https%253A%252F%252F.atlassian.net%252Fplugins%252Fservlet%252Foauth%252Frequest-token%26oauth_consumer_key%253D3MVG9KI2HHAq33RwCPH5bNzAHbOgfiicjJ6HjvVfNhGU8aWXGl6ps.vsEzobCPqRXuDcmeV2Baw%25253D%25253D%2526oauth_nonce%253D-6826921263934288296%2526oauth_signature_method%253DRSA-SHA1%2526oauth_timestamp%253D1492182924
&oauth_signature_method=RSA-SHA1
The code I'm using to try to generate the signature is:
// GitHub OAuth Playground: https://github.com/jesperfj/sfdc-oauth-playground/blob/master/OAuth/src/classes/OAuth.cls
// OAuth Bible: http://oauthbible.com/
// Static Values
String consumerKey = '3MVG9KI2HHAq33RwCPH5bNzAHbOgfiicjJ6HjvVfNhGU8aWXGl6ps.vsEzobCPqRXuDcmeV2Baw==';
String endpoint = 'https://<AtlassianSiteName>.atlassian.net/plugins/servlet/oauth/request-token';
// Params
String callbackParam = '&oauth_callback=' + EncodingUtil.urlEncode('https://localhost/', 'UTF-8');
String consumerKeyParam = '&oauth_consumer_key=' + EncodingUtil.urlEncode(consumerKey, 'UTF-8');
String signatureMethodParam = '&oauth_signature_method=RSA-SHA1';
String timestampParam = '&oauth_timestamp=' + String.valueOf(DateTime.now().getTime()/1000);
String nonceParam = '&oauth_nonce=' + String.valueOf(crypto.getRandomLong());
String versionParam = '&oauth_version=1.0';
String paramString = consumerKeyParam + nonceParam + signatureMethodParam + timestampParam + versionParam + callbackParam;
// Get baseString
String baseString = 'POST&' + encodingUtil.urlEncode(endpoint, 'UTF-8') + paramString;
system.debug(baseString);
blob sig = crypto.signWithCertificate('RSA-SHA1', blob.ValueOf(baseString), 'SelfSignedCert_26Oct2015_184625');
String signature = EncodingUtil.urlEncode(EncodingUtil.base64encode(sig), 'UTF-8');
httpRequest req = new httprequest();
http http = new http();
req.setEndPoint(endpoint);
req.setMethod('GET');
req.setBody(paramString +
'&oauth_signature=' + signature);
httpresponse res = http.send(req);
system.debug(res.getBody());
Note: Yes I understand that I probably shouldn't be sharing some of this information but these are my personal test orgs that contain nothing important and I'm not providing the SSL used. You'll notice some comments at the top of my code containing a few urls to my favorite resources that have gotten me this far. These are not the only resources I've used, just the most useful ones.

Oauth not working CX api

I'm trying to use the oauth for CX exposed api, I followed their documentation, still I'm getting HTTP "BAD REQUEST" error, Here is the code -
String method = "POST";
String code = "";
NameValuePair[] data = {
new NameValuePair("grant_type", "authorization_code"),
new NameValuePair("code", code),
new NameValuePair("redirect_uri",URLEncoder.encode(CALLBACK_URL, "UTF-8"))
};
String secret = CONSUMER_KEY+":"+CONSUMER_SECRET;
String encodedSecret = Base64.encodeBase64String(secret.getBytes("UTF-8"));
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
PostMethod httpMethod = new PostMethod(ACCESS_TOKEN_ENDPOINT_URL);
httpMethod.addRequestHeader("Authorization","Basic "+encodedSecret);
httpMethod.setRequestBody(data);
System.out.println("HTTP call -- " + method + " " + ACCESS_TOKEN_ENDPOINT_URL);
httpClient.executeMethod(httpMethod);
Thanks,
Hemant
I've tested the following slight modification of your code and it works. You might double check that
Your key has been approved (this shouldn't be the problem given the
error you are seeing).
You are using the correct ACCESS_TOKEN_ENDPOINT_URL
Try having the redirect_uri be the same for both the auth_code response and the token request
String method = "POST";
String authCode = "[AUTH-CODE-HERE]";
String CONSUMER_KEY="[YOUR-KEY-HERE]";
String CONSUMER_SECRET="[YOUR-SECRET-HERE]";
String ACCESS_TOKEN_ENDPOINT_URL="https://api.cx.com/1/oauth/token";
String REDIRECT_URI="[YOUR-REDIRECT-HERE]";
NameValuePair[] data = {
new NameValuePair("grant_type", "authorization_code"),
new NameValuePair("code", authCode),
new NameValuePair("redirect_uri", REDIRECT_URI)
};
String secret = CONSUMER_KEY+":"+CONSUMER_SECRET;
String encodedSecret = Base64.encodeBase64String(secret.getBytes("UTF-8"));
PostMethod httpMethod = new PostMethod(ACCESS_TOKEN_ENDPOINT_URL);
httpMethod.addRequestHeader("Authorization","Basic "+encodedSecret);
httpMethod.setRequestBody(data);
System.out.println("HTTP call -- " + method + " " + ACCESS_TOKEN_ENDPOINT_URL);
int responseCode = httpClient.executeMethod(httpMethod);
System.out.println(responseCode);
System.out.println(httpMethod.getResponseBodyAsString());
If you are still running into issues, can you post the result of the following line: System.out.println(httpMethod.getResponseBodyAsString());
The CX developer API has been discontinued.
Sorry for the inconvenience.

Updating issue with JIRA rest api 4.4

I am trying to update the fixVersion of an issue via the JIRA rest api. The JIRA version is 4.4.3#663-r165197. It is the instance hosted by codehaus, not sure if that makes a difference or not.
The request looks like:
curl -u [username]:[password] -X PUT -H 'Content-type: application/json' \
-d "http://jira.codehaus.org/rest/api/latest/issue/GEOS-[id]"
{
"update":{
"fixVersions":[
{
"set":[
{
"name":"2.2-beta3"
}
]
}
]
}
}
But I get back a 405, method not allowed error. Which makes sense if I look at the rest api docs for that version [1]. They seem to indicate there is no way to update an issue in this manner. BUt if I look at the docs for the latest version [2] they seem to indicate it is possible.
So I guess the question is how do I update an issue in this manner in JIRA 4.4? Or is it not possible?
Thanks!
[1] https://developer.atlassian.com/static/rest/jira/4.4.1.html#id151460
[2] http://docs.atlassian.com/jira/REST/latest/#id165544
For 4.4 you have to use the SOAP updateIssue method. 5.0 fixed this.
Prepare Json data as below(Here java as technology i had used), and pass using put method/API.
public static String generateJson(String customFieldId, Object value,
String attribute) {
if (isBlankOrNull(attribute)) {
return "\"" + customFieldId + "\":" + "\"" + value + "\"";
} else {
return "\"" + customFieldId + "\":{\"" + attribute + "\":\"" + ""
+ value + "\"}";
}
}
public static int invokePutMethod(String auth, String url, String data) {
int statusCode = 0;
try {
Client client = Client.create();
WebResource webResource = client.resource(url);
ClientResponse response = webResource
.header("Authorization", "Basic " + auth)
.type("application/json").accept("application/json")
.put(ClientResponse.class, data);
statusCode = response.getStatus();
return statusCode;
} catch (Exception e) {
Constants.ERROR.info(Level.INFO, e);
// vjErrorLog.info(Level.INFO, e);
}
return statusCode;
}
attribute could be key, id, name, value etc,
In case of fix version or components, you may have one more way to prepare json data
return "\"" + customFieldId + "\":[{\"set\" :[{ \"" + attribute
+ "\" :" + "\"" + data + "\"}]}]";
and invoke put method with above json data.

Resources