简体   繁体   English

Node.Js Express认证

[英]Node.Js Express Authentication

I have a simple self-made API in my Node.Js / Express app. 我的Node.Js / Express应用程序中有一个简单的自制API。 It requires authentication. 它需要认证。 My problem is that I don't want the user to have to authenticate via browser (basic authetication) if they already logged into the app using the normal means (I use passport local strategy). 我的问题是,如果用户已经使用常规方式(我使用passport本地策略)登录到应用程序,则我不希望用户通过浏览器进行身份验证(基本身份验证)。 Currently, however, it's not the case, so I wanted to ask you to help me to write it right... 但是,目前情况并非如此,因此我想请您帮助我正确编写它...

In app.js I have the following strings: 在app.js中,我有以下字符串:

var api2 = require('./routes/api2');
app.use('/api2', api2.auth);

In routes/api2.js I have: 在routes / api2.js中,我有:

exports.auth = express.basicAuth(User.authenticate);

Then when the actual request happens, processed via 然后,当实际请求发生时,通过

app.get('/api2/user/statements/:context?', api2.entries);

The user is first requested their user/password – basic authentication - via a standard browser dialog (even if they logged into the app via passport) and only then exports.entries is initiated in api2.js file. 用户第一次请求他们的用户名/密码-基本验证-通过标准的浏览器对话框(即使他们登录到通过护照上的应用程序),然后才exports.entries在api2.js文件启动。

I want that the user is requested their user/password via the browser dialog only if they haven't logged in the app via passport. 我希望仅当他们尚未通过护照登录应用程序时,才通过浏览器对话框要求用户提供用户名/密码。

Since there are Basic/Digest authentication strategies for Passport as well, you could do something like: 由于也有Passport的基本/摘要身份验证策略 ,因此您可以执行以下操作:

var passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    BasicStrategy = require('passport-http').BasicStrategy;

passport.use(new LocalStrategy(...));
passport.use(new BasicStrategy(...));

// set up your Express middlewares
// ...
app.use(passport.initialize());
// if you use passport.session(), you must have included the Express session
// middleware somewhere up above
app.use(passport.session());
// ...

// then use passport.authenticate wherever you need to protect some route(s)
// this will try the local strategy first, then basic
app.use('/api2',
        passport.authenticate(['local', 'basic']));

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

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