GitHub: How to set headers for ajax request? - javascript

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

Related

Request current users API token Django REST Framework

I have a Django web app that is using the Django REST framework to generate various API endpoints.
I can ensure only logged in users can view/read these endpoints, but now I am at the stage of development where I want users to post to the API using tokens. I have successfully done this, however, I have hard-coded the users token into the post request in Javascript... This worked for testing but obviously is not a good final solution.
Is it possible to request the current users token somehow? Could I then include this token in the POST request head automatically?
Thanks for any help/feedback in advance!!
EDIT:
I think I am close, but I am getting a few errors in my chrome console, and still can't retrieve token.
Console Errors:
toggleScript.js:25 Uncaught DOMException: Failed to execute
'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
at getToken (http://127.0.0.1:8000/static/defaults/toggleScript.js:25:7)
at manageDefaults
(http://127.0.0.1:8000/static/defaults/toggleScript.js:62:5)
at HTMLInputElement.onclick (http://127.0.0.1:8000/defaults/:1:1)
getToken # toggleScript.js:25
manageDefaults # toggleScript.js:62
onclick # (index):1
toggleScript.js:24 POST http://127.0.0.1:8000/api-token-auth/ 415
(Unsupported Media Type)
I have a button when pressed, will trigger the function to retrieve the token, and this is what is causing the error stack above.
toggleScript.js
function getToken(){
var xhr = new XMLHttpRequest();
var url = 'http://127.0.0.1:8000/api-token-auth/';
xhr.open("POST", url, true);
var data = JSON.stringify({"username": "myusername", "password": "mypassword"});
xhr.send(data);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.token);
}
};
}
Django Rest Framework provides an API endpoint for requesting a user's token, given a username and password. You can wire the view into your urls.py:
from rest_framework.authtoken import views
urlpatterns += [
url(r'^auth-token/', views.obtain_auth_token)
]
Then when you POST a valid username and password to that view it will return the token in a JSON response:
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
Your app can then store that and send it in subsequent requests.
An example of retrieving the token using JQuery (assuming the view was mapped to the path ^auth-token/ in your urls.py):
$.post('/auth-token/', { username: 'admin', password: 'whatever' }, function(data) {
// Token available as data.token
});
If you try and post to the auth-token view from within an already authenticated session, Django will likely reject the request with a CSRF token missing or incorrect response. You should either ensure that the session is not authenticated when you retrieve the token, or you could potentially include the X-CSRFToken header in the request. You'd need to extract the value from the csrftoken cookie. For example (using JQuery and the JQuery Cookie plugin):
$.ajax({
url: "/auth-token/",
type: "POST",
headers: {
"X-CSRFToken": $.cookie("csrftoken") # Extract the csrftoken from the cookie
},
data:{ username: "admin", password: "whatever" },
dataType:"json"
}).done(function(data) {
// Token available as data.token
});
More info on obtaining an auth token here

OAuth in JIRA with JQuery

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);
}
});
});

How can you make an HTTP request to fetch the status.cgi json data from a Ubiquity AirMax or AirFibre radio with javascript?

My goal is to fetch the status data from a UBNT radio (https://www.ubnt.com/) using an HTTP request. The web interface url is formatted as http://192.168.0.120/status.cgi. Making the request requires a authentication cookie. Using the cookie copied from the existing web interface I am able to successfully retrieve the data.
This is my current code using the Meteor framework.
radioHost = "http://192.168.0.120";
HTTP.call("POST", radioHost + "/login.cgi",
{
headers: {
"Content-Type": "multipart/form-data"
},
data: {
username: "ubnt",
password: "ubnt"
}
}, (err, res) = > {
if(err) return console.log(err);
var cookie = res.headers["set-cookie"][0];
HTTP.call("GET", radioHost + "/status.cgi", {
headers: {
cookie
}
}, (err, res) = > {
if(err) return console.log("Error");
console.log(res);
})
})
The above code achieves both request successfully. However the server is responding to the first with a faulty token ("set-cookie" string). Using the cookie from the existing web framework the response is correct.
Here is a library written in Python that I believe does a similar thing. https://github.com/zmousm/ubnt-nagios-plugins
I believe my problem lies within the HTTP request and the web api not cooperating with the username and password.
Thanks in advance for any help.
A direct POST request to a url is not a recommended way. When you open a browser you just don't directly login. You fetch the page and then submit/login
Not simulating this behavior may impact certain sites depending on how the server works.
So if always want to look at the simulating like a real user/browser would do, make a GET request first and then the POST.
Also capture any cookies from the first GET request and then pass the same on to the next one

jQuery Post Callback from REST API

I am working on an app that will submit data to a REST API and have some questions.
How does jQuery know if my post request was successful or not? Is it only looking at the HTTP status?
Is there a convention on what to return from a POST request to a REST API?
JavaScript
$.post( '/API/removeUser', { Eid: id }, function(data) { row.remove(); } );
PHP SLIM Framework
$app->POST('/API/removeUser', function () use ($app) {
// Get the ID from the jQuery post
$Eid = trim(stripslashes(htmlspecialchars($_POST['Eid'])));
echo json_encode(removeFunction($Eid));
});
Your backend should always return the appropriate HTTP status code along with the actual data. 404 for resources that were not found, 403 for unauthorized requests, 200 for successful requests etc. Most AJAX libraries (including jQuery) will rely on those for determining the result of the operation.
If you need more fine-grained error reporting, you could always include a field like "errorCode" in your response that contains an application-level error code that you define yourself and react to accordingly in your frontend code.

Prevent JavaScript from breaking with a 403 HTTP response

I'm grabbing user information from the Last.fm website with a JQuery $.get request.
Since some users' accounts are private, I sometimes receive a 403 error stating that authentication is required. This breaks the JS code. The last.fm API doesn't let you see if a user is private or not.
Is there a way to catch this error and continue through the code?
Thanks!
Not sure if it works with cross-domain requests, but you could do something like this:
$.ajax({
type: 'GET',
statusCode: {
403: function() {
alert('a 403 was received');
}
},
success: function() {
alert('everything OK');
}
});
Or possibly set it up in $.ajaxSetup() if it works ?
You would be better using a proxy to get the data from API since $.ajax() error handler won;t return errors for cross domain requests per jQery API docs:
http://api.jquery.com/jQuery.ajax/
EDIT Note in docs for error option:
"Note: This handler is not called for cross-domain script and JSONP requests."

Categories