I'm trying to set up a staging instance of my yesod webserver, and I was wondering if there were some easy way to make the entire site password protected. Specifically, I want to be able to prompt those who navigate to my site for credentials. After they authenticate it should function as the typical site. But if they cannot authenticate themselves they should see nothing.
To expand on @MichaelSnoyman's answer, here's how I implemented the WAI HTTP Auth middleware:
From the scaffolded site, I went to Application.hs
, which has already setup some logging middleware like so:
makeApplication :: AppConfig DefaultEnv Extra -> IO Application
makeApplication conf = do
foundation <- makeFoundation conf
-- Initialize the logging middleware
logWare <- mkRequestLogger def
{ outputFormat =
if development
then Detailed True
else Apache FromSocket
, destination = RequestLogger.Logger $ loggerSet $ appLogger foundation
}
-- Create the WAI application and apply middlewares
app <- toWaiAppPlain foundation
return $ logWare app
To add HTTP auth, I referenced the Yesod book's chapter on WAI and the HttpAuth docs that Michael referenced. The docs give this as an example of using the HttpAuth middleware:
basicAuth (\u p -> return $ u == "michael" && p == "mypass") "My Realm"
I was able to just paste that at the bottom right after the logging middleware is applied:
import qualified Network.Wai.Middleware.HttpAuth as HttpAuth
makeApplication :: AppConfig DefaultEnv Extra -> IO Application
makeApplication conf = do
foundation <- makeFoundation conf
-- Initialize the logging middleware
logWare <- mkRequestLogger def
{ outputFormat =
if development
then Detailed True
else Apache FromSocket
, destination = RequestLogger.Logger $ loggerSet $ appLogger foundation
}
-- Create the WAI application and apply middlewares
app <- toWaiAppPlain foundation
return $ logWare $ HttpAuth.basicAuth (\u p -> return $ u == "michael" && p == "mypass") "My Realm" $ app
Here's what that looks like in Safari:
This kind of authentication isn't really appropriate for regular users, but its great for locking down a site meant for internal use. Its also an easy way for machines (monitoring servers, scripts) to authenticate themselves with your server.
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