How to authenticate a http header in Akka http 1.0 RC4

112 views
Skip to first unread message

Shing

unread,
Jul 4, 2015, 7:18:19 AM7/4/15
to akka...@googlegroups.com

Hi,

  In Spray, I can validate a http header X-Token using the following code.


  def routes: Route = post {

    headerValueByName("X-Token") {
      token =>
        authenticate(validate(token)) {
          user => {
            respondWithMediaType(`application/json`) {
              complete {
                """"msg":"successful""""
              }
            }
          }
        }
    }
  }

  def validate(token: String): Future[Authentication[String]] = {
    Future {
      token match {
        case "foo" => Right("foo")
        case _ => Left(AuthenticationFailedRejection(CredentialsRejected, List()))
      }
    }


How to do the above in Akka http (1.0 RC4) ?

Below is my attempt which works. Is there a more elegant solution ?


trait AuthDemoApp {
  implicit val system = ActorSystem("authDemo")
  sys.addShutdownHook({
    system.shutdown()
  })

  implicit val materializer = ActorMaterializer()
  import system.dispatcher


  def check(requestCxt: RequestContext): Boolean = {
    val tokenOpt: Option[HttpHeader] = requestCxt.request.getHeader("X-Token")
    println("Token=" + tokenOpt)
    tokenOpt.map(_.value == "foo").getOrElse(false)
  }

  val route: Route =
    post {
      authorize(check _) {
        headerValueByName("X-Token") {
          token =>
            complete {
              s""""msg":"successful. token=$token""""
            }
        }

      }
    }
  // Starts a server listening at http://localhost:8080
  val binding: Future[ServerBinding] = Http().bindAndHandle(handler = route, interface = "localhost", port = 8080)

  binding.onSuccess {
    case _ => println("Started server ----")
  }

}



Thanks in advance for any suggestions !


Shing





Reply all
Reply to author
Forward
0 new messages