How to pass Authorization header in reactjs API call? - javascript

module.exports ={
_callAPI: function(url,method,data,target){
let token = "santhi" + ":" + "santhi";
let hash = btoa(token);
console.log(hash);
$.ajax({
url: BASEURL + url,
method: method,
data: data,
processData: true,
dataType: 'json',
headers: {
"Authorization" :"Basic " + hash,
"Content-Type" :"application/json"
},
success: (data,textStatus, jqXHR) => {
target('success', data);
},
error: (jqXhr,textStatus,error) => {
target('error',jqXhr,textStatus,error);
}
});
},
}
I am adding authorization as headers like thing. but i am not getting anything. Is there any other way to authorize base64 encoding.
Thanks in advance

Related

How to get oauth access_token with jQuery (localhost)?

I am trying to get access_token utilizing jQuery. Problem is, that I cannot get that token (server is running on localhost). Server works fine (I tried that with postman), but I cannot get it with jQuery.
Browser writes after clicking on the button.
The resource from “http://localhost:8080/oauth/token?callback=jQuery34105901959820360243_1562175129954&grant_type=password&client_id=my-client&client_secret=my-secret&username=test%40seznam.cz&password=Peter&_=1562175129955” was blocked due to MIME type (“application/json”) mismatch (X-Content-Type-Options: nosniff).
jQuery function to get access_token
function authenticateUser(email, password) {
var body = {
grant_type: 'password',
client_id: 'my-client',
client_secret: 'my-secret',
username: "test#seznam.cz",
password: "Peter"
};
$.ajax({
url: 'http://localhost:8080/oauth/token',
crossDomain: true,
type: 'POST',
dataType: 'jsonp',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
header: {"Access-Control-Allow-Origin": "*"},
data: body,
complete: function(result) {
alert(result);
},
success: function(result) {
alert(result + " OK!");
},
error: function(result) {
alert(result + " CHYBA");
},
});
return true;
}
If the javascript file is served by the same server that gives out the tokens then there's no need to use the full url in your jquery ajax code (and there's no need to indicate crossDomain=true). It also seems that your server is expecting json content type instead of url-encoded
use
url: '/oauth/token',
crossDomain: false,
...
contentType: 'application/json; charset=UTF-8',
To make the request
Edit
Trye this way:
$.post("/oauth/token",body,
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
Hope this helps

New TwitchTV API call

I am a beginner to programming and for a challenge I need to get the status (Streaming live/Off-line) for a given number of channels.
I wrote an ajax request but I am still getting 401 as a response. Below my code and a screen shot of the response.
I have even made the token request as async: falseto make sure the token is back before triggering the API call
$("document").ready(function() {
var aoathToken = $.ajax({
type: "POST",
url: "https://id.twitch.tv/oauth2/token?client_id=MYCLIENTID&client_secret=MYSECRET&grant_type=client_credentials",
error: function() {
console.log("Check your request!!")
},
success: function(token) {
console.log(token);
}
})
$.ajax({
type: "GET",
url: "https://api.twitch.tv/helix/streams?user_id=freecodecamp",
contentType: ('application/x-www-form-urlencoded; charset=UTF-8'),
crossDomain: true,
header: {
"Access-Control-Allow-Origin": "*",
"Client-ID": "MY CLIENT ID",
"Authorization": "Bearer " + aoathToken,
},
data: {"user_login": "myUserID"},
dataType: "json",
success: function(json) {
console.log(JSON.stringify(json, null, 2));
},
error: function(json) {
window.alert(json.status + " " + json.message);
},
})

how to send api_key and api_secret arguments in jquery post request

$.ajax({
type: 'POST',
url: 'http://apius.faceplusplus.com/detection/detect',
crossDomain: true,
cache: false,
async: true,
data: '{ "comment" }',
dataType: 'jsonp',
success: function(responseData) {
alert(JSON.stringify(responseData));
},
error: function (responseData, textStatus, errorThrown) {
alert(JSON.stringify(responseData));
}
});
I am sending a post request to above which requires api_key and api_secret parameters for authentication. I tried sending value of this 2 paramenters like this in above request:
headers:
{
"Authorization": "Basic " + Base64.encode('value of api key here' + ":" + 'value of api secret here')
},
But when I execute the request it says 400 BAD REQUEST and when I hit the url in browser it shows
{
"error": "MISSING_ARGUMENTS: api_key",
"error_code": 1004
}
Please suggest me a solution. I am stuck for long time.
Pass the key/value pairs in the data object of the ajax request, like this:
data: '{ "api_key": "thekeyhere", "api_secret": "thesecrethere" }'

how to get access token from bitly using password and username?

$.ajax({
url: 'https://api-ssl.bitly.com/oauth/access_token',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
data: { Authorization: "Basic " + btoa('myusername' + ":" + 'mypassword#123') },
success: function (result) {
console.log(result);
},
error: function () {
alert("Cannot get data");
}
});
I am trying to get access token from bitly api by providing username and password but it is showing invalid_client_authorization error. Does any one have idea on the same?
Bitly documentation : http://dev.bitly.com/authentication.html#resource_owner_credentials
You are concatenating your username with your authorization header.
Your authorization and content-type should go in the headers object.
There is no 'type' property on jquery ajax method, you probably meant 'method'.
Also, you can't send both dataType:'json' and set the content-type to 'application/x-www-form-urlencoded'
$.ajax({
url: 'https://api-ssl.bitly.com/oauth/access_token',
methdo: 'POST',
contentType: '',
dataType: 'json',
headers: {
'Authorization' : 'Basic ' + [INSERT YOUR HASH HERE],
'Content-Type' : 'application/x-www-form-urlencoded',
}
data: { $.serialize({
username: YOURUSERNAME,
password: YOURPASSWORD
})},
success: function (result) {
console.log(result);
},
error: function () {
alert("Cannot get data");
}
});
This should do it
Fixed #goncalomarques answer:
Removed top level "contentType" and "dataType"
Removed data object (otherwise username and password is sent as clear text, in addition to the hashed username and password in the header)
renamed "methdo" to "method"
Explicitly used btoa() to get Base 64 encoded hash (be aware, does not work in older IE versions)
$.ajax({
url: 'https://api-ssl.bitly.com/oauth/access_token',
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa(YOURUSERNAME + ':' + YOURPASSWORD),
'Content-Type': 'application/x-www-form-urlencoded',
},
success: function(result) {
console.log("success");
console.log(result);
},
error: function(response) {
console.log("Cannot get data");
console.log(response);
}
});
Note:
I have this example working, but was unable to get it working with the built-in Stackoverflow editor ("Run snippet") due to cross origin exceptions.

jQuery JSONP ajax, authentication header not being set

I'm trying to make an ajax request to the google contacts API with the following setup:
$.ajax({
url: "https://www-opensocial.googleusercontent.com/api/people/#me/#all",
dataType: 'jsonp',
data: {
alt: 'json-in-script'
},
headers: {
'Authorization': 'Bearer ' + token
},
success: function(data, status) {
return console.log("The returned data", data);
}
});
But the Authentication header doesn't seem to get set. Any ideas?
I had the same problem recently. Try this:
$.ajax({
url: "https://www-opensocial.googleusercontent.com/api/people/#me/#all",
dataType: 'jsonp',
data: {
alt: 'json-in-script'
},
success: function(data, status) {
return console.log("The returned data", data);
},
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer ' + token); }
});
EDIT: Looks like it can't be done with JSONP. Modify HTTP Headers for a JSONP request
When authentication is needed in a cross domain request, you must use a proxy server of some sort.
Since using dataType: jsonp results in the HTTP request actually being made from the script that gets added to the DOM, the headers set in the $.ajax will not be used.
Is seems that most of the OAUTH2 REST resources accept the access_token parameter as part of the request url
http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#query-param
please, try the following code instead:
$.ajax({
dataType: 'jsonp',
url: url,
data: {
'access_token':token.access_token
},
jsonpCallback: 'thecallback',
success: function(data){
_cb(data);
},
error: function(d){
_cb(d);
}
});
Just do this (jquery 2.0, but should work in previous versions)
$.ajax({
url: "/test",
headers: {"Authorization": "Bearer " + $('#myToken').val()}
})
.done(function (data) {
console.log(data);
})
.fail(function (jqXHR, textStatus) {
alert("error: " + textStatus);
});

Categories