JavaScript pCloud API call to fetch userinfo gives an error - javascript

While calling the api from JavaScript
This HTTP request works fine https://api.pcloud.com/userinfo?username=xxxx#gmail.com&password=xxxx
In the below code I want to call via JavaScript
var user='email loggin';
var password='password of pcloud';
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "https://api.pcloud.com/userinfo",
dataType: 'json',
async: false,
data: '{}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', make_base_auth(username, password));
},
success: function (){
alert('Working Fine');
}
});
output in console
XMLHttpRequest cannot load https://api.pcloud.com/userinfo?{}. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
If someone can provide a solution or enhance the code.

Pass the username and password in the data field and remove the "beforeSend" part. For more information and examples, you can check out the pCloud Javascript SDK: https://github.com/pCloud/pcloud-sdk-js
Here is working example (a bit shorter):
$.getJSON("https://api.pcloud.com/userinfo", {
username: "***",
password: "***"
}, function() {
alert("working fine");
});

Related

Calling Mirth 'client api' services from jquery

I have a .Net website, hosted on an intranet web server. On the .Net site I have a basic jquery ajax call to our mirth machine. I'm trying to hit the client apis that are provided with the base install of mirth.
We are running mirth 3.9.1, with a default mirth.properties page, so the CORS settings should be correct.
I've tried a variety of settings in mirth.properties (and restarted mcservice between changes) and a variety of $.ajax settings, but cannot seem to find the right mix.
According to this answer: (https://stackoverflow.com/a/47096927/505829), I should be able to use basic authentication, but even if I have to make two calls, I'm ok with that, I just need something that works. Though one call would be preferred.
Here is the ajax call
$.ajax
({
type: "GET",
url: "https://ngmaintst01:8443/api/channels",
dataType: 'json',
// username: username,
// password: password,
// crossDomain: true,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));
},
xhrFields: {
withCredentials: true
},
// headers: {
// "Authorization": "Basic " + btoa(username + ":" + password)
// },
success: function () {
alert('success');
}
});
Here is the mirth properties:
# CORS headers
server.api.accesscontrolalloworigin = *
server.api.accesscontrolallowcredentials = false
server.api.accesscontrolallowmethods = GET, POST, DELETE, PUT
server.api.accesscontrolallowheaders = Content-Type
server.api.accesscontrolexposeheaders =
server.api.accesscontrolmaxage =
If I take the one call aproach, illistrated above, in chromes dev console I get:
(failed)net::ERR_FAILED
If I take a two call approach (below), the first call is successful (code 200), and the second gets the same error as the single call approach '(failed)net::ERR_FAILED', This time it appears the second call does NOT go out with the cookie session data, which is why a single call approach may be ideal.
$.ajax({
type: 'POST',
url: 'https://' + APPLIANCE+':8443/api/users/_login',
contentType: 'application/x-www-form-urlencoded',
dataType: 'xml',
data: { username: username, password: password },
success: function (data, textStatus, jqXHR) {
//alert(textStatus);
$.ajax({
type: 'GET',
url: 'https://' + APPLIANCE + ':8443/api/channels/' + channelid + '/statistics',
dataType: 'xml',
crossDomain: true,
xhrFields: { withCredentials: true },
//data: data,
//success: function(data, textStatus, jqXHR){ alert(textStatus); },
//error: function(jqXHR, textStatus, errorThrown){ alert(textStatus);}
});
},
error: function (jqXHR, textStatus, errorThrown) { alert(textStatus); }
});
I was able to get this working with some help from the mirth folks on slack. There is a "problem" in that, as far as I know, it will only support one web server. So I either need to have both my test and prod site on this one server, or no test.
Alternatively, I will just use a proxy back end service to circumvent cors altogether. So my local js will call my local proxy server, and forward the request on to mirths api.
Still, for posterity, here is how to get cors to work.
(One possible feature for mirth to implement would be dynamic accesscontrolalloworigin, where you provide an 'access list' of domains, and so long as the request is coming from one of those domains, it spits out, dynamically, that servers name. This would enable me to have multiple servers calling these apis. ala Access-Control-Allow-Origin Multiple Origin Domains?)
# CORS headers
server.api.accesscontrolalloworigin = https://MyDomainServer
server.api.accesscontrolallowcredentials = true
server.api.accesscontrolallowmethods = GET,HEAD,OPTIONS,POST,PUT
server.api.accesscontrolallowheaders = Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization
server.api.accesscontrolexposeheaders =
server.api.accesscontrolmaxage =
$.ajax
({
type: "GET",
url: "https://MirthAppliance:8443/api/channels",
dataType: 'json',
xhrFields: {
withCredentials: true
},
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
success: function () {
//alert('success');
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
// alert('Error - ' + errorMessage);
}
});

JavaScript slack api jquery

My question is very simple and I thought creating this program would only take a couple hours. However now I have been working on it all day trying to figure out what I could be doing wrong.
All I am trying to do is post messages to slack using their postMessage api. I have been able to send messages succesfully using slacks testing methods.
This is the url that is outputted by the test
https://slack.com/api/chat.postMessage?token=xoxp-xxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxxxxx&channel=XXXXXXXX&text=Just%20need%20the%20url&as_user=jheuman&pretty=1
I then decided to try it out locally using this html file served from my file system
<!DOCTYPE html>
<html>
<head>
<title>Testing Slack API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<button onClick="test()">Test</button>
<button onClick="test2()">Authorization Test</button>
<script>
function test() {
var apiUrl = "https://slack.com/api/chat.postMessage";
var token = "xoxp-xxxxx...";//my token has been omitted for security;
var channel = "#general";
var text = "Testing slack api";
var user = "jheuman";
var actualToken = "Bearer " + token;
$.ajax({
headers: {
'Authorization':actualToken,
'Content-Type':'application/json'
},
data: JSON.stringify({
"channel": channel,
"text": text,
"as_user": user
}),
dataType: 'json',
processData: false,
type: 'POST',
url: apiUrl
})
.done(function(data) {
console.log(JSON.stringify(data));
})
.fail(function(response) {
console.log(JSON.stringify(response));
});
};
function test2() {
var apiUrl = "https://slack.com/api/auth.test";
var token = "xoxp-xxxxx..."; //my token has been omitted for security
var channel = "#general";
var text = "Testing slack api";
var user = "jheuman";
var actualToken = "Bearer" + token;
$.ajax({
headers: {
'Authorization':actualToken
},
type: 'POST',
url: apiUrl,
})
.done(function(data) {
console.log(JSON.stringify(data));
})
.fail(function(response) {
console.log(JSON.stringify(response));
});
};
</script>
But when I click either button I get the following error:
Failed to load https://slack.com/api/chat.postMessage: Request header field
Authorization is not allowed by Access-Control-Allow-Headers in preflight
response.
So per a friends Suggestion I tried it out on a server. I used Web Server For Chrome to serve it up on port 8887. First without setting cors headers and then with setting cors headers. Both to no avail. I received the same error.
As you can see I also tried the auth.test call but I receive the same error.
Slack specifically states that they prefer an authorization header and that the api can handle json data.
Other things I have tried:
Having no header field with token in data:
data: JSON.stringify({
'token':actualToken,
'channel': channel,
'text': text,
'as_user': user
}),
dataType: 'json',
processData: false,
type: 'POST',
url: apiUrl
Errors received:
{"ok":false,"error":"invalid_form_data"}
Having no header field with token in data without 'Bearer':
data: JSON.stringify({
'token':token,
'channel': channel,
'text': text,
'as_user': user
}),
dataType: 'json',
processData: false,
type: 'POST',
url: apiUrl
Errors received:
{"ok":false,"error":"invalid_form_data"}
Things I have looked into but don't think will effect outcome
The type of token
So how do I get this post request to work?
I am not set on jquery or ajax, it is just what I have used in the past so if you have a different request library to use I'm all ears.
If you need more information I will try to give it to you
Since configuring CORS correctly for sending data with content-type application/json can be tricky, I would suggest to send the request as application/x-www-form-urlencoded which is the default for AJAX.
Example:
var apiUrl = "https://slack.com/api/chat.postMessage";
var token = MY_TOKEN;
var channel = "general";
var text = "Testing slack api";
var user = "jheuman";
$.ajax({
data: {
"token": token,
"channel": channel,
"text": text,
"as_user": user
},
dataType: 'text',
type: 'POST',
url: apiUrl,
error: function(xhr,status,error){
console.log("error: " + error);
},
success: function(data) {
console.log("result: " + data);
}
});
In case you get CORS errors, you can add crossDomain: true
This solution is tested and works when run in a normal browser.
You need to reply to that CORS preflight with the appropriate CORS headers to make this work. One of which is indeed Access-Control-Allow-Headers. That header needs to contain the same values the Access-Control-Request-Headers header contained (or more).
https://fetch.spec.whatwg.org/#http-cors-protocol explains this setup in more detail.
headers: {
'Authorization':actualToken,
'Content-Type':'application/json',
'Access-Control-Allow-Headers':'x-requested-with'
},

Sending External Parameters in json to pass onto to the api via webhook in dialogflow

I am calling an AJAX post request on /query endpoint of dialogflow and I want to send some parameters from the localStorage of the javascript.
var baseUrl = “https: //api.dialogflow.com/v1/query?v=20150910”
$("#spokenResponse").addClass(“is - active”).find(".spoken-response__text").html(output);
$.ajax({
type: “POST”,
url: baseUrl + “query”,
contentType: “application / json;charset = utf - 8”,
dataType: “json”,
headers: {“
Authorization”: "Bearer " + accessToken
},
data: JSON.stringify({
query: text,
lang: “en”,
sessionId: sessid.toString()
}),
success: function(data) {
prepareResponse(data);
},
error: function() {
respond(messageInternalError);
}
});
Please help me on how to send custom parameters in the request like say city or some id I got from the page. Thank you.

Connecting tfs api using javascript

I've done a new database with a user interface (with Javascript code) and Iam trying to connect the UI with TFS API to get some informations and save it in my Databas
but i have challenge in establishing this connectioin with Javascript
can anyone help me please??
If you want to do this via a javascript client, you could use the invoke as follows:
var self = this;
self.tasksURI = 'https://<SERVER>/tfs/<COLLECTION>/<PROJECT>/_apis/build/builds?api-version=2.0';
self.username = "<USERNAME>"; //basic username so no domain here.
self.password = "<PASSWORD>";
self.ajax = function (uri, method, data) {
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(data),
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(self.username + ":" + self.password));
},
error: function (jqXHR) {
console.log("ajax error " + jqXHR.status);
}
};
return $.ajax(request);
}
self.ajax(self.tasksURI, 'GET').done(function (data) {
alert(data);
});
More details please refer this similar question in SO: TFS 2015 REST API Authentication

Logging into Rails 3 app (using Devise for authentication) using ajax on a separate website

So, I have a rails 3 application using Devise to handle authentication. I have another website (all client side javascript) that is trying to log into this rails 3 app using ajax basic authentication, like so:
username = "test#testing.com"
password = "testing"
$.ajax({
'url': '/users/sign_in',
'otherSettings': 'othervalues',
'beforeSend': function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password))
},
sucess: function(result) {
alert('done');
}//sicc
});
It hits the route correctly, and I can see that everything looks a-okay on the rails side (the server even thinks it's redirecting), but if I then try to hit a route (using jquery, to load json data) that requires authentication, I get that ugly basic auth javascript pop up telling me I need to authenticate.
Devise obviously doesn't use cookies to store auth data, and from my understanding you can't just access the HttpSession from javascript...is there ANYTHING I can do, or will I just have to use authentication tokens (and write a custom controller to return this to me).
EDIT:
Even a post with basic auth doesn't work, and THAT is weird ('cause in retrospect, yes, it's a post route i'm trying to get to). I get a 401 Unauthenticated error... Why would you need to be authenticated to authenticate? Having type be 'GET" works just fine, though, but (again, in retrospect) is hitting the 'new' route rather than 'create'.
username = "test#testing.com"
password = "testing"
$.ajax({
'url': '/users/sign_in',
'type': 'POST',
'otherSettings': 'othervalues',
'beforeSend': function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password))
},
sucess: function(result) {
alert('done');
}//sicc
});
EDIT: Just to confirm, it doesn't seem to be a problem with the "protect_from_forgery" line in the application controller, either...at least, when I comment it out, I still have the same problem.
Nevermind, the problem seems to have been that when I was posting with basic auth, I had a typo in the username, and apparently the way authentication failure is handled is by popping up the basic auth dialogs (very ungraceful, btw)
Solution:
username = "test#testing.com"
password = "testing"
$.ajax({
'url': '/users/sign_in',
'type': 'POST',
'otherSettings': 'othervalues',
'beforeSend': function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password))
},
sucess: function(result) {
alert('done');
}//sicc
});
Is there any reason you cannot send the username and password in the POST data?
var username = "test#testing.com";
var password = "testing";
$.ajax({
url: '/users/sign_in',
type: 'post',
data: 'username=' + username + '&password=' + password
success: function(result) {
alert('done');
}//sicc
});
First do setup.
In /config/initializers/devise.rb
Set config.http_authenticatable = true
This will allow you to authenticate via HTTP
Set config.http_authenticatable_on_xhr = true (Should be true by default)
Now restart
Now for Sign_in:
username = "a#a.com";
password = "b";
$.ajax({
'url': '/users/sign_in',
'type': 'POST',
'otherSettings': 'othervalues',
'beforeSend': function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password))
},
sucess: function(result) {
alert('done');
}
});
And for Sign out:
$.ajax({
'url': '/providers/sign_out',
'type': 'DELETE',
'otherSettings': 'othervalues',
sucess: function(result) {
alert('done');
}
});

Categories

Resources