Thursday, January 26, 2017

Passport JS session data in Angular2

Leave a Comment

What is the best way to send passport session informations from the back end to the frontend?

My application that works on port 3000. First two gets are for facebook login and redirection. Next one is to get user data from the database (user id should be stored in req.user)

routes.js:

app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));  app.get('/auth/facebook/callback',         passport.authenticate('facebook', {             successRedirect : 'http://localhost:8000/',             failureRedirect : '/fail'         }) );  app.get('/auth/userdata', isLoggedIn, function(req, res) {     Donator.findById(req.user, function(err, fulluser) {         if (err) throw err;         res.json(fulluser);     }) });  function isLoggedIn(req, res, next) {     if (req.isAuthenticated()) {         next();     } else {         res.json(false);     } }; 

passport config.js

'facebookAuth' : {         'clientID'      : 'secret',         'clientSecret'  : 'secret',         'callbackURL'   : 'http://localhost:3000/auth/facebook/callback'     }, 

So in my Angular2 application I can go to the http://localhost:3000/auth/facebook, be redirected to the FB login page and if success redirected to the http://localhost:3000/auth/login/callback which takes me to the http://localhost:8000/.

And in my Angular2 application that works on port 8000

getUser(){     this.http.get('http://localhost:3000/auth/userdata')     .map(res => return res.json()) } 

Everytime getUser() is called, it returns 'false'. Is there a simple and safe way to "inject" this session data to my frontend on the different port? Also when I go http://localhost:3000/auth/userdata in browser I can see this profile rendered as JSON.

When I set backend and frontend on the same port It works, facebook, twitter, google, local, everything is fine and getUser returns full user profile.

I hope it's clear.

1 Answers

Answers 1

It was a problem with requests in the Angular2. I've added credentials to each request:

getUser(){     this.http.get('http://localhost:3000/auth/userdata', {withCredentials: true})     .map(res => return res.json()) } 

And now it is fine.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment