I'm making a client application where the user must login using JIRA, similar like other apps where you grant permission to your credentials and access right away the application.
I followed the instructions and I'm setting up my client using this reference I'm sending my request to MY_BASE_URL + "/plugins/servlet/oauth/request-token" but I'm getting a empty response and a CORS error that the request didn succeded.
My question is consuming the api endpoints via javascript is even possible? , I searched a lot here and inside the forums of Atlassian and I the only thing I found is this question which is unanswered.
$("#authenticate").click(function(){
jQuery.ajax({
//The URL to process the request
'url': BASE_URL+'/plugins/servlet/oauth/request-token',
'headers':{
'Access-Control-Allow-Origin':'*'
},
'type': 'GET',
'success': function (data) {
alert('Request token is: ' + data);
}
});
});
Related
I am trying to perform actions on sendgrid lists via their API.
https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html#List-All-Lists-GET
I'm using this to set up my code however I'm getting Error 401 UNAUTHORISED when performing the request via $http in my Angular app.
I tried making the same request in Python and that seemed to working fine though.
var head = {'Authorization': 'Bearer SG.PE-XXXXXXXXXXXXXXXXXXXXXX'};
var sgUrl = "https://api.sendgrid.com/v3/contactdb/lists";
self.$http({
method : "GET",
url : sgUrl,
headers : head,
}).then(function mySuccess(response) {
alert(1);
}, function myError(response) {
alert(0);
});
Thanks!
Update - 2016-01-30
As advised in the comments I have:
installed XAMPP
put my page on Apache and ran the server
made sure the page and the scripts are executing (simple alert test)
set the xhrFields: withCredentials to false to make CORS request as advised in the only answer and taught here
I still cannot pass the request. This is the console log:
XMLHttpRequest cannot load http://localhost:8080/RimmaNew/rest/appointments.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 400
Here how it looks on the 'user end' if this is of any help:
------------------Initial ticket-----------------------------
I have a java rest application that runs locally and accepts so far one get method and returns a json string:
Another method is POST, which is supposed to convert, validate and save the information from the sent form and return a 200 answer. If anything goes wrong during conversion, validation or persistence - an exception is thrown (e.g. BadRequest or 500).
This is the rest method (I omitted for brevity validating, build methods as well as the converter and converter provider classes):
#POST
#Produces("application/json")
#Consumes("application/x-www-form-urlencoded")
public Response bookAppointment(#FormParam("date") Date appDate,
#FormParam("time") Time appTime, #FormParam("type") String appType,
#FormParam("clientName") String clientName, #FormParam("email") String clientEmail,
#DefaultValue("") #FormParam("message") String clientMsg) {
//externalize the validation of all fields to concentrate on "positive"
//scenario only
validator(appDate, appTime, appType, clientName, clientEmail);
Appointment appointment = build(appDate, appTime, appType,clientName,
clientEmail, clientMsg);
try {
repository.add(appointment);
return Response.ok(appointment).build();
} catch (Exception e) {
throw new InternalServerErrorException("Something happened in the application "
+ "and this apointment could not get saved. Please contact us "
+ "to inform us of this issue.");
}
}
The client is not within the application (I thought may be this will be useful) - it is a simple HTML file on my computer that has this jQuery script:
<script type='text/javascript'>
$(document).ready(function(){
$('form#appointmentForm').submit(function(ev){
ev.preventDefault();
$.ajax({
url: 'localhost:8080/RimmaNew/rest/appointments',
type: 'post',
dataType: 'json',
data: $('form#appointmentForm').serialize(),
contentType: 'application/x-www-form-urlencoded',
beforeSend: function() {
$('#ajaxResponse').html("<img src='245.gif' />");
},
success: function(data) {
$('#ajaxResponse').html("<span style='color:white; background-color: green;' class='glyphicon glyphicon-ok'></span><p>"+JSON.stringify(data)+"</p>")
.fadeIn("slow");
},
error: function(xhr, ajaxOptions, thrownError){
$('#ajaxResponse').html("<span style='color:white; background-color: red;' class='glyphicon glyphicon-exclamation-sign'></span><p>Status: ").append(xhr.status)
.append("</p>").fadeIn("slow");
}
});
});
});
</script>
I want to submit a form in order to access its params with the #FormParam annotated attributes. On every request that I send I do not receive any of the thrown errors and the status is always 0. Do you see where am I erring or what am I missing?
A status code of 0 means that the request didn't happen. In order to have a status code a valid http interaction has to happen, if none did there is no status code.
The main reasons why this would happen are:
The DNS could not be resolved
A connection to the host/port could not be established
CORS Issues, the HTML is not being served by the same host/port than the server. In this case you need to write a CORS policy to allow specific domains to
make ajax request to the server.
The HTML is a local file, this is a special case of the CORS problem where some browser don't allow connections without a host.
All of them should show an error on the javascript console ( the weirdest would be CORS that shows itself as a failed OPTIONS request )
I am using "http://j.maxmind.com/app/geoip.js" for multilingual site support but this link is throwing 404 error.
Here is the error
Failed to load resource: the server responded with a status of 404 (Not Found)
www.globalenglish.com/:913 Uncaught ReferenceError: geoip_country_code is not defined
chrome-extension://gllmlkidgbagkcikijiljllpdloelocn/contentscript.js:1849 www.globalenglish.com
getuid:1 GET https://api.bizographics.com/v2/getuid?api_key=422935bcbfc445d59f10758c288c…I%252bJLufjW0EE6tV4BHMF43u8yA9qpnPTK8G7tGxJuiy5ReJz%252fscH55wHNbnsJU%253d 403 (Forbidden)
I checked the site here for new link, this link throws 401 error.
I also checked new API here but this also did not work for me. JS Link works but geoip_country_code() is undefined
How to make it work again !!!! Here is fiddle
Thanks
Unfortunately, Maxmind doesn't provide a geoip api through
http://j.maxmind.com/app/geoip.js
anymore. Although it provides another api as
http://js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js
However it requires a domain registration etc. according to Maxmind's website. The link below is a clone of the old api and valid for around one year now.
http://geoapi123.appspot.com/
I've just used this for one of my projects in development stage for a very quick solution. But I strongly suggest you to update your code according to a trustworthy service again.
A working jsfiddle to show how things could play on here; which shows this chunk of code:
$.ajax( {
type: 'GET',
url: '//geoapi123.appspot.com/',
dataType: 'script',
cache: true,
success: function() {
var geo = geoip_country_code() + '|' + geoip_region_name() + '|' + geoip_city() + '|' + geoip_latitude() + '|' + geoip_longitude();
$('#results').html(geo);
}
});
UPDATE:
I realised this answer is still getting attraction. Please be aware it has been years since I wrote this one. The URL I shared does not seem to be working anymore. Also there are much better approaches to handle the problem now.
Actually, there is a message in the console you might have missed :
Users of the GeoIP2 JavaScript API must register their domains at
https://www.maxmind.com/en/javascript_domains
The loading of the library failed because a request is issued to the js.maxmind.com domain with your current hostname (fiddle.jshell.net in your case) as the referrer to ensure that the client was actually making a request from an authorized hostname.
hey guys i'm using This script but i don't know why HTTPS doesn't work when i try to redirect .. it only work With HTTPS
$.ajax({
url: "http://api.petabyet.com/geoip",
success: function(data) {
switch (data.country_code) {
case 'DE':
window.location.href = "https://google.com/de";
break;
}
}
})
</script>
How do I set authorization headers for ajax request to make request on GitHub account?
I have created Personal Access Tokens on GitHub to use it with ajax for authentication to perform operations on my repository.
ajax request is made as shown below:
var apiDomain = 'https://api.github.com',
api="/users/" + username;
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "token 8da3512a16c3fc0d33d8932ca37e6f5bc4c695c0");
},
url:apiDomain+api+'?callback=testUser',
dataType:'script'
});
I get the response data as expected. However, the ajax call is unauthenticated and I always see the following on the meta object
X-RateLimit-Limit: "60"
X-RateLimit-Remaining: "55"
X-RateLimit-Reset: "1387964695"
status: 200
If the ajax request is authenticated I should be able to make ~5000 requests.
How do I use my Personal Access Tokens to make more ajax requests on GitHub?
Passing the access_token as a query parameter solved the problem.
Here is the modified version with the query parameter "access_token"
var apiDomain = 'https://api.github.com',
api="/users/" + username;
$.ajax({
url:apiDomain+api+'?callback=testUser&access_token=8da3512a16c3fc0d33d8932ca37e6f5bc4c695c0',
dataType:'script'
});
P.S: The comment in the question helped me find the solution. Thanks #VonC
This is a follow up to a previous question I had posted here.
Basically I've been trying to implement a way to send request to twitter oauth resources via javascript. I have a server running a Django application which uses Django-social-auth to register users to Tiwtter. After I've obtained authorisation I get a users access_token and oauth_token_secret.
On the client side I have a javascript application which calls my server to compute the appropriate headers, which I do by using python oauth2. The piece of code doing this is as follows:
url = request.POST['url']
params = {
'oauth_version': "1.0",
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': int(time.time()),
}
at = social.extra_data['access_token'].split('&oauth_token=')[1]
ats = social.extra_data['access_token'].split('&oauth_token=')[0].split('oauth_token_secret=')[1]
token = oauth.Token(key=at, secret=ats)
consumer = oauth.Consumer(key=settings.TWITTER_CONSUMER_KEY, secret=settings.TWITTER_CONSUMER_SECRET)
params['oauth_token'] = token.key
params['oauth_consumer_key'] = consumer.key
req = oauth.Request(method="GET", url=url, parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, consumer, token)
This request parameters are then sent to the client which does the call to Twitter using these parameters:
$.ajax({
url: "https://api.twitter.com/1/statuses/home_timeline.json",
data: parameters,
dataType: 'jsonp',
success: function(twitter_data) {
console.log('twitter_data = ', twdata);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('err = ', textStatus);
console.log('err = ', errorThrown);
}
});
which generates a request for a resource like:
https://api.twitter.com/1/statuses/home_timeline.json?callback=jQuery17107030615725088865_1341786299930&oauth_nonce=15094349&oauth_timestamp=1341785696&oauth_consumer_key=[OAUTH_CONSUMER_KEY HERE]&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_token=[OAUTH_TOKEN HERE]0&oauth_signature=pQwHlKmepgtym%2Ffj%2BupCGP8mv3s%3D&page=2&include_entities=true&_=1341786306712
Still I get a 401 Unauthorized error. I checked the code three times so am wondering if I missing something???
Thanks.
For requests which requires an authentication, you have to put the authentication parameters in a HTTP header called Authorization, not in the POST parameters. It is explained in the Twitter API documentation here : https://dev.twitter.com/docs/auth/authorizing-request.