Search code examples
authenticationhaskellcookiesservant

Haskell servant-auth cookie used via browser


I've been trying to implement cookie authentication using servant-auth and use it in my website. I followed the README on the project's GH site https://github.com/haskell-servant/servant-auth and added a simple Lucid HTML containing a form that pokes the "login" endpoint, then receives and stores the cookie in my browser.

data User = User String
    deriving (Eq, Show, Generic)

data Credentials = Credentials {
    credentialsUserName :: String,
    credentialsPassword :: String
} deriving (Eq, Show, Read, Generic)

instance ToJSON Credentials
instance ToJSON User
instance ToJWT User

instance FromJSON Credentials
instance FromJSON User
instance FromJWT User
instance FromForm Credentials

type Unprotected =
    "logMe" :> Get '[HTML] (Html ())
    :<|> "login" 
            :> ReqBody '[FormUrlEncoded] Credentials 
            :> Verb 'POST 204 '[JSON] (Headers '[ Header "Set-Cookie" SetCookie, Header "Set-Cookie" SetCookie] NoContent)

type Protected
   = "name" :> Get '[JSON] String

type AuthAPI =
    (Servant.Auth.Server.Auth '[Cookie] User :> Protected)
    :<|> Unprotected

The other parts of my code are very close to the snippets presented in README (I can post them if needed). What I have trouble with is that even with the cookie in the browser I'm still unable to access "Protected" endpoint. I get AuthResult Indefinite. I guess I'm missing a tiny part that is responsible for handling cookie to User conversion. How shall I fit it into my code ?


Solution

  • I am also struggling with the same problem, which is not solved yet link : https://github.com/DeepakKapiswe/Gyan-Lahari-Backend/blob/redisIntegration/src/App.hs

    some thing which are really painful setting up are cors and httpOnly

    recently I came across the fact that even when you set NotSecure in cookieSettings, servant-auth-server sets httpOnly flag internally here https://github.com/haskell-servant/servant-auth/blob/696fab268e21f3d757b231f0987201b539c52621/servant-auth-server/src/Servant/Auth/Server/Internal/Cookie.hs#L127

    this way cookie being httpOnly browsers does not send it back when you are testing locally over HTTP and not HTTPS

    this might be the case in your setup, otherwise you should be able to access protected endpoints after authentication.