I have an API that I am able to authenticate against using the Postman client. Using Postman I am able to enter in my username and password into the header and receive back an access token.
I would like to accomplish the same authentication with a simple HTML page using Javascript. However, I am unsure how to craft the Javascript request and pass in my username and password as I did with Postman.
A password is normally considered private, if you include it in your javascript anyone can read it and fire requests off to the API as your user.
Additionally, the browsers same-origin policy - unless configured otherwise will stop you firing ajax requests to a domain other than the one the webpage was loaded from.
Instead you should create a proxy script in the server-side language of your choice hosted on your domain and fire your ajax requests off to this.
This script would do the relevant actions with the API keeping your credentials a secret and return the response.
Under the address bar of Postman there's a link that says "Generate Code" on previous versions it was a button with a </> symbol.
Clicking that link opens up a popup with a dropdownlist where Javascript is one option, this will generate the code to do the request.
Let me also add to the other answers that with jQuery you can do a get request with $.get(), and a post request with $.post(). But I would do what Vector suggests and generate the JavaScript with Postman.
You could do that with ajax call within a javascript file and you can aslo do with the xhttprequest .
example of ajax call:
$.ajax({
url : url, //URL
type : 'POST', // The HTTP Method
data : array,
contentType : 'application/json',
cache : false,
success : function (data) {
},
error : function (err) {
});
In this you can also add the Headers where u can your api access token
Related
I have a webpage consisting of HTML/CSS/JS/JQUERY on server 1.
On server 2, I have a PHP file to avoid cors.
So, I make requests from server 1 to server 2. The PHP code then uses cURL to interact with API I am working with.
This API sends back cookies, which I want to forward back to server 1 ( the website).
I've been searching for a while, but I have no idea how to go about doing this?
I'm guessing it has to do with something to catch the response headers?
Any help would be nice! I'm new to PHP.
Heres more info:
// Here is how I am calling the server 2 file.
$.ajax({
URL:"HTTP://localhost......server.php",
type:"post",
data: $(this).serialize(),
success: .....,
});
Is there any way I can just get the headers in this file regularly?
Eg. Make it automatically set the cookies here?
If I understand this question correctly. You are hosting a website, and the website makes a request to a PHP script that in turn calls an API that returns some set-cookie headers.
For the cookies to be passed on to the client viewing the website, you'd need to extract the cookie values and call PHPs setcookie function before returning the response to the client from PHP.
Most frameworks will provide a mechanism to specify the header for the response to the client and provide the ability to set a cookie.
Based on your update:
// Here is how I am calling the server 2 file.
$.ajax({
URL:"HTTP://localhost......server.php",
type:"post",
data: $(this).serialize(),
success: .....,
});
So you have some JS that is making a request to the "server 2" file. This "server 2" file should be able to extract the values from the response to the curl call it is making and return set-cookie headers to the client. The client will then store those cookies and could provide them on subsequent requests to http://localhost, for how long, for what paths etc are configurable as part of the process for creating the cookie.
Might be worth posting more code, or making it clearer what you aim is with this as there may be a better solution outside of extracting cookie data from the curl call and passing back to the client.
I have a cms, where am using laravel as web api, angularjs for requests.
I have an iframe where I call to services with a direct link and put it usig trusted src function.
The main problem is, I can not use a normal http post request and hide parameters, because using http request will return data, not file, and the report api returns in headers, an html file, pdf ... etc) so when i get result to the success of my http request, it won't download pdf file, it will show special chars
in the i frame am calling the api like this :
"localhost/api/getreportService/"+$scope.brandid+"&"+$scope.customerid"
but that's cannot be secure, is there any way to hide the request here from users?
ok, I found a solution, I called the api via http post request then I used $sce tustAsHtml for the response, with a ng-bind-html in my template and the result is good now, the report is showing in the div,
Now all is safe, the user needs a token to access the report, and that's impossible without a login.
In short, I have a Pharbicator setup on a domain A, but then I have to implement a service on domain B which relies on the Pharbicator.
So this is the story, I am trying to gather information using the Phabricator Conduit user.whoami API to see whether the current user is logged in. But due to various reasons I couldn't make it. I would like to know what is the correct way of doing so.
I have tried three methods but they all did not work. Here is what I tried
Method 1: Using Ajax Request
What I did is just to fire an POST Ajax request with the api token
$.ajax({
url: 'http://127.0.0.1:8080/api/user.whoami',
method: 'POST',
cache: false,
data: 'api-token='+app.PHABRICATOR_APIKEY
}).done(function(response) {
console.dir(response);
}).fail(function(jqXHR, textStatus) {
console.log(textStatus);
});
This method does not work (as expected) because it is a CORS request, and the Phabricator server does not have Access-Control-Allow-Origin header.
Although I can add that Access-Control-Allow-Origin header, but somehow this requires modifying the Phabricator source code so I would consider this as the last solution I would do.
Method 2: Using a PHP as proxy and inside use curl to request for it. So the whole request will be like Client Browser <-> PHP Proxy Script <-> Phabricator
This method is actually able to send the request and get response. But the information is wrong as it returns only the user of the API key.
If I understand it correctly, the curl is not having my browser session, so there is no way for it to really know who I (the browser client) am in Pharbricator. So I assume then the API will just fallback to use the information of API key and thus return information not I intended.
Method 3: Using the PHP library __phutil_library_init__.php provide by Phabricator
require_once '/var/www/html/phabricator/libphutil/src/__phutil_library_init__.php';
$api_token = PHABRICATOR_APIKEY;
$api_parameters = array();
$client = new ConduitClient('http://127.0.0.1:8080/');
$client->setConduitToken($api_token);
$result = $client->callMethodSynchronous('user.whoami', $api_parameters);
return $result;
Again this is nothing special, just a direct copy of code from the documentation. But again it is returning only the user the API key belongs to. And I think it is just the same as what method 2 is behaving.
I am thinking if I am understand the Conduit API in a wrong way. And more importantly I would like to know how I should implement the whole architecture so that it can gather information using the current browser session. Thank you.
I'm using basic authentication to secure a set of WCF web services exposed only inside our corporate network, and I was wondering if there was a way to trigger the browser's credentials dialog to appear from an AJAX call when the web service returns with a 401 error?
Currently my AJAX call receives the 401 as a regular failed request and doesn't prompt the browser to do anything. However, if I take the same URI and copy-paste it into into the browser's URL bar, the returned 401 correctly triggers the Basic Authentication dialog.
Is there any way to get the AJAX callback to tell the browser to pop up that dialog?
Dynamically create an iframe with your url and append to document. It'll trigger authentication form. jQuery snipet to add iframe
$('<iframe src="your_url"></iframe>').appendTo('body')
A very simplified example is here:
var url = 'your_url_here';
$.ajax({
url: url,
error: function(response){
if(response.status==401){
$('<iframe src="'+url+'"></iframe>').appendTo('body');
}
},
success:function(){
//your success code here
}
});
I have faced almost the same 401 problem, except for my request was cross domain. But I hope the reason is the same. Following the instructions on developer.mozilla - Access control CORS I have finally succeeded with simple:
var xhttp=new XMLHttpRequest();
xhttp.withCredentials = true;
xhttp.open("GET", "https://my.foo.server/app/resource", true);
xhttp.send();
I think the xhttp.withCredentials is the solution. It is not header! You let browser to communicate with server through cookies. The following answer explains a lot XHR2 withCredentials - which cookies are sent?
Without xhttp.withCredentials there was always 401 (Unauthorized). But using it, the browser added the required header Authorization:Basic dGVFooFooFooFoosaWVudA== or triggered the login dialog, when credentials were not available yet.
You can't, you'll need to provide the request with the credentials.
See How to use Basic Auth with jQuery and AJAX?
You would suggest to open/display/insert a form to allow inserting username and password and than resend the AJAX Request with the given credentials. I wouldn't really on browsers credential popup.
How you set authentication header you can read here: How to use Basic Auth with jQuery and AJAX?
Yes, you can invoke it from AJAX. Just pass the request with the following header:
withCredentials: true
As found somewhere in the stack :
Receiving a 401 response is the server telling you, “you aren’t
authenticated–either not authenticated at all or authenticated
incorrectly–but please reauthenticate and try again.” To help you out,
it will always include a WWW-Authenticate header that describes how to
authenticate
Use jQuery's beforeSend callback to add an HTTP header with the authentication information
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
Do you meet the conditions highlighted in this SO answer?
Also based on in this other answer you may want to check that the headers returned from your backend are the same whether you request it from the browser or from an AJAX call.
you could just trigger a redirect when you check for the 401 condition:
window.location = "https://example.com"
I'm trying to get data from an API with javascript but i'm getting an error on the request.
$.ajax({
dataType: "jsonp",
url: "https://www.bitstamp.net/api/ticker/",
type: "GET",
succes: myfunction
});
result:
{"error": "GET parameters not allowed for this request."}
I use Jsonp because its another domain.
Why can't I get the data with Jquery?
If I just browse to the link I can see the Json.
I just tried getting data from the url you provided using AJAX. The server did not return any data using the $.ajax and this clearly shows that the server does not support cross domain requests. That is why I asked you if you had access to code because you have to manually specify if you want API to support cross domain requests.
One way around to this is using some server side language to access this API. I once had similar problem and the used PHP CURL to access the API. The php code then served data to JQuery to be used on frontend. So you can write relay code to solve this problem.
Because, as the error message says, bitstamp do not allow it.
If they get a JSONP request for the data, they respond with the error instead of the normal response.