Authentication and Authorization

Authentication and authorization are two very related, and yet separate, concepts. While the former deals with identifying a user, the latter determines what a user is allowed to do. Unfortunately, since both terms are often abbreviated as “auth,” the concepts are often conflated.

Yesod provides built-in support for a number of third-party authentication systems, such as OpenID, BrowserID and OAuth. These are systems where your application trusts some external system for validating a user’s credentials. Additionally, there is support for more commonly used username/password and email/password systems. The former route ensures simplicity for users (no new passwords to remember) and implementors (no need to deal with an entire security architecture), while the latter gives the developer more control.

On the authorization side, we are able to take advantage of REST and type-safe URLs to create simple, declarative systems. Additionally, since all authorization code is written in Haskell, you have the full flexibility of the language at your disposal.

This chapter will cover how to set up an “auth” solution in Yesod and discuss some trade-offs in the different authentication options.

Overview

The yesod-auth package provides a unified interface for a number of different authentication plugins. The only real requirement for these backends is that they identify a user based on some unique string. In OpenID, for instance, this would be the actual OpenID value. In BrowserID, it’s the email address. For HashDB (which uses a database of hashed passwords), it’s the username.

Each authentication plugin provides its own system for logging in, whether it be via passing tokens with an external site or a email/password form. After a successful login, the plugin sets a value in the user’s session to indicate his/her AuthId. This AuthId is usually a Persistent ID from a table used for keeping track of users.

There are a few functions available for querying a user’s AuthId, most commonly maybeAuthId, requireAuthId, maybeAuth and requireAuth. The require versions will redirect to a login page if the user is not logged in, while the second set of functions (the ones not ending in Id) give both the table ID and entity value.

Since all of the storage of AuthId is built on top of sessions, all of the rules from there apply. In particular, the data is stored in an encrypted, HMACed client cookie, which automatically times out after a certain configurable period of inactivity. Additionally, since there is no server-side component to sessions, logging out simply deletes the data from the session cookie; if a user reuses an older cookie value, the session will still be valid.

There are plans to add in a server-side component to sessions which would allow forced logout. This will almost certainly be implemented before a 1.0 release of Yesod.

On the flip side, authorization is handled by a few methods inside the Yesod typeclass. For every request, these methods are run to determine if access should be allowed, denied, or if the user needs to be authenticated. By default, these methods allow access for every request. Alternatively, you can implement authorization in a more ad-hoc way by adding calls to requireAuth and the like within individual handler functions, though this undermines many of the benefits of a declarative authorization system.

Authenticate Me

Let’s jump right in with an example of authentication.

  1. {-# LANGUAGE OverloadedStrings, TemplateHaskell, TypeFamilies,
  2. MultiParamTypeClasses, QuasiQuotes #-}
  3. import Yesod
  4. import Yesod.Auth
  5. import Yesod.Auth.BrowserId
  6. import Yesod.Auth.GoogleEmail
  7. import Data.Text (Text)
  8. import Network.HTTP.Conduit (Manager, newManager, def)
  9. data MyAuthSite = MyAuthSite
  10. { httpManager :: Manager
  11. }
  12. mkYesod "MyAuthSite" [parseRoutes|
  13. / RootR GET
  14. /auth AuthR Auth getAuth
  15. |]
  16. instance Yesod MyAuthSite where
  17. -- Note: In order to log in with BrowserID, you must correctly
  18. -- set your hostname here.
  19. approot = ApprootStatic "http://localhost:3000"
  20. instance YesodAuth MyAuthSite where
  21. type AuthId MyAuthSite = Text
  22. getAuthId = return . Just . credsIdent
  23. loginDest _ = RootR
  24. logoutDest _ = RootR
  25. authPlugins _ =
  26. [ authBrowserId
  27. , authGoogleEmail
  28. ]
  29. authHttpManager = httpManager
  30. instance RenderMessage MyAuthSite FormMessage where
  31. renderMessage _ _ = defaultFormMessage
  32. getRootR :: Handler RepHtml
  33. getRootR = do
  34. maid <- maybeAuthId
  35. defaultLayout [whamlet|
  36. <p>Your current auth ID: #{show maid}
  37. $maybe _ <- maid
  38. <p>
  39. <a href=@{AuthR LogoutR}>Logout
  40. $nothing
  41. <p>
  42. <a href=@{AuthR LoginR}>Go to the login page
  43. |]
  44. main :: IO ()
  45. main = do
  46. man <- newManager def
  47. warpDebug 3000 $ MyAuthSite man

We’ll start with the route declarations. First we declare our standard RootR route, and then we set up the authentication subsite. Remember that a subsite needs four parameters: the path to the subsite, the route name, the subsite name, and a function to get the subsite value. In other words, based on the line:

  1. /auth AuthR Auth getAuth

We need to have getAuth :: MyAuthSite -> Auth. While we haven’t written that function ourselves, yesod-auth provides it automatically. With other subsites (like static files), we provide configuration settings in the subsite value, and therefore need to specify the get function. In the auth subsite, we specify these settings in a separate typeclass, YesodAuth.

Why not use the subsite value? There are a number of settings we would like to give for an auth subsite, and doing so from a record type would be inconvenient. Also, since we want to have an AuthId associated type, a typeclass is more natural.On the flip side, why not use a typeclass for all subsites? It comes with a downside: you can then only have a single instance per site, disallowing serving different sets of static files from different routes. Also, the subsite value works better when we want to load data at app initialization.

So what exactly goes in this YesodAuth instance? There are six required declarations:

  • AuthId is an associated type. This is the value yesod-auth will give you when you ask if a user is logged in (via maybeAuthId or requireAuthId). In our case, we’re simply using Text, to store the raw identifier- email address in our case, as we’ll soon see.

  • getAuthId gets the actual AuthId from the Creds (credentials) data type. This type has three pieces of information: the authentication backend used (browserid or googleemail in our case), the actual identifier, and an associated list of arbitrary extra information. Each backend provides different extra information; see their docs for more information.

  • loginDest gives the route to redirect to after a successful login.

  • Likewise, logoutDest gives the route to redirect to after a logout.

  • authPlugins is a list of individual authentication backends to use. In our example, we’re using BrowserID, which logs in via Mozilla’s BrowserID system, and Google Email, which authenticates a user’s email address using their Google account. The nice thing about these two backends is:

    • They require no set up, as opposed to Facebook or OAuth, which require setting up credentials.

    • They use email addresses as identifiers, which people are comfortable with, as opposed to OpenID, which uses a URL.

  • authHttpManager gets an HTTP connection manager from the foundation type. This allow authentication backends which use HTTP connections (i.e., almost all third-party login systems) to share connections, avoiding the cost of restarting a TCP connection for each request.

In our RootR handler, we have some simple links to the login and logout pages, depending on whether or not the user is logged in. Notice how we construct these subsite links: first we give the subsite route name (AuthR), followed by the route within the subsite (LoginR and LogoutR).

The figures below show what the login process looks like from a user perspective.

Initial page load

Authentication and Authorization - 图1

BrowserID login screen

Authentication and Authorization - 图2

Homepage after logging in

Authentication and Authorization - 图3

Email

For many use cases, third-party authentication of email will be sufficient. Occassionally, you’ll want users to actual create passwords on your site. The scaffolded site does not include this setup, because:

  • In order to securely accept passwords, you need to be running over SSL. Many users are not serving their sites over SSL.

  • While the email backend properly salts and hashes passwords, a compromised database could still be problematic. Again, we make no assumptions that Yesod users are following secure deployment practices.

  • You need to have a working system for sending email. Many web servers these days are not equipped to deal with all of the spam protection measures used by mail servers.

    The example below will use the system’s built-in sendmail executable. If you would like to avoid the hassle of dealing with an email server yourself, you can use Amazon SES. There is a package called mime-mail-ses which provides a drop-in replacement for the sendmail code used below. This is the approach we use on the Haskellers.com site.

But assuming you are able to meet these demands, and you want to have a separate password login specifically for your site, Yesod offers a built-in backend. It requires quite a bit of code to set up, since it needs to store passwords securely in the database and send a number of different emails to users (verify account, password retrieval, etc.).

Let’s have a look at a site that provides email authentication, storing passwords in a Persistent SQLite database.

  1. {-# LANGUAGE OverloadedStrings, TypeFamilies, QuasiQuotes, GADTs,
  2. TemplateHaskell, MultiParamTypeClasses, FlexibleContexts #-}
  3. import Yesod
  4. import Yesod.Auth
  5. import Yesod.Auth.Email
  6. import Database.Persist.Sqlite
  7. import Database.Persist.TH
  8. import Data.Text (Text)
  9. import Network.Mail.Mime
  10. import qualified Data.Text.Lazy.Encoding
  11. import Text.Shakespeare.Text (stext)
  12. import Text.Blaze.Renderer.Utf8 (renderHtml)
  13. import Text.Hamlet (shamlet)
  14. import Data.Maybe (isJust)
  15. import Control.Monad (join)
  16. share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistUpperCase|
  17. User
  18. email Text
  19. password Text Maybe -- Password may not be set yet
  20. verkey Text Maybe -- Used for resetting passwords
  21. verified Bool
  22. UniqueUser email
  23. |]
  24. data MyEmailApp = MyEmailApp Connection
  25. mkYesod "MyEmailApp" [parseRoutes|
  26. / RootR GET
  27. /auth AuthR Auth getAuth
  28. |]
  29. instance Yesod MyEmailApp where
  30. -- Emails will include links, so be sure to include an approot so that
  31. -- the links are valid!
  32. approot = ApprootStatic "http://localhost:3000"
  33. instance RenderMessage MyEmailApp FormMessage where
  34. renderMessage _ _ = defaultFormMessage
  35. -- Set up Persistent
  36. instance YesodPersist MyEmailApp where
  37. type YesodPersistBackend MyEmailApp = SqlPersist
  38. runDB f = do
  39. MyEmailApp conn <- getYesod
  40. runSqlConn f conn
  41. instance YesodAuth MyEmailApp where
  42. type AuthId MyEmailApp = UserId
  43. loginDest _ = RootR
  44. logoutDest _ = RootR
  45. authPlugins _ = [authEmail]
  46. -- Need to find the UserId for the given email address.
  47. getAuthId creds = runDB $ do
  48. x <- insertBy $ User (credsIdent creds) Nothing Nothing False
  49. return $ Just $
  50. case x of
  51. Left (Entity userid _) -> userid -- newly added user
  52. Right userid -> userid -- existing user
  53. authHttpManager = error "Email doesn't need an HTTP manager"
  54. -- Here's all of the email-specific code
  55. instance YesodAuthEmail MyEmailApp where
  56. type AuthEmailId MyEmailApp = UserId
  57. addUnverified email verkey =
  58. runDB $ insert $ User email Nothing (Just verkey) False
  59. sendVerifyEmail email _ verurl =
  60. liftIO $ renderSendMail (emptyMail $ Address Nothing "noreply")
  61. { mailTo = [Address Nothing email]
  62. , mailHeaders =
  63. [ ("Subject", "Verify your email address")
  64. ]
  65. , mailParts = [[textPart, htmlPart]]
  66. }
  67. where
  68. textPart = Part
  69. { partType = "text/plain; charset=utf-8"
  70. , partEncoding = None
  71. , partFilename = Nothing
  72. , partContent = Data.Text.Lazy.Encoding.encodeUtf8 [stext|
  73. Please confirm your email address by clicking on the link below.
  74. \#{verurl}
  75. Thank you
  76. |]
  77. , partHeaders = []
  78. }
  79. htmlPart = Part
  80. { partType = "text/html; charset=utf-8"
  81. , partEncoding = None
  82. , partFilename = Nothing
  83. , partContent = renderHtml [shamlet|
  84. <p>Please confirm your email address by clicking on the link below.
  85. <p>
  86. <a href=#{verurl}>#{verurl}
  87. <p>Thank you
  88. |]
  89. , partHeaders = []
  90. }
  91. getVerifyKey = runDB . fmap (join . fmap userVerkey) . get
  92. setVerifyKey uid key = runDB $ update uid [UserVerkey =. Just key]
  93. verifyAccount uid = runDB $ do
  94. mu <- get uid
  95. case mu of
  96. Nothing -> return Nothing
  97. Just _ -> do
  98. update uid [UserVerified =. True]
  99. return $ Just uid
  100. getPassword = runDB . fmap (join . fmap userPassword) . get
  101. setPassword uid pass = runDB $ update uid [UserPassword =. Just pass]
  102. getEmailCreds email = runDB $ do
  103. mu <- getBy $ UniqueUser email
  104. case mu of
  105. Nothing -> return Nothing
  106. Just (Entity uid u) -> return $ Just EmailCreds
  107. { emailCredsId = uid
  108. , emailCredsAuthId = Just uid
  109. , emailCredsStatus = isJust $ userPassword u
  110. , emailCredsVerkey = userVerkey u
  111. }
  112. getEmail = runDB . fmap (fmap userEmail) . get
  113. getRootR :: Handler RepHtml
  114. getRootR = do
  115. maid <- maybeAuthId
  116. defaultLayout [whamlet|
  117. <p>Your current auth ID: #{show maid}
  118. $maybe _ <- maid
  119. <p>
  120. <a href=@{AuthR LogoutR}>Logout
  121. $nothing
  122. <p>
  123. <a href=@{AuthR LoginR}>Go to the login page
  124. |]
  125. main :: IO ()
  126. main = withSqliteConn "email.db3" $ \conn -> do
  127. runSqlConn (runMigration migrateAll) conn
  128. warpDebug 3000 $ MyEmailApp conn

Authorization

Once you can authenticate your users, you can use their credentials to authorize requests. Authorization in Yesod is simple and declarative: most of the time, you just need to add the authRoute and isAuthorized methods to your Yesod typeclass instance. Let’s see an example.

  1. {-# LANGUAGE OverloadedStrings, TemplateHaskell, TypeFamilies,
  2. MultiParamTypeClasses, QuasiQuotes #-}
  3. import Yesod
  4. import Yesod.Auth
  5. import Yesod.Auth.Dummy -- just for testing, don't use in real life!!!
  6. import Data.Text (Text)
  7. import Network.HTTP.Conduit (Manager, newManager, def)
  8. data MyAuthSite = MyAuthSite
  9. { httpManager :: Manager
  10. }
  11. mkYesod "MyAuthSite" [parseRoutes|
  12. / RootR GET POST
  13. /admin AdminR GET
  14. /auth AuthR Auth getAuth
  15. |]
  16. instance Yesod MyAuthSite where
  17. authRoute _ = Just $ AuthR LoginR
  18. -- route name, then a boolean indicating if it's a write request
  19. isAuthorized RootR True = isAdmin
  20. isAuthorized AdminR _ = isAdmin
  21. -- anyone can access other pages
  22. isAuthorized _ _ = return Authorized
  23. isAdmin = do
  24. mu <- maybeAuthId
  25. return $ case mu of
  26. Nothing -> AuthenticationRequired
  27. Just "admin" -> Authorized
  28. Just _ -> Unauthorized "You must be an admin"
  29. instance YesodAuth MyAuthSite where
  30. type AuthId MyAuthSite = Text
  31. getAuthId = return . Just . credsIdent
  32. loginDest _ = RootR
  33. logoutDest _ = RootR
  34. authPlugins _ = [authDummy]
  35. authHttpManager = httpManager
  36. instance RenderMessage MyAuthSite FormMessage where
  37. renderMessage _ _ = defaultFormMessage
  38. getRootR :: Handler RepHtml
  39. getRootR = do
  40. maid <- maybeAuthId
  41. defaultLayout [whamlet|
  42. <p>Note: Log in as "admin" to be an administrator.
  43. <p>Your current auth ID: #{show maid}
  44. $maybe _ <- maid
  45. <p>
  46. <a href=@{AuthR LogoutR}>Logout
  47. <p>
  48. <a href=@{AdminR}>Go to admin page
  49. <form method=post>
  50. Make a change (admins only)
  51. \ #
  52. <input type=submit>
  53. |]
  54. postRootR :: Handler ()
  55. postRootR = do
  56. setMessage "You made some change to the page"
  57. redirect RootR
  58. getAdminR :: Handler RepHtml
  59. getAdminR = defaultLayout [whamlet|
  60. <p>I guess you're an admin!
  61. <p>
  62. <a href=@{RootR}>Return to homepage
  63. |]
  64. main :: IO ()
  65. main = do
  66. manager <- newManager def
  67. warpDebug 3000 $ MyAuthSite manager

authRoute should be your login page, almost always AuthR LoginR. isAuthorized is a function that takes two parameters: the requested route, and whether or not the request was a “write” request. You can actually change the meaning of what a write request is using the isWriteRequest method, but the out-of-the-box version follows RESTful principles: anything but a GET, HEAD, OPTIONS or TRACE request is a write request.

What’s convenient about the body of isAuthorized is that you can run any Handler code you want. This means you can:

  • Access the filesystem (normal IO)

  • Lookup values in the database

  • Pull any session or request values you want

Using these techniques, you can develop as sophisticated an authorization system as you like, or even tie into existing systems used by your organization.

Conclusion

This chapter covered the basics of setting up user authentication, as well as how the built-in authorization functions provide a simple, declarative approach for users. While these are complicated concepts, with many approaches, Yesod should provide you with the building blocks you need to create your own customized auth solution.