From 015811cbe7fea938b40a6af4a0eedcd21b68d574 Mon Sep 17 00:00:00 2001 From: Joel Cavat <jcavat@gmail.com> Date: Mon, 25 Feb 2019 12:12:50 +0100 Subject: [PATCH] Example with bearer tokens --- README.md | 6 ++++++ src/main/resources/application.conf | 1 + src/main/scala/com/example/UserRoutes.scala | 12 +++++++++--- 3 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 README.md create mode 100644 src/main/resources/application.conf diff --git a/README.md b/README.md new file mode 100644 index 0000000..a26efcc --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ + + +``` +curl -H "Authorization: Bearer ABCD" http://localhost:8080/users +``` + diff --git a/src/main/resources/application.conf b/src/main/resources/application.conf new file mode 100644 index 0000000..9deae3a --- /dev/null +++ b/src/main/resources/application.conf @@ -0,0 +1 @@ +tokens = ["ABCD", "DEFG"] \ No newline at end of file diff --git a/src/main/scala/com/example/UserRoutes.scala b/src/main/scala/com/example/UserRoutes.scala index b7de30d..1a6ff41 100644 --- a/src/main/scala/com/example/UserRoutes.scala +++ b/src/main/scala/com/example/UserRoutes.scala @@ -20,6 +20,9 @@ import com.example.UserRegistryActor._ import akka.pattern.ask import akka.util.Timeout +import com.typesafe.config.ConfigFactory +import collection.JavaConversions._ + //#user-routes-class trait UserRoutes extends JsonSupport { //#user-routes-class @@ -35,8 +38,10 @@ trait UserRoutes extends JsonSupport { // Required by the `ask` (?) method below implicit lazy val timeout = Timeout(5.seconds) // usually we'd obtain the timeout from the system's configuration + val tokens: List[String] = ConfigFactory.load().getStringList("tokens").toList + def check(credentials: Credentials): Option[String] = credentials match { - case p @ Credentials.Provided(id) if id == "john" && p.verify("p4ssw0rd") => Some(id) + case p @ Credentials.Provided(token) if tokens.exists(t => p.verify(t)) => Some(token) case _ => None } @@ -45,7 +50,8 @@ trait UserRoutes extends JsonSupport { //#users-get-delete lazy val userRoutes: Route = Route.seal { pathPrefix("users") { - authenticateBasic(realm = "secure site", check) { userName => + //authenticateBasic(realm = "secure site", check) { userName => + authenticateOAuth2(realm = "secure site", check) { token => concat( //#users-get-delete pathEnd { @@ -53,7 +59,7 @@ trait UserRoutes extends JsonSupport { get { val users: Future[Users] = (userRegistryActor ? GetUsers).mapTo[Users] - log.info(userName + " registered") + log.info(token + " registered") complete(users) }, post { -- GitLab