yesod — password protecting staging site

2019-06-28 05:08发布

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.

2条回答
Deceive 欺骗
2楼-- · 2019-06-28 05:45

You could use the http auth middleware.

http://hackage.haskell.org/package/wai-extra-3.0.1/docs/Network-Wai-Middleware-HttpAuth.html

Sorry for brevity, on a mobile.

查看更多
在下西门庆
3楼-- · 2019-06-28 05:47

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:

HTTP auth browser screenshot

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.

查看更多
登录 后发表回答