gpt4 book ai didi

javascript - Passport 和 express 的基本认证

转载 作者:行者123 更新时间:2023-11-30 12:08:59 24 4
gpt4 key购买 nike

我一定错过了什么,但根据我找到的所有教程,这就是使用 expresspassport 对 Node 应用程序进行基本身份验证的方式 + 本地 Passport 。我知道这不符合最佳实践,我只是想让 POC 继续:

'use strict'

var express = require('express');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy

var app = express();

var users = { 'user': 'secretpass'};

passport.use(new LocalStrategy(
function(username, password, done) {
console.log('Username:', username, 'password:', password);
if (!users[username] || users[username] != password) {
console.log('Username:', username, 'password:', password);
return done (null, false);
}
return done(null, {username: username});
}
));

app.use(passport.initialize());


app.get('/', function (req, res) {
res.send ('GET request to root');
});

app.post('/', function (req, res) {
res.send ('POST request to root');
});

app.get('/unauthorized', function (req, res) {
res.status(200).send('GET Forbidden');
});

app.post('/unauthorized', function (req, res) {
res.status(200).send('Post Forbidden');
});

app.post('/webhook',
passport.authenticate('local', { successRedirect: '/', failureRedirect: '/unauthorized'}),
function (req, res) {
res.send ('authenticated!');
}
);

var server = app.listen(8081, function() {
console.log('Server listening at', server.address().address, 'on port', server.address().port);
});

奇怪的是,我什至没有让 LocalStrategy 构造函数中的那些 console.log() 语句向我显示任何内容,所以我猜我真的只是错过了一些东西。我尝试使用 DHC 和 Postman 发送 POST 请求,

  • 将基本身份验证字段设置为用户名和密码,
  • 使用用户名:密码@url 格式的方法,
  • 将用户名和密码作为表单数据发送

最佳答案

对于基本身份验证,您需要 passport-http ,而不是 passport-local(用于通过表单数据进行身份验证)。

试试这个:

var BasicStrategy = require('passport-http').BasicStrategy;
...
passport.use(new BasicStrategy(...));
...
app.post('/webhook',
passport.authenticate('basic', {
session : false,
successRedirect : '/',
failureRedirect : '/unauthorized'
}), function (req, res) {
// FWIW, this isn't useful because it's never reached, because Passport
// will always issue a redirect (either to / or to /unauthorized)
res.send ('authenticated!');
}
);

关于javascript - Passport 和 express 的基本认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34378937/

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