Aerodynamika
Aerodynamika

Reputation: 8403

Node.Js Express Authentication

I have a simple self-made API in my Node.Js / Express app. 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). 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:

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

In routes/api2.js I have:

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.

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.

Upvotes: 0

Views: 630

Answers (1)

mscdex
mscdex

Reputation: 106698

Since there are Basic/Digest authentication strategies for Passport as well, you could do something like:

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']));

Upvotes: 1

Related Questions