Backbone with Oauth2 granttype password - javascript

I want to call an OAuth2 service with grant_type password.
I am using Backbone with Jquery.
Parameters for the POST:
grant_type=password
client_id=[YOUR_APP_ID]
client_secret=[YOUR_CLIENT_SECRET]
username=[USER_NAME]
password=[USER_PASSWORD]
I have tried several NPM plugins but all give error.
I have created a custom post AJAX but this also does not work:
var results = $.ajax({
// The URL to process the request
url : "https://app1pub.smappee.net/dev/v1/oauth2/token",
type : "POST",
data : {
grant_type : "password",//jshint ignore:line
username: "myuser",
password: "secret",
client_id: "myclient",//jshint ignore:line
client_secret: "clientSecret"//jshint ignore:line
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer $token");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function(response) {
//console.log(response);
console.log(response.access_token);//jshint ignore:line
data.access_token = response.access_token;//jshint ignore:line
//tokenGranted();
}
});
return results.responseText;
(see fiddle: https://jsfiddle.net/gf70sss5/)
All give me the error:
"XMLHttpRequest cannot load https://app1pub.smappee.net/dev/v1/oauth2/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access."
Does anyone know a NPM plugin which works with the password granttype? Preferrably with an example. I have tried a few (like simple-oauth2) but I can't get any working.
Or an AJAX call which does work? Or what I am doing wrong?

Try this, but i've still a problem with the "Access-Control-Allow-Origin" error
var url = 'https://app1pub.smappee.net/dev/v1/oauth2/token';
// ajax call
$.ajax({
type: "POST",
url: url,
data: {"grant_type": "password", "client_id": client_id, "client_secret": client_secret,"username": username,"password": password},
beforeSend : function(xhr) {
xhr.setRequestHeader("POST", "/dev/v1/oauth2/token HTTP/1.1");
xhr.setRequestHeader("HOST", "app1pub.smappee.net");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
},
error : function() {
// error handler
},
success: function(data) {
// success handler
alert(data["access_token"])
}

Related

How do I make an XGET request with jQuery? [duplicate]

I am trying to create a basic authentication through the browser, but I can't really get there.
If this script won't be here the browser authentication will take over, but I want to tell the browser that the user is about to make the authentication.
The address should be something like:
http://username:password#server.in.local/
I have a form:
<form name="cookieform" id="login" method="post">
<input type="text" name="username" id="username" class="text"/>
<input type="password" name="password" id="password" class="text"/>
<input type="submit" name="sub" value="Submit" class="page"/>
</form>
And a script:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
async: false,
data: '{"username": "' + username + '", "password" : "' + password + '"}',
success: function (){
alert('Thanks for your comment!');
}
});
Use jQuery's beforeSend callback to add an HTTP header with the authentication information:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
How things change in a year. In addition to the header attribute in place of xhr.setRequestHeader, current jQuery (1.7.2+) includes a username and password attribute with the $.ajax call.
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
username: username,
password: password,
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
EDIT from comments and other answers: To be clear - in order to preemptively send authentication without a 401 Unauthorized response, instead of setRequestHeader (pre -1.7) use 'headers':
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
headers: {
"Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
},
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
Use the beforeSend callback to add a HTTP header with the authentication information like so:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
async: false,
data: '{}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', make_base_auth(username, password));
},
success: function (){
alert('Thanks for your comment!');
}
});
Or, simply use the headers property introduced in 1.5:
headers: {"Authorization": "Basic xxxx"}
Reference: jQuery Ajax API
The examples above are a bit confusing, and this is probably the best way:
$.ajaxSetup({
headers: {
'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
}
});
I took the above from a combination of Rico and Yossi's answer.
The btoa function Base64 encodes a string.
As others have suggested, you can set the username and password directly in the Ajax call:
$.ajax({
username: username,
password: password,
// ... other parameters.
});
OR use the headers property if you would rather not store your credentials in plain text:
$.ajax({
headers: {"Authorization": "Basic xxxx"},
// ... other parameters.
});
Whichever way you send it, the server has to be very polite. For Apache, your .htaccess file should look something like this:
<LimitExcept OPTIONS>
AuthUserFile /path/to/.htpasswd
AuthType Basic
AuthName "Whatever"
Require valid-user
</LimitExcept>
Header always set Access-Control-Allow-Headers Authorization
Header always set Access-Control-Allow-Credentials true
SetEnvIf Origin "^(.*?)$" origin_is=$0
Header always set Access-Control-Allow-Origin %{origin_is}e env=origin_is
Explanation:
For some cross domain requests, the browser sends a preflight OPTIONS request that is missing your authentication headers. Wrap your authentication directives inside the LimitExcept tag to respond properly to the preflight.
Then send a few headers to tell the browser that it is allowed to authenticate, and the Access-Control-Allow-Origin to grant permission for the cross-site request.
In some cases, the * wildcard doesn't work as a value for Access-Control-Allow-Origin: You need to return the exact domain of the callee. Use SetEnvIf to capture this value.
Use the jQuery ajaxSetup function, that can set up default values for all ajax requests.
$.ajaxSetup({
headers: {
'Authorization': "Basic XXXXX"
}
});
There are 3 ways to achieve this as shown below
Method 1:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
headers: {
"Authorization": "Basic " + btoa(uName+":"+passwrd);
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 2:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic " + btoa(uName+":"+passwrd));
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 3:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
username:uName,
password:passwrd,
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
JSONP does not work with basic authentication so the jQuery beforeSend callback won't work with JSONP/Script.
I managed to work around this limitation by adding the user and password to the request (e.g. user:pw#domain.tld). This works with pretty much any browser except Internet Explorer where authentication through URLs is not supported (the call will simply not be executed).
See http://support.microsoft.com/kb/834489.
According to SharkAlley answer it works with nginx too.
I was search for a solution to get data by jQuery from a server behind nginx and restricted by Base Auth. This works for me:
server {
server_name example.com;
location / {
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization";
# Not necessary
# add_header Access-Control-Allow-Credentials "true";
# add_header Content-Length 0;
# add_header Content-Type text/plain;
return 200;
}
auth_basic "Restricted";
auth_basic_user_file /var/.htpasswd;
proxy_pass http://127.0.0.1:8100;
}
}
And the JavaScript code is:
var auth = btoa('username:password');
$.ajax({
type: 'GET',
url: 'http://example.com',
headers: {
"Authorization": "Basic " + auth
},
success : function(data) {
},
});
Article that I find useful:
This topic's answers
http://enable-cors.org/server_nginx.html
http://blog.rogeriopvl.com/archives/nginx-and-the-http-options-method/

REST request errors in Jquery but not REST Client

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".

HTTP Authentication failing in AJAX for postmates api

I'm trying to use the postmates API, which first requires us to authenticate ourselves using http basic authentication. The username field in the code below is where we inserted our private API key.
<script>
$(document).ready(function(){
// Request with custom header
$.ajax({
url: ' http://username:#api.postmates.com',
type: 'GET',
dataType: 'jsonp',
success: function(response) { alert("Success"); },
error: function(error) {alert(error); }
});
});
</script>
The error we are getting is
XMLHttpRequest cannot load
http://api.postmates.com/?callback=jQuery112008309037607698633_1462052396724&_=1462052396725.
Response for preflight is invalid (redirect)
need the authentication
https://postmates.com/developer/docs#authentication
The actual header that is used will be a base64-encoded string like
this:
Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==
Try to
$(document).ready(function(){
// Request with custom header
$.ajax({
url: ' http://username:#api.postmates.com',
type: 'GET',
dataType: 'jsonp',
success: function(response) { alert("Success"); },
error: function(error) {alert(error); },
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==");
}
});
});
I don't test because jsfiddle block external petitions.

"400 Bad Request" response for AJAX request

I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})

Use basic authentication with jQuery and Ajax

I am trying to create a basic authentication through the browser, but I can't really get there.
If this script won't be here the browser authentication will take over, but I want to tell the browser that the user is about to make the authentication.
The address should be something like:
http://username:password#server.in.local/
I have a form:
<form name="cookieform" id="login" method="post">
<input type="text" name="username" id="username" class="text"/>
<input type="password" name="password" id="password" class="text"/>
<input type="submit" name="sub" value="Submit" class="page"/>
</form>
And a script:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
async: false,
data: '{"username": "' + username + '", "password" : "' + password + '"}',
success: function (){
alert('Thanks for your comment!');
}
});
Use jQuery's beforeSend callback to add an HTTP header with the authentication information:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
How things change in a year. In addition to the header attribute in place of xhr.setRequestHeader, current jQuery (1.7.2+) includes a username and password attribute with the $.ajax call.
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
username: username,
password: password,
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
EDIT from comments and other answers: To be clear - in order to preemptively send authentication without a 401 Unauthorized response, instead of setRequestHeader (pre -1.7) use 'headers':
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
headers: {
"Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
},
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
Use the beforeSend callback to add a HTTP header with the authentication information like so:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
async: false,
data: '{}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', make_base_auth(username, password));
},
success: function (){
alert('Thanks for your comment!');
}
});
Or, simply use the headers property introduced in 1.5:
headers: {"Authorization": "Basic xxxx"}
Reference: jQuery Ajax API
The examples above are a bit confusing, and this is probably the best way:
$.ajaxSetup({
headers: {
'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
}
});
I took the above from a combination of Rico and Yossi's answer.
The btoa function Base64 encodes a string.
As others have suggested, you can set the username and password directly in the Ajax call:
$.ajax({
username: username,
password: password,
// ... other parameters.
});
OR use the headers property if you would rather not store your credentials in plain text:
$.ajax({
headers: {"Authorization": "Basic xxxx"},
// ... other parameters.
});
Whichever way you send it, the server has to be very polite. For Apache, your .htaccess file should look something like this:
<LimitExcept OPTIONS>
AuthUserFile /path/to/.htpasswd
AuthType Basic
AuthName "Whatever"
Require valid-user
</LimitExcept>
Header always set Access-Control-Allow-Headers Authorization
Header always set Access-Control-Allow-Credentials true
SetEnvIf Origin "^(.*?)$" origin_is=$0
Header always set Access-Control-Allow-Origin %{origin_is}e env=origin_is
Explanation:
For some cross domain requests, the browser sends a preflight OPTIONS request that is missing your authentication headers. Wrap your authentication directives inside the LimitExcept tag to respond properly to the preflight.
Then send a few headers to tell the browser that it is allowed to authenticate, and the Access-Control-Allow-Origin to grant permission for the cross-site request.
In some cases, the * wildcard doesn't work as a value for Access-Control-Allow-Origin: You need to return the exact domain of the callee. Use SetEnvIf to capture this value.
Use the jQuery ajaxSetup function, that can set up default values for all ajax requests.
$.ajaxSetup({
headers: {
'Authorization': "Basic XXXXX"
}
});
There are 3 ways to achieve this as shown below
Method 1:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
headers: {
"Authorization": "Basic " + btoa(uName+":"+passwrd);
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 2:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic " + btoa(uName+":"+passwrd));
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 3:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
username:uName,
password:passwrd,
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
JSONP does not work with basic authentication so the jQuery beforeSend callback won't work with JSONP/Script.
I managed to work around this limitation by adding the user and password to the request (e.g. user:pw#domain.tld). This works with pretty much any browser except Internet Explorer where authentication through URLs is not supported (the call will simply not be executed).
See http://support.microsoft.com/kb/834489.
According to SharkAlley answer it works with nginx too.
I was search for a solution to get data by jQuery from a server behind nginx and restricted by Base Auth. This works for me:
server {
server_name example.com;
location / {
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization";
# Not necessary
# add_header Access-Control-Allow-Credentials "true";
# add_header Content-Length 0;
# add_header Content-Type text/plain;
return 200;
}
auth_basic "Restricted";
auth_basic_user_file /var/.htpasswd;
proxy_pass http://127.0.0.1:8100;
}
}
And the JavaScript code is:
var auth = btoa('username:password');
$.ajax({
type: 'GET',
url: 'http://example.com',
headers: {
"Authorization": "Basic " + auth
},
success : function(data) {
},
});
Article that I find useful:
This topic's answers
http://enable-cors.org/server_nginx.html
http://blog.rogeriopvl.com/archives/nginx-and-the-http-options-method/

Categories