I am requesting a video from an API that requires JWT web tokens:
// when the ajax call is done (the tolken is recieved )
getAccessToken.done(function(data) {
var d = JSON.stringify({'fpath': fpath})
// get the download url
var downloadurl = $.ajax({
type: "POST",
url: "https://gcp.inbcu.com/download",
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "JWT " + data.access_token);
},
contentType: 'application/json',
data: d,
success: function(response){
$('#video-source').attr('src', response.url)
$('#myvideo').load()
},
error:function(jqXHR, textStatus, errorThrown) {
console.log("request for download url failed: ", textStatus, errorThrown, jqXHR);
},
dataType: 'json'
});
This ajax call itself is successful (200) and returns the proper values. Mainly it returns a url to set the source of the video.
Problem is, the video src attempts to access the url and doesn't have permission (no jwt token/ authorization). How am I supposed to load the video with the proper permission when loading the src of a video? Is this possible?
As the answer to a similar question explains, this isn't possible. Either you need to do it as an AJAX request, which you previously did, but which was slow, or, you need to add additional methods for the server to accept authentication.
Regarding these auth options, you could add a session cookie that the server can check, or append the token to the video url, like response.url + '?token=' + token.
A service worker would be capitabel of adding the auth token. But that only solves the problem for FF & Blink
Related
I am having some trouble getting a few things working. I am trying to connect through basic authentication. I am using javascript in my HTML code. I get the following error message: " Failed to load http://**********/connections?********* : Response for preflight is invalid (redirect)" where I have redacted the API endpoint. The code I wrote is the following.
var Key = "something";
var Secret = "something else";
var url = 'http://**********';
$.ajax({
headers: {
'X-******-Key':Key,
'X-**********Secret':Secret,
'Content-Type':'application/x-www-form-urlencoded'
},
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(json) {
alert("Success", json);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(Key + ":" + Secret));
},
type: 'GET',
contentType: 'json',
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
hi
</html>
You can substitute the API end points and secret and Key to try the code for a common basic authentication API to try the code. I don't have access to the Server. I know it is still possible to make this work because someone else said they have this working. Can anyone help me with this?
Response for preflight is invalid (redirect)
Your server doesn't handle CORS properly.
Browsers won't let fetch data via ajax if the request is made to an external domain unless the server handles CORS properly and CORS headers are available in the responses.
Please read the article:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Here is the link to the Web API notes on how to create a new playlist. https://developer.spotify.com/web-api/create-playlist/
As far as I understand, the POST requests the url https://api.spotify.com/v1/users/{user_id}/playlists. This is requested while passing the access token and data. The content type of the data being 'application/json'.
For some reason this is failing and returning a Error 403 (Forbidden) in the console.
Anything I'm missing?
//(playlistName, userId, accessToken) are passed to this.
var urlString = 'https://api.spotify.com/v1/users/' + userId + '/playlists';
var jsonData = {
"name": playlistName,
"public": false
};
$.ajax({
type: 'POST',
url: urlString,
data: jsonData,
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
},
contentType: 'application/json',
success: function(result) {
console.log('Woo! :)');
},
error: function() {
console.log('Error! :(');
}
})
Having tried your example, I get a 401 unauthorized when filling in bogus data. So you are authorized, but the API really does not grant you the rights (403 forbidden).
Please have a look at the authorization guide. I am pretty sure, your error is there. Especially have a look at scope. You might simply not grant enough power in the login. And therefore ending up with only public access, which does not include adding playlists.
I cite form the API docs:
To be able to create private playlists, the user must have granted the
playlist-modify-private scope.
https://developer.spotify.com/web-api/authorization-guide/
I have a problem. I have the Authorization header generated by OAuth Tool in Twitter (I hid value of keys)
Authorization: OAuth oauth_consumer_key="xxxxxxxxxxxxxxxx", oauth_nonce="xxxxxxxxxxxxxxxx", oauth_signature="xxxxxxxxxxxxxxx", oauth_signature_method="HMAC-SHA1", oauth_timestamp="xxxxxxxxx", oauth_version="1.0"
And I have a AJAX code:
$.ajax({
url: 'https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames&since_id=24012619984051000&max_id=250126199840518145&result_type=mixed&count=4',
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'OAuth oauth_consumer_key="xxxxxxxxxxxxxxx", oauth_nonce="xxxxxxxxxxxxxxx", oauth_signature="xxxxxxxxxxxxxxx", oauth_signature_method="HMAC-SHA1", oauth_timestamp="xxxxxxxxx", oauth_version="1.0"');
},
dataType: "jsonp",
success: function(data) {
console.log("Success: " + data);
}
},
error: function(data) {
console.log("Error " + data);
}
});
But this code returned error
Object {readyState: 4, status: 404, statusText: "error"}
Here is part of documentation Twitter REST API which I use:
https://dev.twitter.com/rest/reference/get/search/tweets
What is wrong? Any ideas?
Twitter does not support generating the authentication header from a webpage. You must go through the "handshake" using their site to authenticate and redirecting back to your webpage.
If you want to avoid this and keep your oauth keys locally, you will need to build a server which can authenticate using stored keys. Then your webpage will make Twitter requests via your server.
My problem is "simple". I'm developing a hybrid Android application that makes HTTP requests via Jquery Ajax.
The problem is that when my requests gets failed(Server returns 401/403 ...etc), Jquery fires only HTTP 404 error that is not correct.
I'm making HTTP post requests like that:
var request = $.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: obj,
cache: false,
contentType : 'application/json',
beforeSend : function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));
},
success: function(data){
// Success
},
error: function(request, status, errorThrown){
console.log("call Login ajax failed with error, status:" + status + " errorThrown:" + errorThrown);
console.log("call Login ajax failed with errorCode : " + request.status);
}
The strange thing is that when i run my project as DynamicWeb project in my browser at my PC and in the url use my ip address the jquery fires the correct error events, but when i use "localhost" in the url, the jquery act as in the android devices, fires only 404 event.
I tried to change jquery libary to a newest version 2.1.1 but this doesn't help.
PS. I'm using jquery 2.0.2...
You'll need to set the header of the response to Content-type: application/json.
Before you echo the json. Or you could set the type of the ajax call to text, html.
Also it is recommended to chain your callback functions with jquery like so
$.ajax({
url: url,
headers: { "Accept-Encoding" : "gzip" }, // Use the response seen in sniffer
type: 'POST',
dataType: 'json',//be sure you are receiving a valid json response or you'll get an error
})
.done(function(response) {
console.log("success");
console.log(response);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
The problem for me was that server doesn't allow Cross-domain requests. So i must set "Access-Control-Allow-Origin:", "*" header in responses from my server and everything will be ok...
On site1.domain.com I am running a greasemonkey script that takes in user credentials to authenticate to site2.domain.com and pull the entire page and parse out a server generated token that is needed to complete the rest of the script running on site1.domain.com and then make another URL GET to site2.domain.com.
xmlhttp.open("GET", url, false, username, password );
is the call I'm attempting but I'm receiving the error "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied". I looked around and I understand that there are complications with this type of functionality but I haven't figured out what I need to do in this situation.
EDIT: Tried this using verisons of the code below but receiving Cross-domain error for any datatype other than jsonp but with jsonp I recieve "htmlString is undefined". I also tried defining the return value as a String and in that case I received "6" (without any manipulation).
var htmlString = getPage(url,username, password);
var index = htmlString.indexOf("Token");
//some other code that parses out just the token, shown as "finalString" in the end
$("#logMessage").text (finalString);
function getPage(url, username, password) {
return $.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
async: false,
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', btoa(username + ":" + password));
}
}).responseText;
}