I have a rest server running locally and a front end server running locally aswell. The rest server uses restify and session-cookie with passportjs. This all seems to be working fine as im using Postman app to test the API where cookies are being found and saved:
Postman app image
But when i use ajax on my front end app to login, i do not receive the cookie. Or at least it does not seem to save. This is the ajax code:
$("form#login-form").submit(function(){
var data ={
email: $(this).find("input[name='email']").val(),
password: $(this).find("input[name='password']").val()
};
var data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: URL + "/login",
data: data,
contentType: "application/json",
dataType: "json",
xhrFields: {
withCredentials: true
},
success: function(data) {
console.log(data);
if(data.error){
console.log("logged in error:" + data.error);
}
else {
console.log("logged in:" + data.LoggedIn);
window.location.replace("/");
}
}
});
But the front end acts like it does log me in with each page displaying the right user info and logging out works perfectly too, but i cannot find a stored session for the page anywhere in chrome or firefox dev tools.
What could be causing this?
Related
i want to login to activision site and after i convert a xsrf token via the 'get' request for the login site, when i try to make a 'post' login with my account details & the xsrfToken i'm getting stuck in the air and nothing pop up to my console and its seems like the program stil running...
This may be because they have "I'm not a robot" [recaptcha] authentication?
I took the code from : https://documenter.getpostman.com/view/5519582/SzzgAefq
var axios = require('axios');
var qs = require('qs');
var data = qs.stringify({
'username': 'myUserName',
'password': 'myPassword',
'remember_me': 'true',
'_csrf': 'xsrfToken'
});
var config = {
method: 'post',
url: 'https://s.activision.com/do_login?new_SiteId=activision',
headers: {
'Cookie': "XSRF-TOKEN=xsrfToken"
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Okay, so after checking the code, the source of the problem was what I suspected and is because of the verification of "I'm not a robot" [recaptcha] authentication!
Whoever else encounters this problem - what you need to do is generate a script that will connect from your PC browser to their site from a user for whom you manually activated the "Remember me", or you have to pay to a third-party library that will pass the verification for you. Then retrieve the session data from it.
I've created a node.js microservice using the libraries express and request.
The idea is to forward a post-request by the client application from the first endpoint ("http://example.com/proxy/x") to the second one ("http://example.com/x"). If I do the request to /proxy/x via POSTMAN locally to my "localhost:/proxy/x" instance, it works just fine. The request gets the expected response without any problem. If I push it to the cloud environment using a containering system and ask the endpoint via "http://example.com/proxy/x" it says "CANNOT /GET /x" and fails with a 404 error.
To cover the "404" error, I've even created a app.get listener on "/proxy/x".
Now it returns "error = true". That means my POST is turned to a GET call.
The url is already hardcoded, before I've generated it with a combination of req.protocol and req.get('host'). Seems to generate a valid url, still does not work.
POST http://example.com/proxy/target
app.post('/proxy/target', (req, res) => {
// const currentURL = req.protocol + '://' + req.get('host');
const requestBody = req.body;
request.post({
url: 'http://example.com/target',
followAllRedirects: true, // I've also tried to outcomment it
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic user:password',
},
form: requestBody
},
(err, response, body) => {
if (err) {
return console.log(err);
} else {
// console.dir(response);
return res.status(response.statusCode).send(response.body);
}
}
);
});
app.route('/target')
.post(function (req, res) {
//some code
});
Expected result should be the response body the call delivers, if I'm callign /target directly.
{
'success':true
}
It actually is responding with:
Cannot GET /x/
As it works perfectly on my localhost, it might be the case that my cloud dev environment is the problem.
I would be glad for additional ideas. The cloudsystem is a containering environment called CloudFoundry.
Update:
It seems like CloudFoundry is using NGINX per default: https://docs.cloudfoundry.org/buildpacks/nginx/index.html
Other developers had similar issues when using NGINX: https://www.digitalocean.com/community/questions/post-request-redirects-to-get-in-nginx-proxy-and-nodejs
Full disclaimer: I have never worked with Microsofts NTLM before.
I've tried around 30 different ways to access the 7Pace timetracker API on our local TFS instance. I know it works if i access the URI directly in Chrome, it prompts me for my AD login, and swiftly serves me all the data requested. Same for Postman, except there is an authentication tab for NTLM ahead of time.
Postman suggests this for Node.js using request:
var request = require("request");
var options = {
method: 'GET',
url: 'http://TFSURL/odata/TimeExport%28StartDate=%272018-11-14%27,EndDate=%272018-11-14%27%20,PopulateTopParentColumns=null,GroupTimeByDateByUser=null,IncludeBillable=null%29',
headers: {
'cache-control': 'no-cache',
Authorization: 'NTLM NOTTHEREALTOKENKJASDKLHWKLLASBEDBSDAOBAW'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
This returns nothing. Notice the Authorization header. I've tested multiple different variants of similar. My next guess was to request through Chrome, then sniff it with Tellerik Fiddler and try to replicate the headers. I've done this as well, but to no avail. I end up with a very similar result to that above, except chrome uses negotiate:
Any ideas on how to go about this ? Maybe other debugging options?
You will need to through the 3 steps of authentication for NTLM. It's not that easy if you want to do it manually as the NTLM spec is not really open.
There's Node.js module you can use: https://www.npmjs.com/package/httpntlm (disclaimer: I created it)
To GET your url, you would need the following:
var httpntlm = require('httpntlm');
httpntlm.get({
url: "http://tfs2:8090/api/FlexPOS%20APS/odata/TimeExport%28StartDate=%272018-11-14%27,EndDate=%272018-11-14%27%20,PopulateTopParentColumns=null,GroupTimeByDateByUser=null,IncludeBillable=null%29",
username: 'your username',
password: 'your password',
workstation: 'anything',
domain: ''
}, function (err, res){
if(err) return err;
console.log(res.headers);
console.log(res.body);
});
Client side: I'm trying the create an ajax call to the routes thats supposed to pass on the user uid information to the server side. The user is signed in with firebase facebook and I used the firebase log in template to do so.
$.ajax({
url: '/meals/putMeal',
type: 'PUT',
dataType: "json",
contentType: "application/json",
data: JSON.stringify({testMeal: testMealData, userID: authData.uid}),
success:function(result){
alert(result);
}
});
Server Side, I was just checking the userID however it returned undefined. I also tested getting firebase.auth().uid on the server side and it also returned undefined. The user is definitely logged in.
router.put('/putMeal',function(req,res){
console.log(req.body);
console.log("req body is " + req.body.testMeal.Name);
console.log("the user is " + req.body.userID);
}); //CREATE
I use fetch() to send a post request for logon,
after server validation, I use req.session.account = account[0]; to save the account information to the session and return a redirect URL,
But after the redirect, the account information in the session is lost, why is that?
If you would have some example code, that would help us track down the problem. My first idea would be to make sure express-session is properly configured:
var app = express();
var session = require('express-session');
app.use(session({
secret: 'ibfiyegfiyegfe' // Secret is a required option.
}));
For futher configuration options, see the express-session repository.
EDIT: Based on the additional information, I'm guessing you have express-session configured to also use cookies for managing the sessions. What this means, is that for every HTTP request Express sends a response back that includes a cookie. jQuery based AJAX calls will ignore the response cookie however, which causes consecutive requests to Express to look as if you never logged in. To allow saving the cookie when performing AJAX requests with jQuery, use the xhrFields field to enable withCredentials:
$.ajax({
url: "http://....",
type: "POST",
xhrFields: {
withCredentials: true
},
data: {username: username, password: password},
success: function(responseBody) {
console.log("success!");
},
error: function(responseBody) {
console.log("error!");
}
});
Hope this helps.
Sorry to everyone, I don't making the question clear.
I use the fetch() method send a request to logon.
fetch('/logon', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
account: account,
password: password
})
}).then(function(response){
return response.json();
}).then(function(json){
if(json.success == 1){
window.location.href = json.redirecturl;
}else{
indexDispatcher.dispatch({
actionType: 'logonFaild',
errorInfo: json.msg
});
}
});
And the server's response is just simple JSON:
if (err) {
consoloe.log(err);
} else {
req.session.account = account[0]; //save account to session
var redirecturl = '/team/' + team[0].id;
console.log("account添加到session了");
res.json({
success: 1,
redirecturl: redirecturl
});
}
But when the client get the redirecturl and redirect, the account data is lost,so it will occur a TypeError: Cannot read property 'id' of undefined(id is saved in req.session.account).
But when I use jquery $.ajax relpace fetch, it works well. I don't know the reason.
I had the same experience like you hundreds of times which I finally found the problem. You don't need to worry if cookies enable or disable.
You just have to re-declare parts of your scripts (variables-the data which you want to display) in a if else condition.
Just redeclare the same thing using !isset and then else with the same variables mentioned twice in the if else condition, if you understand what i mean.
It will call back the same variables over and over. And make sure start session is above the page. no need to worry about headers or white lines, it has actually nothing to do with it.
I've tried it a million times. You don't need to bother using ajax etc. PHP can do almost everything. cheerio.