How to call Web API from ExtJS with token based authentication - javascript

Ext.Ajax.request({
url: 'Employee/Search',
method: 'POST',
headers: { "Content-Type":"application/json","Accept": "application/json","Authorization": "OAuth oauth_token=158ghhBtgf2586525hggfgdf" },
jsonData: {
"FirstName": txtFirstName.getValue()
},
success: function(response) {
},
failure: function(response) {
}
});
This is giving me 401 (Unauthorized Request)

I am using adal.js library by Microsoft, and using the following code:
window.acquireTokenCallback = function (error, token) {
if(error || !token) {
Ext.alert('ADALERROR', error || 'Token empty');
return;
}
// Apply token to all future Ajax requests.
Ext.Ajax.setDefaultHeaders({
'Authorization': 'Bearer ' + token,
'Accept': 'application/json'
});
// Load Settings from Server.
me.loadSettings();
};

Related

Getting 400 error status code on client_credentials Spotify API request

I'm dealing with Spotify's API but not succeed to automatically get a new access token.
function api() {
$.ajax({
type: 'POST',
url: 'https://accounts.spotify.com/api/token?grant_type=client_credentials',
headers: {
'Authorization': 'Basic myClientIdEncodedToBase64Format:myClientSecretEncodedToBase64Format'
},
success: function(data) {
console.log('Succes ->', data);
},
error: function(error) {
console.log('Error -> ', error);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm getting a 400 error. If [i refer the doc][1], '400: Bad Request - The request could not be understood by the server due to malformed syntax. The message body will contain more information'.
What am i doing wrong here ?
Thanks !
Here my code. I add data :
function api() {
$.ajax({
type: 'POST',
url: 'https://accounts.spotify.com/api/token',
data: 'grant_type=client_credentials',
headers: {
'Authorization': 'Basic myClientIdAndMyClientSecretConvertedToBase64'
},
success: function(data) {
console.log('Succes ->', data);
},
error: function(error) {
console.log('Error -> ', error);
}
});
}

How to create user in openfire using restapi in nodeJs application?

This is my function in NodeJs app which I am using to create user in openfire.
var createUser = function(objToSave, callback) {
const options = {
method: 'POST',
uri: url.resolve(Config.APP_CONSTANTS.CHAT_SERVER.DOMAIN_NAME, '/plugins/restapi/v1/users'),
headers: {
'User-Agent': 'Request-Promise',
'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: objToSave
}
request(options)
.then(function(response) {
callback(null, response);
})
.catch(function(error) {
// Deal with the error
console.log(error);
callback(error);
});
};
the objToSave is a json object contains username and password.
{
"Username": "gabbar",
"Password": "gabbar#123"
}
when i run this function i am getting the following error..
{
"statusCode": 400,
"error": "Bad Request"
}
I configured my secret-key properly and domain name is localhost://9090, can anybody tell me what I am doing wrong ? thanks in advance.
I think the options you provided needs JSON.stringify object before send it
The modified options is as below
const options = {
method: 'POST',
uri: url.resolve(Config.APP_CONSTANTS.CHAT_SERVER.DOMAIN_NAME, '/plugins/restapi/v1/users'),
headers: {
'User-Agent': 'Request-Promise',
'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: JSON.stringify(objToSave)
}
I find out that problem was with request-promise. it was not properly sending data in the required format. so Instead of that now I am using different module minimal-request-promise. and It worked like charm for me. After using that, my code looks something like this.
var requestPromise = require('minimal-request-promise');
var createUser = function(objToSave, callback) {
const options = {
headers: {
'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(objToSave)
};
requestPromise.post('http://localhost:9090/plugins/restapi/v1/users', options)
.then(function(response) {
callback(null, response);
})
.catch(function(error) {
// Deal with the error
console.log(options);
console.log(error);
callback(error);
});
};

ProductHunt API Authentication using jQuery

I'm trying to use the ProductHunt API using jQuery. To use the ProductHunt API, you need to authenticate before you can access the data. I'm using the OAuth Authentication.
Here is the code that I have got.
// api key and secret
key = "api key goes here"
secret = "api secret goes here"
var base_url = "https://api.producthunt.com/v1/"
var token_url = base_url +"oauth/token"
var today_post_url = base_url + "posts"
function get_token(){
var token = '';
$.ajax({
url: token_url,
type: "POST",
async: false,
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: {
"client_id": key,
"client_secret": secret,
"grant_type": 'client_credentials'
},
success: (function(res) {
token = res.access_token;
})
});
return (token);
}
function get_todays_posts() {
token = get_token();
console.log(token);
$.ajax({
url: today_post_url,
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
success: (function(res){
return res;
})
})
}
But when I run get_todays_post(), I get a error message saying GET https://api.producthunt.com/v1/posts 401 (Unauthorized)

How to send a token with an AJAX request from jQuery

I use express-jwt and create my token via jQuery and save it in my localStorage with:
$.ajax({
url: "http://localhost:8080/login",
type: 'POST',
data: formData,
error : function(err) {
console.log('Error!', err)
},
success: function(data) {
console.log('Success!')
localStorage.setItem('token', data.id_token);
}
});
I have a protected route in my backend like:
app.get('/upload',jwt({secret: config.secret}), function(req, res) {
res.sendFile(path.join(__dirname + '/upload.html'));
});
How can I send the token from localStorage with the request header?
You can set the headers in a $.ajax request:
$.ajax({
url: "http://localhost:8080/login",
type: 'GET',
// Fetch the stored token from localStorage and set in the header
headers: {"Authorization": localStorage.getItem('token')}
});
If you are using JWT authentication then this is how you add it to the headers in .ajax() method:
headers: {
Authorization: 'Bearer '+token
}
,
I use the approach below to cover JWT authentication with the result status types
$.ajax({
url: "http://localhost:8080/login",
type: "POST",
headers: { Authorization: $`Bearer ${localStorage.getItem("token")}` },
data: formData,
error: function(err) {
switch (err.status) {
case "400":
// bad request
break;
case "401":
// unauthorized
break;
case "403":
// forbidden
break;
default:
//Something bad happened
break;
}
},
success: function(data) {
console.log("Success!");
}
});

Parse webrequest to Coinbase gives 401 not authorized

I'm trying to send bitcoin through Coinbase's API, and this is my code:
// create object to send as data
var transaction = {
to : correctusermail, // "my#email.com"
amount_string : amount, // "1.00"
amount_currency_iso : currency // "EUR"
};
// get correct auth key from user
var authq = new Parse.Query(Parse.User);
authq.get(objectid, {
success: function(userObject) {
correctauth = userObject.get("provider_access_token");
console.log(correctauth);
console.log(transaction);
// send post request
// make post request
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://coinbase.com/api/v1/transactions/send_money',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {
access_token: correctauth,
transaction: transaction
},
success: function(httpResponse) {
response.success(120);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(111);
}
});
},
error: function(userObject, error) {
response.error(150);
}
});
As you can see I'm making sure that my correctauth var is correct by logging it, which works just fine.
All the other variables are correct, I've checked them. So what am I missing? It's probably very small.
From my understanding of the Coinbase API documentation, the access_token should always be part of the URL, e.g.
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://coinbase.com/api/v1/transactions/send_money?access_token='
+ correctauth,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: {
transaction: transaction
},
// ... etc ...

Categories