Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple password-protection for React app on Heroku

I have a simple React app, created with create-react-app, that I'd like to deploy to Heroku (or somewhere easy) and password-protect. The protection can be really simple—just a single password is fine.

I started looking into HTTP basic auth but didn't find an easy answer. The closest I found was in this post, but (a) I don't love the idea of having to eject my app, and (b) I couldn't get it working. I was hoping I could find a Heroku plugin, but no luck there either.

It wouldn't be too hard to write a component that wraps my app and requests a password before showing it. The problem is that it executes client-side. I want to store the correct password server-side (or a hash thereof), and have the app send password attempts up to the server.

Since create-react-app operates on top of Node, I'm hoping there's an easy way to tell it to execute and store certain things on the server, but maybe I'm wrong. Any suggestions?

like image 342
Dave Feldman Avatar asked Aug 23 '18 16:08

Dave Feldman


3 Answers

If you use Node in backend you can use Passport Basic Auth

app.get('*', passport.authenticate('basic', { session: false }), (req, res) => {
  res.sendFile(path.join(`${__dirname}/../build/index.html`))
})

Every time you access the page in browser, a popup will appear, asking you username and password.

like image 64
froston Avatar answered Oct 24 '22 06:10

froston


This create-react-app buildpack seems to support http basic auth:

https://github.com/substantial/create-react-app-buildpack

https://elements.heroku.com/buildpacks/substantial/heroku-buildpack-static

like image 28
Jed Richards Avatar answered Oct 24 '22 06:10

Jed Richards


I am assuming your intentions are wanting to protect the config vars in heroku so other people cannot access you database with your credentials.

The way I password protected my deployment to heroku, is to make a keys_prod.js file containing the Heroku config vars of my mLab database in my backend using express and mongoDB:

keys_prod.js file:

module.exports = {
  mongoURI: process.env.MONGO_URI,
  secretOrKey: process.env.SECRET_OR_KEY
};

keys.js file:

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./keys_prod');
} else {
  module.exports = require('./keys_dev');
}

in my server.js file I added:

// DB Config
const db = require('./config/keys').mongoURI;

// Server static assets if in production
if (process.env.NODE_ENV === 'production') {
  // Set static folder
  app.use(express.static('client/build'));

  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
  });
}

This allows you to request the config vars you filled in heroku without including it in your repo.

like image 30
Nathan Samsoedien Avatar answered Oct 24 '22 04:10

Nathan Samsoedien