Search code examples
scalaplayframeworktypesafe-config

Play Framework: How to read an entire configuration section consisting of unknown keys


Here below is how I'd like to configure security profiles for my Play application – each entry in auth.securityProfiles consists of an Operation => Roles pair:

auth {
    securityProfiles {
        myOperation1 = "author, auditor"
        myOperation2 = "admin"
        myOperationN = "auditor, default"
    }
}

How do I read all the entries in section auth.securityProfiles to produce a Map like this?

val securityProfiles = Map(
  "myOperation1" -> "author, auditor",
  "myOperation2" -> "admin",
  "myOperationN" -> "auditor, default"
)

Thanks.


Solution

  • Here is my solution... I've just modified the configuration like this...

    auth {
        securityProfiles = [
            {
                operation = "myOperation1"
                roles = ["author", "auditor"]
            }
            {
                operation = "myOperation2"
                roles = ["admin"]
            }
            {
                operation = "myOperationN"
                roles = ["auditor", "default"]
            }
        ]
    }
    

    ... and then read it with the following code snipper:

    import scala.collection.mutable.Map
    
    var securityProfiles = Map[String, List[String]]().withDefaultValue(List.empty)
      configuration.getConfigList("auth.securityProfiles").map { _.toList.map { config =>
        config.getString("operation").map { op =>
          securityProfiles += (op -> config.getStringList("roles").map(_.toList).getOrElse(List.empty))
      }
    }}
    

    I hope that helps.