Is there an optional authentication middleware from Passport.js?
Let's say I have a route, /api/users
. I want to give just a list of users to the public, but to authenticated people, I want to add more fields.
Currently I have just a dumb custom method that does the same thing, but I wonder if:
My method, roughly, looks like
function optionalAuth(req, res, next) {
var authHeader = req.headers.authorization;
var token = parseToken(authHeader); // just getting the OAuth token here
if(!token) {
return next();
}
User.findOne({
token: token
}, function(err, user) {
if(err) {
return res.json(401, {message: 'auth expired'});
};
if(user) {
req.user = user;
}
next();
});
}
This, however, seems dumb to me, and also not in passport-auth-strategies.js or some other auth layer where I think it should be. What is the better way to do it?
Bonus points for telling me if I'm doing the proper thing returning 401 if I find a token but it's invalid :)
Passport is authentication middleware for Node. js. As it's extremely flexible and modular, Passport can be unobtrusively dropped into any Express-based web application. A comprehensive set of strategies supports authentication using a username and password, Facebook, Twitter, and more.
Strategies are responsible for authenticating requests, which they accomplish by implementing an authentication mechanism. Authentication mechanisms define how to encode a credential, such as a password or an assertion from an identity provider (IdP), in a request.
JSON Web Token is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed; Passport: Simple, unobtrusive authentication for Node. js.
Passport is a popular, modular authentication middleware for Node. js applications. With it, authentication can be easily integrated into any Node- and Express-based app. The Passport library provides more than 500 authentication mechanisms, including OAuth, JWT, and simple username and password based authentication.
Might be late now, but there's an anonymous
Passport strategy to allow exactly this. That way the public routes can either take authentication or not, but when they do you'll still have all of the information associated with the authenticated user. Check it out here: https://github.com/jaredhanson/passport-anonymous
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With