Skip to content

Instantly share code, notes, and snippets.

@JoeKarlsson
Created April 27, 2016 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoeKarlsson/4908450a84e40ab0092e7b28f711ce0b to your computer and use it in GitHub Desktop.
Save JoeKarlsson/4908450a84e40ab0092e7b28f711ce0b to your computer and use it in GitHub Desktop.
Basic Authentication with Passport Via: https://gist.github.com/JoeKarlsson1/50c6cc6d389ce16556f0
var express = require('express');
var app = express();
// Passport's sole purpose is to authenticate requests, which it does through an extensible set of plugins known as strategies. Passport does not mount routes or assume any particular database schema, which maximizes flexibility and allows application-level decisions to be made by the developer.
var passport = require('passport');
// This module lets you authenticate HTTP requests using the standard basic and digest schemes in your Node.js applications.
var BasicStrategy = require('passport-http').BasicStrategy; // Want to use Basic Authentication Strategy
// Other middleware
var user = { username : 'bob', password : 'secret', email : 'bob@example.com' };
passport.use(new BasicStrategy(
function(username, password, done) {
// Example authentication strategy
if ( !(username === user.username && password === user.password) ) {
return done(null, false);
}
return done(null, user);
}));
// Protecting endpoints
app.get('/secret',
passport.authenticate('basic', { session : false }),
function(req, res) {
res.json(req.user);
});
app.listen(3000, function() {
console.log('Example app listening on port 3000');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment