繁体   English   中英

基本认证与护照和快递

[英]Basic auth with passport and express

我一定错过了一些东西,但根据我发现的所有教程,这就是你使用expresspassport + passport-local对节点应用程序进行基本身份验证的方法。 我知道这不符合最佳实践,我只是想让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请求,

  • 将基本auth字段设置为用户名和密码,
  • 使用username:password @ 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!');
  }
);

使用passport-http模块进行基本身份验证

var express = require('express');
var passport = require('passport');
var app = express();
var BasicStrategy = require('passport-http').BasicStrategy;
passport.use(new BasicStrategy(
   function (username, password, done) {
      //perform auth here for user.
      //use done(null,false) if auth fails

      done(null, {
         user: "xyz"
      });


   }
));

app.get('/app', passport.authenticate('basic', {
   session: false
}), (req, res) => {
   console.log("Hello");

   res.send('ok');
});

app.listen(4000, (err, res) => {
   console.log(err, res);
   console.log('server is launched');
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM