我正在设计一些我希望经过身份验证的用户可以访问的API端点。 我为此任务选择了护照,我还选择了两种身份验证策略:Bearer和local。 其背后的原因是管理员用户将使用用户名和密码,而移动应用程序将提供access_token。
我面临的问题是,当我向路由添加两个身份验证策略时,我收到错误请求错误400.
我以此为例passport.js with multiple authentication providers?
下面是一个示例代码:
var express = require('express')
, passport = require('passport')
, util = require('util')
, http = require('http')
, BearerStrategy = require('passport-http-bearer').Strategy
, LocalStrategy = require('passport-local').Strategy;
var users = [
{id: 1, username: 'bob', password: 'secret', email: 'bob@example.com', token: '123'}
, {id: 2, username: 'joe', password: 'birthday', email: 'joe@example.com', token: '456'}];
function findByUsernameAndPassword(username, password, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
if (user.username === username && user.password === password) {
return fn(null, user);
}
}
return fn(null, null);
}
function findByToken(token, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
if (user.token === token) {
return fn(null, user);
}
}
return fn(null, null);
}
function findById(id, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
if (user.id === id) {
return fn(null, user);
}
}
return fn(null, null);
}
passport.use(new LocalStrategy(
function (username, password, done) {
findByUsernameAndPassword(username, password, done);
}
));
passport.use(new BearerStrategy(
function (token, done) {
findByToken(token, done);
}
));
var app = express();
app.use(passport.initialize());
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
findById(id, done);
});
app.route('/')
.get(passport.authenticate(['bearer', 'local']),
function (req, res) {
res.json({username: req.user.username, email: req.user.email});
});
var server = http.createServer(app);
server.listen(3000, function onListen(err) {
if (err) {
throw err;
}
console.log('app started on port 3000');
});
以下是我正在使用的模块的版本
"dependencies": {
"express": "^4.12.2",
"passport": "^0.2.1",
"passport-http-bearer": "^1.0.1",
"passport-local": "^1.0.0"
}
可能导致此类问题以及如何解决问题。
问候。