rkusa/koa-passport

Local strategy: ctx.state.user is undefined

JonathanWbn opened this issue · 7 comments

I am trying to set up local authentication for my react app. Since I would like to handle the routing on the client side, I am not redirecting via passport.
My flow would look like this:

  • POST request from the client with email and password
  • GET request from the client to fetch user data

I have set it up like this:

router.post('/login/local', passport.authenticate('local-login', function(err, user, info) {
    if (err) // handle error
    else if (!user && info) // handle no user
    else {
      // handle successful login
      ctx.login(user);
    }
  }));

That works fine and I send back the response to the client. But when I send another request from the client to access the user data, there is no user data attached to the request:

router.get('/profile', (ctx) => {
    // ctx.state.user is undefined
}

What am I missing here? Is this not how it should work?

rkusa commented

Are you calling the middleware passport.session() and also have a session middleware setup (e.g. koa-generic-session)?

Yes, I am setting it up like in the example:

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const router = require('./routes.js');
const cors = require('koa-cors');
const convert = require('koa-convert');
const session = require('koa-generic-session');
const passport = require('koa-passport');
const MongoStore = require('koa-generic-session-mongo');

const nconf = require('./env/nconf');

const app =  new Koa();

app.keys = [nconf.get('APP_KEYS')];

require('./auth');

app
  .use(cors())
  .use(bodyParser())
  .use(convert(session()))
  .use(passport.initialize())
  .use(passport.session())
  .use(router.routes())
  .use(router.allowedMethods())
rkusa commented

Could you try return ctx.login(user);

I tried it, still the same issue.
I can see the session.state.user being created when ctx.login(user) gets called. But the session is empty when the next request comes in.

rkusa commented

Could you inspect the requests in your browser's dev tools and check whether the response to the POST request contains a Set-Cookie header and the following GET request (for the user data) contains the corresponding Cookie header?

rkusa commented

Since you are using the CORS middleware, does the GET request for fetching the user information come from another host? If so, you may need to adjust the credentials option of the fetch API.

Yes! That's exactly it. I had to allow sending cookies on the fetch and in koa-cors.
Thank you so much, really appreciate it.