I am trying to use the JIRA REST API to preform some requests. One of the first things that you must do, according the docs, is authenticate in some way.
Atlassian offers 2 methods; Basic Auth and Cookie Based Auth, the later of which uses cookies to establish a session.
The issue comes into play when I involve Jquery/JS.
Here is the request when preformed in ARC (Advanced Rest Client) for Chrome:
If I run that request, I will get a HTTP 200 response with the correct JSON, which is what I want.
However, when I attempt to do this with Jquery/JS, I recieve an error every time.
Here is that code:
function cookieLogin() {
//Grab username and password from the fields on the page
var user = $("#loginUsername").val();
var pass = $("#loginPassword").val();
$.ajax({
//URL
url: baseURL + path,
//Method
//type: 'POST', //analogous to 'method'
method: 'POST',
//Headers
accept: 'application/json',
dataType: 'application/json',
contentType: 'application/json',
//Payload to be sent
data:
{
"username": "admin",
"password": "admin"
},
//Responses to HTTP status codes
statusCode: {
200: function () {
alert("Success!");
},
401: function() {
alert("Invalid Credentials");
},
403: function () {
alert("Failed due to CAPTCHA requirement/throttling.")
}
},
success: function (data) {
var result = jQuery.parseJSON(data);
console.log(result);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error!!!");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
I have assured that the URL is correct. As you can see, I also hard-coded the credentials (this is merely a test page) just to test as well. I'm not sure why I am receiving errors in JS when I replicated the same thing that worked in ARC.
As per the documentation, I am seeing that "accept" should be "accepts" and "dataType" takes the string "json", not "application/json".
Related
i am working for the first time with Django Framework. A service provider is using django i can see the data only with an active Cookie on their API Docs.
We received now an API Token to call for the data on the framework.
I am trying to call the data with the Token via AJAX but i receive everytime the same console log "401 (Unauthorized)".
$.ajax({
type: 'POST',
headers: {
'X-CSRFTOKEN': "XXXXXXXXXXXXXXX",
'Content-Type': 'application/json'
},
url: 'www.service-provider.url/api/...',
success: function () {
console.log("ok");
},
error: function () {
console.log("error");
}
});
Sorry i'm a beginner at this point and have no idea where to begin with. I've searched for solution on the inet but couldn't find anything that would work.
Okay i got it! Before the token api key there must be "Token ...".
$.ajax({
type: 'GET',
url: 'https://my-url.com/api/1.0/?format=json',
headers:{
"Content-Type": 'application/json',
"Authorization": 'Token XXXXXXXXXXXXXXXXXXXXX',
},
success: function(data){
console.log(data);
}
});
I'm having trouble following an API Guide using AJAX. I have successfully got the session token from the login api as the session token is needed to make requests to GET/POST data.
Code to get the session token:
var sessionToken = null;
$.ajax({
url: '<API-URL>/1/json/user_login/',
data: {
'login_name' : 'USERNAME',
'password' : 'PASSWORD'
},
type: 'GET',
dataType: 'json',
success: function(data) {
sessionToken = data.response.properties.session_token;
$("#result").text("Got the token: " + sessionToken);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
On successful, we get the session token: D67ABD0454EB49508EAB343EE11191CB4389255465
{response: {…}}
response:
properties:
action_name: "user_login"
data: [{…}]
action_value: "0"
description: ""
session_token: "D67ABD0454EB49508EAB343EE11191CB4389255465"
__proto__: Object
__proto__: Object
__proto__: Object
Now that I have a valid session token, I can now make requests to get data. I'm trying to get driver data using the following code:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
According to the documentation, I need to use POST instead of GET in order to get vehicle details in the response and pass the session token as a parameter:
Unfortunately it seems to return blank data when using GET and Permission denied when using POST. I've tried sending the parameters as an array like the documentation but that fails also. I've tried passing the session token as Authorisation but still get no response.
The only help I got from the API support team was: "POST can’t be with parameter query on the end point."
What am I doing wrong?
Any help is appreciated. Thanks!
I don't know what service/api you're trying to call, but from the error message you've posted and the brief documentation it looks like you're structuring your url wrong:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
You're including the action parameter as part of the url by the looks of things when the doc you posted implies it should be part of the data (and the error they sent you of "POST can’t be with parameter query on the end point." also supports this). So try the following: (of course without seeing more of the docs it's difficult to know if your actual base url is correct)
$.ajax({
url: '<API-URL>/1/json/',
data: {
'action': {'name':'api_get_data',
'parameters': [ {'license_nmbr' : vrn }],
'session_token' : sessionToken
}
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
I have next situation:
Main authentication flow happens on server, then client side obtains these data, since that moment I wanna client be able to update token by itself. It's seems there is all needed data on client(access_token, refresh_token), but I can't figure out how to organize request to https://login.microsoftonline.com/common/oauth2/v2.0/token route.
First I tried to get json response:
$.ajax({
url: `https://login.microsoftonline.com/common/oauth2/token?grant_type=refresh_token&refresh_token=refresh_token&scope=openid%20profile%20offline%20access%20user.read%20mail.read%20contacts.read%20calendars.read&client_id=client&client_secret=secret`,
type: 'POST',
cache: false,
processData: false,
contentType: false,
dataType: 'json',
headers: {
'Host': 'https://login.microsoftonline.com',
'Content-Type': 'application/json'
},
success: function(data) {
...
},
error: function(xhr) {
...
}
});
After that I figured out that it's only possible to get this data with redirect, is it correct? If it is, can someone produce an example of how to implement this, looks like it's needed to create an iframe and handle authorization somehow. Thanks.
UPDATED:
as Alina Li pointed in comment to her answer, there is a solution right in the official doc https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
According to my test, you could using refresh-token through the below code:
var data = "grant_type=refresh_token&refresh_token=refreshToken&client_id=" + appState.clientId;
$http = $http || $injector.get('$http');
$http.post(authUrl + '/token', data, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
}).error(function (err, status) {
});
You don’t need to add scope parameter.
Reference from:
Storing Refresh Token In JavaScript, Getting New Access Token
This problem must have been solved billions of times, yet I'm having a hard time finding my way. I have a backend service that grants OAuth2 tokens with user/password. When the user logs in, I would like the browser to go to the next page. The thing is, such page is only accessible with an auth header. Methods such as document.location.href = "http://nextpage" don't let me set the authorization header, like Authorization = Bearer 1234567890.
The code that runs when the user clicks on the "Login" button is:
var json = {
grant_type: "password",
client_id: "myClient",
username: email, // <--- comes from a form
password: password, // <--- comes from a form
client_secret: "mySecret"
};
$.ajax({
url: "http://localhost:9000/auth/token/grant",
method: 'POST',
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(json),
cache: false,
success: function (data) {
localStorage.authToken = data.access_token;
localStorage.refreshToken = data.refresh_token;
// Here I would like to move the browser to the next page
document.location.href = "http://localhost:9000/nextPage";
}.bind(this),
error: function (xhr, status, err) {
console.error("login request error: ", status, err.toString());
}.bind(this)
});
Thanks for your tips!
I am working now in a phonegap android application, I need the user's current address, so that i have used this
JSON api.
This is my code to get data for location updates from JSON api
$.ajax('http://maps.googleapis.com/maps/api/geocode/json?latlng=26.9008773,75.7403539&sensor=true', {
dataType: 'jsonp',
timeout: 3000,
data: {
_method: 'GET'
},
success: function (data,status) {
if (data._status != 200) {
console.log('received error', data._status);
// handle error
}else{
console.log('received data', data);
// do something useful with the data
}
},
error: function(data,status) {
var myObject = JSON.stringify(data);
console.log("Data Returned is " + myObject);
console.log("Status is " + status);
alert('error');
},
complete: function(data, status) {
alert('complete');
}
});
Every time it goes on error section , then the complete section, never goes into the success part.
the console output is :
12-10 11:11:34.393: I/Web Console(10620): Data Returned is {"readyState":4,"status":404,"statusText":"error"} at file:///android_asset/www/index.html:263
12-10 11:11:34.393: I/Web Console(10620): Status is error at file:///android_asset/www/index.html:264
Can anyone tell me, where exactly the problem is ?
If I remember correctly the default security policy in PhoneGap is to block all network access. You need to whitelist http://maps.googleapis.com.
The api you request does not support jsonp, the final request will like this:
http://maps.googleapis.com/maps/api/geocode/json?callback=jQuery18309743240959942341_1386656119920&latlng=26.9008773,75.7403539&sensor=true&_method=GET&_=1386656120107
with the callback param, but the output is still json, not javsscript file like
jQuery18309743240959942341_1386656119920(jsonDataHere...)
Take a look at this: https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse, it request url like this
https://maps.googleapis.com/maps/api/js/GeocodeService.Search?5m2&1d40.714224&2d-73.96145200000001&7sUS&9sen&callback=_xdc_._4cni6z&token=46423
And the output is:
_xdc_._4cni6z && _xdc_._4cni6z( { ....
That's jsonp.
ajax_call ='http://maps.googleapis.com/maps/api/geocode/json?latlng=26.9008773,75.7403539&sensor=true';
$.ajax({
type: "GET",
url: ajax_call,
cache:false,
dataType: "json",
success: function(response){
$.each(response.results, function(key, value) {
//alert(value.formatted_address);
console.log(value.formatted_address);
});
}
}).done(function() {
})