Comments (8)
Weird, my JWT strategy isn't being executed. Maybe this is a fix?
from koa-passport.
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.
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.
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.
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.
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.
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.
@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)
- compatibility issue of koa-passport with apollo-server-koa 2.0
- koa-passport doesn't work with local-strategy? HOT 1
- Delegate Koa's ctx.protocol in request HOT 1
- external session storage does not work HOT 2
- The callback in ctx.login() is not being executed, "Error: Failed to serialize user into session" HOT 9
- passport.authenticate("jwt", {session: false}) will not executed. Does koa-passport support JWT strategies? HOT 1
- passport serialize user: next is not a function HOT 2
- mocking request loses original koa app instance, breaking resolving of req.subdomains, because req.app.subdomainOffset is undefined HOT 4
- Documentation | authenticate() HOT 2
- Use koa-passport without koa-session HOT 1
- Not work well with @koa/router in Typescript HOT 2
- koa-passport@next is broken! HOT 1
- Passing multiple strategies to passport.authenticate() HOT 1
- export `AuthenticateOptions` HOT 1
- Should `ctx.state.user` contains `password`? HOT 1
- Update passport to latest version HOT 2
- req.session.regenerate is not a function HOT 17
- Mix of express/koa with passport in both breaks HOT 3
- Passport authentification - LocalStrategy async/await issue
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from koa-passport.