1

UPDATE

I think it's worth mentioning I am running Angular CLI which runs on port 4200 and my server is running on port 8080. Could this be a problem? It's the only thing I can think of at the moment

When I make a call to my route '/auth/login' I set a loggedIn property on the session object. To check a user is authenticated, a request is made to '/auth/checktoken'. In here, I check for the presence of the loggedIn property on the req.session object. When I do these requests within Postman everything works perfectly fine, but when using the browser my session.loggedIn property is undefined. I will paste the relevant code below. Thanks in advance for any help

Server Side

router.get('/checktoken', (req, res) => {
  if(!req.session.loggedIn) {
    return res.status(401).send({
      userTitle: 'Not authorised',
      userMessage: 'You are not authorised to view this'
    })
  }

  return res.status(200).send()
})

Client Side

@Injectable()
export class CheckAuthenticationService implements CanActivate {
  constructor(
    private router: Router,
    private http: HttpClient) { }

  canActivate() {
    this.http.get('http://localhost:8080/auth/checktoken', { responseType: 'text' })
      .toPromise()
      .then(() => {
        this.router.navigate(['admin']);
      })
      .catch( () => {
        this.router.navigate(['login']);
      });

    return true;
  }
}

Snippet of login code that sets the loggedIn property

if (user) {
  user.comparePassword(password, (err, isMatch) => {
    if (isMatch && isMatch) {
      req.session.loggedIn = user;
      res.status(200).send()
    } else {
      res.status(404).send({
        userTitle: 'Wrong password',
        userMessage: 'Please make sure your password is correct'
      });
      }
    });
  }

Session Store setup

app.use(session({
  name: 'jack-thomson',
  secret: SECRET_KEY,
  saveUninitialized: false,
  resave: true,
  store: new MongoStore({
    mongooseConnection: mongoose.connection
  })
}))

This all works in Postman but when hitting these endpoints on the client, .loggedIn is undefined, always

Jackthomson
  • 644
  • 8
  • 23

3 Answers3

2

I had the same problem before. I think it's about cors credential. I use Axios on React to POST data login to my Express backend application. I need to add these lines:

    import axios from 'axios';
    axios.defaults.withCredentials = true;

Then on my Express project, I add cors:

var cors = require('cors');
app.use(cors({
  credentials: true, 
  origin: 'http://localhost:3000'  // it's my React host
  })
);

Finally I can call my login function as usual, for instance:

signup(){
    var url = 'http://localhost:3210/'
    axios.post(url, {
      email: this.refs.email.value,
      username: this.refs.username.value,
      password: this.refs.password.value,
      passwordConf: this.refs.passwordConf.value
    })
    .then((x)=>{
      console.log(x);
      if(x.data.username){
        this.setState({statusSignup: `Welcome ${x.data.username}`});
      } else {
        this.setState({statusSignup: x.data});
      }
    })
    .catch((error)=>{console.log(error)})
  }

  login(){
    var url = 'http://localhost:3210/';
    var data = {
      logemail: this.refs.logemail.value,
      logpassword: this.refs.logpassword.value,
    };
    axios.post(url, data)
    .then((x)=>{
      console.log(x);
      if(x.data.username){
        this.setState({statusLogin: `Welcome ${x.data.username}`});
      } else {
        this.setState({statusLogin: x.data});
      }
    })
    .catch((error)=>{console.log(error)})
  }

And it works! Hope this solve your problem.

Lintang Wisesa
  • 619
  • 10
  • 14
1

Are you using CORS?

I had the same problem, and i solved it by putting { withCredentials: true } as optional arguments in every request. I mean whenever you send a http/https request in your service, put this as last argument, and you are good to go.

You can read this and this Stackoverflow question for more information on the topic.

Himanshu Mittal
  • 584
  • 1
  • 6
  • 21
  • I have tried that :( And yes I am using a CORS middleware in my node server – Jackthomson Oct 15 '17 at 09:40
  • Yo need to add this in every request, and following is a snippet of my middleware use, if it may help you `app.use(cors({ origin: 'http://localhost:4200', credentials: true })); app.use( session ({ name: 'connect.sid', httponly: true, secret : process.env.SESSION_KEY, resave: false, saveUninitialized: true, store: new MongoStore({ mongooseConnection: mongoose.connection }) }));` – Himanshu Mittal Oct 15 '17 at 11:10
  • Thank you man but it does not work at all :/ I'm not sure if it's to do with my server running on a different port to the angular application. The angular app is running on port 4200 and my server is running on 8080 – Jackthomson Oct 15 '17 at 11:16
  • My session id is different on every request this is why I feel it is a port issue. Postman works fine but that is working on one port – Jackthomson Oct 15 '17 at 11:17
1

I have finally figured out what is going on. My Angular CLI was running on 4200 and my server was running on a separate port. I have gotten over the issue with serving my application with express so it is all one one route. This has solved the issue for me. If anyone comes by this I hope this information comes in handy to you!

Jackthomson
  • 644
  • 8
  • 23