Code Monkey home page Code Monkey logo

Comments (8)

devt3000 avatar devt3000 commented on June 11, 2024 3

Weird, my JWT strategy isn't being executed. Maybe this is a fix?

from koa-passport.

 avatar commented on June 11, 2024 3

For those who don't like this piece of code:

router.get(
  '/users',
  passport.authenticate('jwt', { session: false }),
  auth,
  getUsers
);

You can try something like this:

const passport = require('koa-passport');

const privateRoute = (ctx, next) => {
  return passport.authenticate('jwt', { session: false }, async (err, user) => {
    if (err || !user) {
      ctx.throw(401, 'Unauthorized');
    } else {
      await ctx.login(user);
      await next();
    }
  })(ctx);
};

And then use it like this:

router.get(
  '/users',
  privateRoute,
  getUsers
);

I was trying to find such solution for 5 hours. I guess i need to leave it here, maybe it will help somebody in the future.

from koa-passport.

rkusa avatar rkusa commented on June 11, 2024 1

Hey, just to let you know, it is on my todo to look into it, I just wasn't able to find the time, yet.

from koa-passport.

rkusa avatar rkusa commented on June 11, 2024 1

I re-evaluated the change I proposed above and not think that it is not a good idea, since it basically tries to make passport.authenticate both callable as a middleware and as an inline function. The failing tests are a prove, that doing so is error-prone.

I am wondering whether your example should just be?

const auth = async (ctx, next) => {
  logger.info('startAuth')

  if (!ctx.state.user) {
    ctx.throw(401, 'Unauthorized')
  }

  logger.info('endAuth')

  await next()
}

const getUsers = async (ctx) => {
  logger.info('startGetUsers')

  const users = await User.find({})

  ctx.body = {
    payload: users
  }

  logger.info('endGetUsers')
}

router.get(
  '/users',
  passport.authenticate('jwt', { session: false }),
  auth,
  getUsers
)

from koa-passport.

Brozish avatar Brozish commented on June 11, 2024 1

Hey Markus!

Thank you very much for your response and the example given. The middleware approach worked for me!
You may close this issue.

from koa-passport.

rkusa avatar rkusa commented on June 11, 2024

First, thanks for the good issue. A good description, example, and even a blame to track down the origin of the change that introduced the behaviour 💙

I think we cannot change return next() to return because this would break using the passport.authenticate as a middleware. Instead, I'd suggest the following change f3e1708, which would allow the following usage:

const [user] = await passport.authenticate('jwt', { session: false })(ctx)

The change basically allows calling passport.authenticate without having to add a callback. In this case it now

  • forwards errors to the returned promise,
  • returnes the callback's result to the returned promise
    (not the (ctx) instead of `(ctx, next)

Please let me know if this change would work for you. (though I have to fix the tests for this change, before being able to publish them)

from koa-passport.

katlimruiz avatar katlimruiz commented on June 11, 2024

For those who don't like this piece of code:

router.get(
  '/users',
  passport.authenticate('jwt', { session: false }),
  auth,
  getUsers
);

You can try something like this:

const passport = require('koa-passport');

const privateRoute = (ctx, next) => {
  return passport.authenticate('jwt', { session: false }, async (err, user) => {
    if (err || !user) {
      ctx.throw(401, 'Unauthorized');
    } else {
      await ctx.login(user);
      await next();
    }
  })(ctx);
};

And then use it like this:

router.get(
  '/users',
  privateRoute,
  getUsers
);

I was trying to find such solution for 5 hours. I guess i need to leave it here, maybe it will help somebody in the future.

this is exactly what I've been looking for, though I dont quite get exactly what is doing (to me, this should return a middleware object, not the execution of it) ... but it works :)

from koa-passport.

ezze avatar ezze commented on June 11, 2024

@ghost, thanks a lot for sharing this solution! I was also searching for hours how to combine authenticate middleware from koa-passport and custom callbacks to return my API responses are JSON instead of plain text. Using something like

const jwtAuth = passport.authenticate('jwt', { session: false }, (error, user) => {...});
router.get('/path', jwtAuth, nextMiddleware);

prevents nextMiddleware from being called.

The following allows me both to provide a custom response and to proceed to nextMiddleware:

const jwtAuth = async(ctx, next) => {
  await passport.authenticate('jwt', { session: false }, async(error, user) => {
    if (error || !user) {
      throw Boom.unauthorized();
    }
    await next();
  })(ctx, next);
};

from koa-passport.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.