我試圖通過護照http包的幫助來保護我的風帆js rest api,但此刻我無法弄清楚錯誤在我的代碼中。 我用這個repo和這個tutorial來了解這應該如何工作。我的問題是,我的代碼總是返回一個401. 我真的不知道在哪裏尋找錯誤。如果您需要更多關於我的代碼的信息,請點評。 布魯諾Sails JS護照http 401
編輯: 我找到了問題的根源(隨着@Viktor的幫助)。我只是不太瞭解HTTP-Basic身份驗證如何工作。現在的問題是我如何發送我的認證和我的數據?如果我只使用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: '[email protected]', 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: "[email protected]", password: "test" })
.expect(200)
.end(callback);
},
function(callback){
request(sails.hooks.http.app)
.post('/user/update')
.send({ numbers: [1234], mail: "[email protected]", password: "test" })
.expect(200)
.end(callback);
}
], done);
});
});
});
嘗試使用「基本」,而不是用戶認證 –
好,不過我想我可以說出不同的策略 – Bruno
https://開頭github上。com/jaredhanson /護照-http我希望這會幫助你 –