yesod — password protecting staging site

寵の児 提交于 2019-12-10 17:24:25

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/24770415/yesod-password-protecting-staging-site

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!