node.js - PassportJS req.user undefined when authentification from an android app -
node.js - PassportJS req.user undefined when authentification from an android app -
i'm developing api in nodejs, authentification part i'm using passportjs. i'm using tutorial: http://scotch.io/tutorials/javascript/easy-node-authentication-setup-and-local
in browser, it's ok user when seek android app, req.user undefined.
app.post('/login', passport.authenticate('local-login', { successredirect: '/loginsuccess', failureredirect: '/loginfailure', failureflash : true // allow flash messages })); app.get('/loginfailure', function(req, res, next) { res.setheader('content-type', 'application/json'); res.json({user: req.user, message: req.flash('loginmessage')[0]}); }); app.get('/loginsuccess', function(req, res, next) { console.log(req.user); res.setheader('content-type', 'application/json'); res.json({user: req.user, message: "test"}); });
//
passport.use('local-login', new localstrategy({ usernamefield : 'login', passwordfield : 'password', passreqtocallback : true // allows pass in req our route (lets check if user logged in or not) }, function(req, login, password, done) { // asynchronous process.nexttick(function() { user.findone({$or:[{'local.email': login.tolowercase()}, {'local.login': login}]}, function(err, user) { // if there errors, homecoming error if (err) homecoming done(err); // if no user found, homecoming message if (!user) homecoming done(null, false, req.flash('loginmessage', 'no user found.')); if (!user.validpassword(password)) homecoming done(null, false, req.flash('loginmessage', 'oops! wrong password.')); // well, homecoming user else homecoming done(null, user); }); }); }));
and android code:
public class loginactivity extends activity { private button loginbutton = null; private button cancelbutton = null; private boolean isonline() { connectivitymanager cm = (connectivitymanager) getsystemservice(appinfo.getappcontext().connectivity_service); networkinfo netinfo = cm.getactivenetworkinfo(); if (netinfo != null && netinfo.isconnectedorconnecting()) { homecoming true; } homecoming false; } private onclicklistener clicklistenerloginbutton = new onclicklistener() { @override public void onclick(view v) { if (!isonline()) { toast.maketext(loginactivity.this, getresources().getstring(r.string.error_no_network), toast.length_long).show(); homecoming ; } new loginoperation().execute(getresources().getstring(r.string.urllogin)); } }; private onclicklistener clicklistenercancelbutton = new onclicklistener() { @override public void onclick(view v) { intent result = new intent(); setresult(result_canceled, result); finish(); } }; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_login); loginbutton = (button)findviewbyid(r.id.loginbutton); cancelbutton = (button)findviewbyid(r.id.cancelbutton); loginbutton.setonclicklistener(clicklistenerloginbutton); cancelbutton.setonclicklistener(clicklistenercancelbutton); } private object user; private class loginoperation extends asynctask<string, void, void> { string response = ""; string error = null; string info =""; private progressdialog dialog = new progressdialog(loginactivity.this); edittext login_emailedittext = (edittext) findviewbyid(r.id.login_emailedittext); edittext passwordedittext = (edittext) findviewbyid(r.id.passwordedittext); protected void onpreexecute() { dialog.setmessage("please wait.."); dialog.show(); try{ info += "&"+urlencoder.encode("login", "utf-8")+ "=" +urlencoder.encode(login_emailedittext.gettext().tostring(), "utf-8"); info += "&"+urlencoder.encode("password", "utf-8")+ "=" +urlencoder.encode(passwordedittext.gettext().tostring(), "utf-8"); } grab (unsupportedencodingexception e) { e.printstacktrace(); } } @override protected void doinbackground(string... urls) { bufferedreader reader=null; seek { url url = new url(urls[0]); // send post info request urlconnection conn = url.openconnection(); conn.setdooutput(true); outputstreamwriter wr = new outputstreamwriter(conn.getoutputstream()); wr.write( info ); wr.flush(); // server response reader = new bufferedreader(new inputstreamreader(conn.getinputstream())); stringbuilder sb = new stringbuilder(); string line = null; // read server response while((line = reader.readline()) != null) { sb.append(line + " "); } // append server response content string response = sb.tostring(); } catch(exception ex) { error = ex.getmessage(); } { seek { reader.close(); } catch(exception ex) {} } homecoming null; } protected void onpostexecute(void unused) { dialog.dismiss(); if (error != null) { toast.maketext(loginactivity.this, "errorandroid: " + error, toast.length_long).show(); } else { seek { jsonobject jsonobject = new jsonobject(response); toast.maketext(loginactivity.this, jsonobject.tostring(), toast.length_long).show(); user = jsonobject.get("user"); } grab (jsonexception e) { toast.maketext(loginactivity.this, "errorandroidjson: " + e.getmessage(), toast.length_long).show(); } } } } }
and seek browser: user1/password1
http://exemple.com:4040/login
i'm using express4.0 tried express3.8. i'm totally lost, don't understand @ why work browser not app.
edit: think problem come way phone call api in android, http header request should different browser it's not working good.
thanks help.
you expressjs server returning "302 moved temporarily
"
http/1.1 302 moved temporarily x-powered-by: express access-control-allow-origin: * access-control-allow-headers: content-type access-control-allow-credentials: true access-control-allow-methods: post, get, put, delete, options location: /loginsuccess vary: take content-type: text/html; charset=utf-8 content-length: 82 date: wed, 08 oct 2014 23:29:31 gmt connection: keep-alive
with "location"
set /loginsuccess
;
android urlconnection
default automatically follows redirect, , fetching info returned /loginsuccess
the problem is, expressjs server requires send cookie set;
so solution
disable automatic redirect; add together below line after initial url.openconnection()
((httpurlconnection)conn).setinstancefollowredirects(false);
manually follow url redirect, cookie
value set in request. add together below code snippet after wr.flush();
line
string cookie = conn.getheaderfield("set-cookie"); conn = new url("http://example.com:4040/loginsuccess").openconnection(); conn.setrequestproperty("cookie", cookie); conn.connect();
consider replacing hardcoded url above "baseurl + conn.getheaderfield("location")"
android node.js express passport.js passport-local
Comments
Post a Comment