Search code examples
scalaplayframeworksilhouette

How to log user credentials when authentication fails with Scala Play Framework and Silhouette


I have a secured action using silhouette, something like this:

def data: Action[JsValue] = silhouette.SecuredAction(errorHandler).async(parse.json) { implicit request =>
...

I would like to log messages when user fails to authenticate. And preferably the username he/she used to authenticate with. I can't find a way to do this.


Solution

  • In the end I found that creating my own AuthProvider (or rather overriding the existing BasicAuthProvider) and adding a MarkerContext is the easiest. Like this:

    class BasicAuthProvider @Inject()(
        override protected val authInfoRepository: AuthInfoRepository,
        override protected val passwordHasherRegistry: PasswordHasherRegistry)(implicit override val executionContext: ExecutionContext)
        extends providers.BasicAuthProvider(authInfoRepository, passwordHasherRegistry)(executionContext) {
    
      /**
        * Authenticates an identity based on credentials sent in a request.
        *
        * @param request The request.
        * @tparam B The type of the body.
        * @return Some login info on successful authentication or None if the authentication was unsuccessful.
        */
      override def authenticate[B](request: Request[B]): Future[Option[LoginInfo]] = {
        getCredentials(request) match {
          case Some(credentials) =>
            val loginInfo = LoginInfo(id, credentials.identifier)
            val marker: org.slf4j.Marker =
              MarkerFactory.getMarker(loginInfo.toString)
            implicit val mc: MarkerContext = MarkerContext(marker)
    
            authenticate(loginInfo, credentials.password).map {
              case Authenticated => Some(loginInfo)
              case InvalidPassword(error) =>
                logger.warn(error)
                None
              case UnsupportedHasher(error) => throw new ConfigurationException(error)
              case NotFound(error) =>
                logger.warn(error)
                None
            }
          case None => Future.successful(None)
        }
      }
    }