我正在尝试使用passport http包保护我的 sails js rest api,但是目前我无法确定代码中的错误在哪里。我使用了这个 repo 和这个 tutorial 来了解这应该如何工作。我的问题是我的代码总是返回401。我真的不知道要在哪里寻找错误。如果您需要更多关于我的代码的信息,请评论。Bruno
编辑:我找到了问题的源头(在@Viktor的帮助下)。我只是不太理解HTTP-Basic身份验证的工作原理。现在的问题是,我如何发送我的auth凭据和数据?如果我只是测试具有auth(...)路由的路由,它们就有效...但是我如何添加数据?或者我必须先进行身份验证,然后在第二个请求中发送数据?
编辑:我找到了问题的源头(在@Viktor的帮助下)。我只是不太理解HTTP-Basic身份验证的工作原理。现在的问题是,我如何发送我的auth凭据和数据?如果我只是测试具有auth(...)路由的路由,它们就有效...但是我如何添加数据?或者我必须先进行身份验证,然后在第二个请求中发送数据?
passport.js
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
var bcrypt = require('bcrypt');
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findOne({
id: id
}, function(err, user) {
done(err, user);
});
});
passport.use('user-authentication', new BasicStrategy(
function(mail, password, done) {
sails.log.error("hallo");
User.findOne({
mail: mail
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {
message: 'Incorrect email.'
});
}
// Make sure the password is correct
bcrypt.compare(password, user.password, function(err, isMatch) {
if (err) {
return done(err);
}
// Password did not match
if (!isMatch) {
return done(null, false, {
message: 'Invalid Password'
});
}
// Success
return done(null, user);
});
});
}
));
isAuthenticated.js
var passport = require("passport");
module.exports = function (req, res, ok) {
passport.authenticate("user-authentication", {
session: false
}, function (err, user, info) {
if (err || !user) {
res.set("WWW-Authenticate", "Basic realm=\"Restricted\"");
return res.send("You are not permitted to perform this action", 401);
}
req.session.user = user;
return ok(null, user);
})(req, res, ok);
};
policies.js
module.exports.policies = {
'*': true,
'UserController': {
update: 'isAuthenticated'
}
}
UserController.test.js
var request = require('supertest');
var async = require('async');
describe('UserController', function() {
describe('#new()', function() {
it('...', function (done) {
request(sails.hooks.http.app)
.post('/user/new')
.send({ own_number: '654122', password: 'test', mail: 'test@test.com', device_id: '1234', numbers: [1234567] })
.expect(200)
.end(done);
});
});
describe('#update()', function(){
it('...', function (done) {
async.series([
function(callback){
request(sails.hooks.http.app)
.post('/contact/update')
.send({ number: 1234, mail: "test@test.com", password: "test" })
.expect(200)
.end(callback);
},
function(callback){
request(sails.hooks.http.app)
.post('/user/update')
.send({ numbers: [1234], mail: "tet@test.com", password: "test" })
.expect(200)
.end(callback);
}
], done);
});
});
});