Search code examples
scalaplayframeworksilhouette

Stateless Silhouette CookieAuthenticator can't find / deletes cookie


I have a Play app that allows users to log in with social providers, and have authentication set up identically to the Play-Silhouette-Slick seed example. The following code is probably fine, but I included it anyway.

def authenticate(provider: String): Action[AnyContent] = Action.async { implicit request =>
(socialProviderRegistry.get[SocialProvider](provider) match {
  case Some(provider: SocialProvider with CommonSocialProfileBuilder) =>
    provider.authenticate().flatMap {
      case Left(result) => Future.successful(result) // Redirect user to social provider
      case Right(authInfo) => for {
        profile <- provider.retrieveProfile(authInfo)
        user <- userService.save(profile)
        authInfo <- authInfoRepository.save(profile.loginInfo, authInfo)
        authenticator <- silhouette.env.authenticatorService.create(profile.loginInfo)
        cookie <- silhouette.env.authenticatorService.init(authenticator)
        result <- silhouette.env.authenticatorService.embed(cookie, Redirect(routes.EateriesController.eaterySelection()))
      } yield {
        silhouette.env.eventBus.publish(LoginEvent(user, request))
        println("Just to verify that everything went well")
        result
      }
    }
  case _ => Future.failed(new ProviderException(s"Cannot authenticate with unexpected social provider $provider"))
}).recover {
  case e: ProviderException =>
    logger.error("Unexpected provider error", e)
    Redirect(routes.SignInController.index()).flashing("error" -> Messages("could.not.authenticate"))
  }
}

My problem is that after a user logs in, my application's endpoints fail to detect that the user is logged in. When I get redirected to the page immediately after logging in, I can verify in Firefox that the authenticator cookie is set, but as soon as I navigate to another page in my app then the cookie is no longer present.

I'm guessing my app thinks that the cookie is invalid or something, and then deletes it, but I currently have no clue. Is there some other reason why this could be happening / how should I log my application to narrow down the problem?


Solution

  • I would suggest, that your cookie expired.

    You can configure this in CookieAuthenticatorSettings, which has cookieMaxAge set to None, which means the resulting cookie is transient.