gpt4 book ai didi

authentication - 使用koa和passport进行认证

转载 作者:行者123 更新时间:2023-12-03 19:43:06 45 4
gpt4 key购买 nike

我正在使用 koa 和 passport 尝试实现中间件,以防止在未经身份验证时访问 URI。

var koa = require('koa');
var session = require('koa-generic-session');
var bodyParser = require('koa-bodyparser');
var koaRouter = require('koa-router');
var passport = require('koa-passport');
var views = require('co-views');
var render = views('.', { map: { html: 'swig' }});
var localStrategy = require('passport-local').Strategy;

var app = koa();
var router = koaRouter();

app.keys = ['secret'];
app.use(session());
app.use(bodyParser());
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
done(null, user);
});

passport.deserializeUser(function(user, done) {
done(null, user);
});

passport.use(new localStrategy(function(username, password, done) {
if (username === 'user1' && password === 'password2') {
done(null, { userId: 99, userName: 'redBallons' });
} else {
done(null, false);
}
}));

router.get('/login', function *(next) {
this.body = yield render('index.html');
});

router.post('/login', passport.authenticate('local', {
successRedirect: '/secretBankAccount',
failureRedirect: '/login'
}));

router.get('*', function *(next) {
if (! this.isAuthenticated()) {
console.log('not authenticated');
this.redirect('/login');
} else {
console.log('authenticated');
yield next;
}
});

router.get('/secretBankAccount', function *(next) {
this.body = '2 dollars';
});

app.use(router.routes());
app.listen(8080);

但是,我永远无法访问我的 secretBankAccount。我可以输入正确的用户名和密码,并且可以看到经过身份验证的消息,但是 router.get('*') 中的 yield next 不会让我通过下一个路由功能

最佳答案

使用 koa-router 时预计只有一条路线被击中。所以当你点击 '*' route 即使您 yield next,它也不会到达另一条路线.

所以你应该用你自己的身份验证中间件替换通用路由:

app.use(function*(next) {
if (this.isAuthenticated()) {
yield next
} else {
this.redirect('/login')
}
});

身份验证中间件将强制您使用两个路由对象而不是一个来进行路由。这样您就可以区分公共(public)路由和安全路由。所以像:
var public = new koaRouter();

public.get('/login', function *(next) {
this.body = yield render('index.html');
});

public.post('/login', passport.authenticate('local', {
successRedirect: '/secretBankAccount',
failureRedirect: '/login'
}));

app.use(public.routes());

app.use(function*(next) {
if (this.isAuthenticated()) {
yield next;
} else {
this.redirect('/login');
}
})

var secured = new koaRouter();

secured.get('/secretBankAccount', function *(next) {
this.body = '2 dollars';
});

app.use(secured.routes());

在上面的示例中,请求将首先到达公共(public)路由中间件。然后,如果它与当前请求与公共(public)路由不匹配,它将移至身份验证中间件。如果 isAuthenticated()false将发生重定向。如果 isAuthenticated()true它将进入安全路由。

此方法基于 the koa-passport-example projectkoa-passport 的作者创建.

关于authentication - 使用koa和passport进行认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31879211/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com