AJAX GMAIL API Call Authorization error - javascript

I'm new to the GMail API and am trying to make an AJAX call to retrieve mails.
My code is:
$.ajax({
beforeSend: function (request)
{
request.setRequestHeader("authorization", "Bearer xxxxxxxxxxxxxxxxx.apps.googleusercontent.com");
},
url: 'https://www.googleapis.com/gmail/v1/users/me/messages?key=xxxxxxxxxxxxxxxxxx',
dataType: 'json',
cache: false,
success: function(data) {
// this.setState({Emails: data});
console.log("Mail thread"+data);
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
The response is a 401 error. On examining the request, I find the following query parameter appended to the request URL getting sent:
&_=1470236511985
So the request URL appears like this.
https://www.googleapis.com/gmail/v1/users/me/messages?key=xxxxxxxxxxxxxxxxxx&_=1470236511985
Is the appended query parameter causing the 401 error or am I using the authorization header incorrectly? How can I resolve this.
Thanks in advance.

For testing purposes, you can go to the OAuth 2.0 Playground and get an access token with the Gmail API scopes. Just use this access token in a query parameter named access_token:
var accessToken = 'ya29...';
$.ajax({
url: 'https://www.googleapis.com/gmail/v1/users/me/messages?access_token=' + accessToken,
dataType: 'json',
success: function(data) {
console.log(data.messages);
}
}

Related

add new record in CRM using web API

I am trying to add records to CRM using Javascript but getting:
401 Unauthorized Error.
My question is how to get the token and use it inside the JavaScript function.
$(document).ready(function() {
$("#Save").click(function() {
var ProductDetails = new Object();
ProductDetails.ProductName = $("#txt_productName").val();
ProductDetails.ProductDetail = $("#txt_desc").val();
$.ajax({
url: "https://mycrm.dynamics.com/api/data/v9.1/Products",
type: "Post",
dataType: 'JSON',
data: ProductDetails,
contentType: 'application/x-www-form-urlencoded',
success: function(data) {
alert('Updated Successfully');
},
error: function(request, status, error) {
alert(request.status);
}
});
});
});
You need add Authorization information in Http Header. Here is an example if you use JWT.
$(document).ready(function() {
$("#Save").click(function() {
var ProductDetails = new Object();
ProductDetails.ProductName = $("#txt_productName").val();
ProductDetails.ProductDetail = $("#txt_desc").val();
$.ajax({
url: "https://mycrm.dynamics.com/api/data/v9.1/Products",
type: "Post",
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization':'Bearer your token here'
},
dataType: 'JSON',
data: ProductDetails,
contentType: 'application/x-www-form-urlencoded',
success: function(data) {
alert('Updated Successfully');
},
error: function(request, status, error) {
alert(request.status);
}
});
});
});
You have to add a header with the bearer token like this:
$.ajax({
(...)
headers: {
"Authorization": "Bearer " + token
},
(...)
In order to get a token you have to register an application in Azure Active Directory first, in the same tenant as your Dynamics 365 instance. Check this link if you need a thorough step by step guide to do it.
After registering you application in AAD you also have to add some code to do the authentication with Azure and getting the token. ADAL.js does this job for you, but keep in mind that it prompts the user to manually add his username and password in a office 365 popup. This is called interactive authentication and as far as I know it can't be avoided.
For a full HTML + JS working example click here.

Access Django Rest Framework API using Javascript - getting a Token

I have an API setup using Django Rest Framework. It works fine when accessing via cURL or HTTPie or even the browsable API. The API has token authentication so initially you have to supply credentials which will return a token. Using HTTPie (or even curl) you would do this:
http POST http://127.0.0.1:8000/api/v1/api-token-auth/ username="user1" password="testpassword"
This would return a response e.g.:
HTTP/1.0 200 OK
Allow: POST, OPTIONS
Content-Type: application/json
Date: Sun, 03 Sep 2017 16:57:38 GMT
Server: WSGIServer/0.2 CPython/3.6.1
X-Frame-Options: SAMEORIGIN
{
"token": "fgfdgfdgfdgfdgd45345345lkjlj"
}
You would then take the token and perform a GET/PUSH/etc like so:
http --json POST http://127.0.0.1:8000/api/v1/test/ test_text="Testing" 'Authorization: Token fgfdgfdgfdgfdgd45345345lkjlj'
I have been Google searching for a while now and cannot find any clear answers as to how the above two lines would translate into Javascript? How do I (1) Pass through credentials to get a token; (2) Retrieve the Token; (3) Use the token to make a GET and PUSH request?
I agree you should use Ajax.
You need an ajax call in the very beginning of you app:
var data = {username:'user',password:'password'}
$.ajax({
type: 'POST',
data: data,
url: 'http://your_url',
success: function(res){
console.log(res)
$.ajaxSetup({
headers: {
"token": res.token
}
});
},
error: function(error) {
callbackErr(error,self)
}
})
Haven`t tested, but idea is use an Ajax call to get the token and use .ajaxSetup to save the token to a header for all following ajax requests.
The you can do this:
var data = {test_text="Testing"}
$.ajax({
type: 'POST',
data: data,
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
console.log(res) //answer of api call.
});
},
error: function(error) {
callbackErr(error,self)
}
})
Or this:
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/api/v1/ANOTHER_TES/',
success: function(res){
console.log(res) //answer of api call.
});
},
error: function(error) {
callbackErr(error,self)
}
})
Change type parameter of the call to change your request.
See #Tico's answer.
How do I (1) Pass through credentials to get a token; (2) Retrieve the Token; (3) Use the token to make a GET and PUSH request?
$.ajax({
type: 'POST',
data: {
username: "user1",
password: "testpassword"
},
url: 'http://127.0.0.1:8000/api/v1/api-token-auth/',
success: function(res){
$.ajaxSetup({
headers: {
"token": res.token
}});
$.ajax({
type: 'POST',
data: {
test_text: "Testing"
},
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
alert(res);
}});
}
});
as post, get or any other url calls are asynchronous calls. So in order to maintain the program flow and make the post request you need to use promise feature of js, which will make your post call synchronous.
js promise description
var data = {username:'user',password:'password'}
$.ajax({
type: 'POST',
data: data,
url: 'http://your_url',
success: function(res){
console.log(res)
$.ajaxSetup({
headers: {
"token": res.token
}
});
},
error: function(error) {
callbackErr(error,self)
}
})
this code will work fine if you use this at the starting of your program, but this is asynchronous, to make it synchronous with your program you need to use promise.
And for the third part of your question you need to do this...
$.ajax({
type: 'GET',
url: 'http://your_url' + "/token=" + your_token,
success: function(res){
console.log(res)
},
error: function(error) {
callbackErr(error,self)
}
})

CROS Origin API Call issue?

I host my MVC API in server 'A'.
I tried to call API using jquery ajax call from native server (server 'A'). it's working fine as expected.
But, when tried to call API from server 'B'. I got an error.
No 'Access-Control-Allow-Origin' header is present on the requested resource
My ajax call like below
$.ajax({
url: Url,
type: "GET",
data: Data,
contentType: "application/json charset=utf-8",
async: false,
cache: false,
error: function (xhr, ajaxOptions, thrownError) {
console.log("Exception in ajaxRequest - " + xhr.status + ' - ' + thrownError);
},
success: function (data) {
ResultData = $.parseJSON(data);
}
});

Authenticating bigcommerce using zapier and javascript

I am trying to authenticate using javascript through Zapier but I am unable to authenticate. I am using the following code:
var auth = 'Basic **************';
var url = 'https://www.*****.com/api/v2/customers?email=mel****.com';
$.ajax({
url : url,
method : 'GET',
dataType: "json",
contentType: "application/json; charset=utf-8",
async: false,
crossDomain: true,
beforeSend : function(req) {
req.setRequestHeader('Authorization', auth);
},
success: function(result) {
alert('done');
console.log(result);
},
error: function (request, textStatus, errorThrown) {
console.log(request.responseText);
console.log(textStatus);
console.log(errorThrown);
}
});
However I keep receiving a 401 unauthenticated user error. I have tried running it from an https site but can't get it to work. Any pointers would be greatly appreciated.
You need to base64 encode your username:password credentials.
var auth = 'Basic ' +window.btoa('username:password');

not a valid HTTP header field value ajax error

I'm developing some javascript code to use the summon api server. I developed a simple js function to send a ajax request to the server using JQuery .ajax as below.
requestApi = function(currentDate, digest) {
return $.ajax({
type: "GET",
url: "http://api.summon.serialssolutions.com/2.0.0/search",
data: "s.q=cancer",
headers: {
'Accept': 'application/xml',
'x-summon-date': currentDate,
'Authorization': 'Summon myuser;' + digest
},
error: function(xhr, status, err) {
return console.log(status, err.message);
}
}).done(function(data) {
return console.log(data);
}).fail(function() {
return console.log("Summon Ajax Failed!");
});
};
but I faced an error like:
Failed to execute 'setRequestHeader' on 'XMLHttpRequest':
'Summon myuser;CkKhLokX5jdOx8oCYhgn848MZfw='
is not a valid HTTP header field value.
I don't really know where the problem is. Guide me please. Thanks

Categories

Resources