I have expressjs sitting on a nodejs server and I have a client side cordova app making ajax requests to certain routes.
This is fine until I need to make a POST request to login using passportjs, there is a 302 redirect that takes place so I get this 302 Moved Temporarily when making this call
$('body').on('submit', '#logIn', function(e){
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: "http://mydomain.io:3300/login",
data: JSON.stringify(formData),
type: "POST",
crossDomain: true,
dataType: "json",
async: true,
success: function(response){
alert('succeeded!');
console.log(response);
alert(response);
},
failure: function(message){
alert("failed");
console.log(message);
alert(message);
}
});
});
So my question is how is it possible using CORS to login to the app using client side ajax?
CORS is not your problem here.
Passport wants to redirect your user (based on the values you've passed to passport.authenticate). For instance:
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { successRedirect: '/',
failureRedirect: '/login' }));
Passport will tell the browser to redirect to / or /login by returning a 302. You can remove the redirect by removing the second parameter to passport.authenticate:
app.get('/auth/facebook/callback',
passport.authenticate('facebook'));
This will call next() on successful authentication (and return 401 otherwise).
The examples here use FacebookStrategy, but it works with any strategy.
Related
I've got a problem. Every time I have to clear caches and cookies first and then the AJAX request can be requested successfully. Otherwise I will get 403 response from the server, which is Django RESTful framework.
This is what I request
$.ajax({
url: url_add,
type : 'PATCH',
dataType: 'json',
data: {
'followup_customer': note,
},
statusCode: {
200: function() {
window.location.reload();
}
},
});
You should add a correct HTTP header, containing CSRF token as described in django docs.
I have an $.ajax request that hits and API. The API returns four cookies and then performs a (302) redirect.
$.ajax({
url: authUrl,
type: 'post',
mode: 'no-cors',
dataType: 'text',
data: dataObj,
})
.done(function (response) {
console.log('response');
console.log(response);
let myCookies = document.cookie;
console.log(myCookies);
});
I'm trying to get the cookies inside the $.ajax, but the redirect causes the code in the .done to never execute.
Even if I try to get the cookies in the console (where I can see the cookies and their values), I get nothing back.
This is happening inside a Chrome Extension, but even if I run this outside the extension I get the same result.
I'm trying to use the google chart api in an XPages application.
I'm using the code example given by the documentation : https://developers.google.com/chart/interactive/docs/php_example#exampleusingphphtml-file
I have to replace the call to the php page by a call to an LS agent.
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
So my code goes to :
var jsonData = $.ajax({
url: "http://server/database/agent?openagent",
dataType: "json",
async: false
}).responseText;
On my local domino server, it works fine.
On the production domino server, I get nothing. The chart is not drawn. After debugging the js client side, it seems the ajax call is expecting an authentification even if I had to log in before.
The anonymous access is not allowed on both servers.
The security level seems to be same on both environments
Any help will be welcome (or any other way to proceed if I'm wrong).
Thank you
If you are able to draw the google chart in your local server, but not in production server, this means it is your server issue.
You can add authentication header in your jquery ajax call to make authenticated ajax request
$.ajax({
headers: {
"Authorization": "Bearer <TOKEN HERE>"
}
})
You can also send username and password in jquery ajax call, to make authenticated request. Here is the sample code from the link
$.ajax({
type: 'GET',
url: 'url',
dataType: 'json',
//whatever you need
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth(user, password));
},
success: function () {});
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
at the end, I tried to run the ajax request through dojo instead of Jquery.
My codes became this one :
var jsonData = dojo.xhrGet({
url: "http://server/database/agent?openagent",
handleAs:"json",
...
})
I did no changes at the security level or anything else.
I do not understand why the jquery syntax is not working as well the dojo syntax.
anyway, it is working now.
Many thanks to all for your suggestions
I am converting a web app into a cordova app the only thing stopping me is the fact that the app is expressjs based, since cordova requires an index.html I need to use CORS to render the app and provide the login session.
I can use ajax/CORS with regular pages but when it comes to authorization I am stuck.
I use passportjs to authenticate on this POST route app.post('/login', passport.authenticate('local-login')); so on my client side cordova app I make an ajax call to make this request for me.
$('body').on('submit', '#logIn', function(e){
e.preventDefault();
var formData = $(this).serialize();
console.log(formData);
$.ajax({
url: "http://mysite.io:3300/login",
data: JSON.stringify(formData),
type: "POST",
crossDomain: true,
dataType: "json",
async: true,
success: function(response){
alert('succeeded!');
console.log(response);
alert(response);
},
failure: function(message){
alert("failed");
console.log(message);
alert(message);
}
});
});
When I make the POST request I get a 401 Unauthorized so I have been doing research on that, I still am not sure why it's not authorizing?
From the Passport docs:
By default, if authentication fails, Passport will respond with a 401 Unauthorized status, and any additional route handlers will not be invoked.
The username/password combination you're posting is not valid.
So... i'm making a cross domain (CORS) call. When i initially make it on the page, it works just fine (noting that cross-domain issues aren't really a problem), but when i make another request later to the same server adding a bearer authorization token to the header, it is failing with a 401 Unauthorized.
Also, when i run this code from the same domain, both calls run successfully (identifying that the token is ok...)
Thoughts?
$.ajax({
url: apiPath.userMetaUrl(),
xhrFields: {
withCredentials: true
},
cache: false,
error: function (xhr, ajaxOptions, thrownError) {
console.log("url: " + apiPath.userMetaUrl());
console.log("fn loadUserMetaData xhr.status: " + xhr.status);
console.log("fn loadUserMetaData xhr.responseText: " + xhr.responseText);
console.log("fn loadUserMetaData thrownError: " + thrownError);
},
dataType: "json",
jsonpCallback: "callback",
beforeSend : setHeader,
success: function (data) {
//woohoo!
}
}
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + authenticatedInfo.access_token);
}
Again, running this code from same domain as apiPath.userMetaURL() works fine. On a different domain, the initial call without adding request header works fine. Access-Control-Allow-Orign has the cross-domain URL added. Access-Control-Allow-Headers has Authorization added.
xhr.status returns 0 and responseText/thrownError are blank.
JSONP != ajax
These requests you are making are simply adding <script> tags to your DOM. It's just wrapped in an ajax syntax for ease of use. You can't modify the request headers in this fashion. You need to create a CORS ajax request, and configure your server to handle them.
Executing jsonp requests on the same domain though... I believe jQuery just uses an xmlHttpRequest though. For cross-domain, it uses <script> tags. This would explain the behavior you are seeing.
Consider the following.
$.ajax({
url: 'http://google.com',
dataType: 'jsonp',
beforeSend: function(xhr) { xhr.setRequestHeader('foo', 'bar'); }
});
Look at your network traffic. It will create the request, but you will not see the foo header.