rkusa / koa-passport

Passport middleware for Koa
MIT License
774 stars 54 forks source link

Local strategy: ctx.state.user is undefined #98

Closed JonathanWbn closed 7 years ago

JonathanWbn commented 7 years ago

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:

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 7 years ago

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

JonathanWbn commented 7 years ago

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 7 years ago

Could you try return ctx.login(user);

JonathanWbn commented 7 years ago

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 7 years ago

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 7 years ago

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.

JonathanWbn commented 7 years ago

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.