Akka (42): Http: authentication, autorization and use of raw headers

Keywords: Scala JSON Database

When we use Akka-http as a database data exchange tool, the data is stored in Entity in the form of Source[ROW,]. In many cases, besides data, we may need to transfer additional information, such as how to deal with the data. We can transfer additional custom messages through raw-header of Akka-http, which can be achieved through raw-header filtering provided by Akka-http. On the client side, we put the additional message in the raw header of HttpRequest, as follows:

  import akka.http.scaladsl.model.headers._
  val request = HttpRequest(HttpMethods.POST,uri = s"http://localhost:8011/rows")
                   .addHeader(RawHeader("action","insert:county"))

Here the client notes that the uploaded data should be inserted into the count table. The server can obtain this information as follows:

             optionalHeaderValueByName("action") {
                case Some(action) =>
                  entity(asSourceOf[County]) { source =>
                    val futofNames: Future[List[String]] =
                      source.runFold(List[String](""))((acc, b) => acc ++ List(b.name))
                    complete(s"Received rows for $action")
                  }
                case None => complete ("No action specified!")
              }

Akka-http provides authentication and authorization through Directive of the Credential class. The client can provide its own user identity information in the following ways:

  import akka.http.scaladsl.model.headers._
  val request = HttpRequest(HttpMethods.POST,uri = s"http://localhost:8011/rows")
    .addHeader(RawHeader("action","insert:county"))
    .addCredentials(BasicHttpCredentials("john", "p4ssw0rd"))

The authentication processing method of the server to the client is as follows:

  import akka.http.scaladsl.server.directives.Credentials
  def myUserPassAuthenticator(credentials: Credentials): Future[Option[User]] = {
    implicit val blockingDispatcher = httpSys.dispatchers.lookup("akka-httpblocking-ops-dispatcher")
    credentials match {
      case p @ Credentials.Provided(id) =>
        Future {
          // potentially
          if (p.verify("p4ssw0rd")) Some(User(id))
          else None
        }
      case _ => Future.successful(None)
    }
  }

  case class User(name: String)
  val validUsers = Set("john","peter","tiger","susan")
  def hasAdminPermissions(user: User): Future[Boolean] = {
    implicit val blockingDispatcher = httpSys.dispatchers.lookup("akka-httpblocking-ops-dispatcher")
    Future.successful(validUsers.contains(user.name))
  }

The following is how Credential-Directive is used:

         authenticateBasicAsync(realm = "secure site", userPassAuthenticator) { user =>
            authorizeAsync(_ => hasPermissions(user)) {
              withoutSizeLimit {
                handleExceptions(postExceptionHandler) {
                  optionalHeaderValueByName("action") {
                    case Some(action) =>
                      entity(asSourceOf[County]) { source =>
                        val futofNames: Future[List[String]] =
                          source.runFold(List[String](""))((acc, b) => acc ++ List(b.name))
                        complete(s"Received rows for $action sent from $user")
                      }
                    case None => complete(s"$user did not specify action for uploaded rows!")
                  }
                }
              }
            }
          }

The following is a demonstration code for this discussion:

Client:

import akka.actor._
import akka.stream._
import akka.stream.scaladsl._
import akka.http.scaladsl.Http
import scala.util._
import akka._
import akka.http.scaladsl.common._
import spray.json.DefaultJsonProtocol
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.common.EntityStreamingSupport
import akka.http.scaladsl.model._
import spray.json._

trait MyFormats extends SprayJsonSupport with DefaultJsonProtocol
object Converters extends MyFormats {
  case class County(id: Int, name: String)
  implicit val countyFormat = jsonFormat2(County)
}

object HttpClientDemo extends App {
  import Converters._

  implicit val sys = ActorSystem("ClientSys")
  implicit val mat = ActorMaterializer()
  implicit val ec = sys.dispatcher

  implicit val jsonStreamingSupport: JsonEntityStreamingSupport = EntityStreamingSupport.json()

  import akka.util.ByteString
  import akka.http.scaladsl.model.HttpEntity.limitableByteSource

  val source: Source[County,NotUsed] = Source(1 to 5).map {i => County(i, s"Number of prefectures, cities and counties in Guangxi Zhuang Autonomous Region #$i")}
  def countyToByteString(c: County) = {
    ByteString(c.toJson.toString)
  }
  val flowCountyToByteString : Flow[County,ByteString,NotUsed] = Flow.fromFunction(countyToByteString)

  val rowBytes = limitableByteSource(source via flowCountyToByteString)

  import akka.http.scaladsl.model.headers._
  val request = HttpRequest(HttpMethods.POST,uri = s"http://localhost:8011/rows")
    .addHeader(RawHeader("action","insert:county"))
    .addCredentials(BasicHttpCredentials("john", "p4ssw0rd"))

  val data = HttpEntity(
    ContentTypes.`application/json`,
    rowBytes
  )

  def uploadRows(request: HttpRequest, dataEntity: RequestEntity) = {
    val futResp = Http(sys).singleRequest(
      request.copy(entity = dataEntity)
    )
    futResp
      .andThen {
        case Success(r@HttpResponse(StatusCodes.OK, _, entity, _)) =>
          entity.dataBytes.map(_.utf8String).runForeach(println)
        case Success(r@HttpResponse(code, _, _, _)) =>
          println(s"Upload request failed, response code: $code")
          r.discardEntityBytes()
        case Success(_) => println("Unable to Upload file!")
        case Failure(err) => println(s"Upload failed: ${err.getMessage}")

      }
  }


  uploadRows(request,data)

  scala.io.StdIn.readLine()

  sys.terminate()

}

Server:

import akka.actor._
import akka.stream._
import akka.stream.scaladsl._
import akka.http.scaladsl.Http
import akka._
import akka.http.scaladsl.common._
import spray.json.DefaultJsonProtocol
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import scala.concurrent._
import akka.http.scaladsl.server._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.model._

trait MyFormats extends SprayJsonSupport with DefaultJsonProtocol
object Converters extends MyFormats {
  case class County(id: Int, name: String)
  val source: Source[County, NotUsed] = Source(1 to 5).map { i => County(i, s"Regional Number of Guangdong Province, China #$i") }
  implicit val countyFormat = jsonFormat2(County)
}

object HttpServerDemo extends App {

  import Converters._

  implicit val httpSys = ActorSystem("httpSystem")
  implicit val httpMat = ActorMaterializer()
  implicit val httpEC = httpSys.dispatcher


  implicit val jsonStreamingSupport = EntityStreamingSupport.json()
    .withParallelMarshalling(parallelism = 8, unordered = false)

  def postExceptionHandler: ExceptionHandler =
    ExceptionHandler {
      case _: RuntimeException =>
        extractRequest { req =>
          req.discardEntityBytes()
          complete((StatusCodes.InternalServerError.intValue, "Upload Failed!"))
        }
    }

  import akka.http.scaladsl.server.directives.Credentials
  def userPassAuthenticator(credentials: Credentials): Future[Option[User]] = {
    implicit val blockingDispatcher = httpSys.dispatchers.lookup("akka-httpblocking-ops-dispatcher")
    credentials match {
      case p @ Credentials.Provided(id) =>
        Future {
          // potentially
          if (p.verify("p4ssw0rd")) Some(User(id))
          else None
        }
      case _ => Future.successful(None)
    }
  }

  case class User(name: String)
  val validUsers = Set("john","peter","tiger","susan")
  def hasPermissions(user: User): Future[Boolean] = {
    implicit val blockingDispatcher = httpSys.dispatchers.lookup("akka-httpblocking-ops-dispatcher")
    Future.successful(validUsers.contains(user.name))
  }

  val route =
    path("rows") {
      get {
        complete {
          source
        }
      } ~
        post {
          authenticateBasicAsync(realm = "secure site", userPassAuthenticator) { user =>
            authorizeAsync(_ => hasPermissions(user)) {
              withoutSizeLimit {
                handleExceptions(postExceptionHandler) {
                  optionalHeaderValueByName("action") {
                    case Some(action) =>
                      entity(asSourceOf[County]) { source =>
                        val futofNames: Future[List[String]] =
                          source.runFold(List[String](""))((acc, b) => acc ++ List(b.name))
                        complete(s"Received rows for $action sent from $user")
                      }
                    case None => complete(s"$user did not specify action for uploaded rows!")
                  }
                }
              }
            }
          }
        }
    }

  val (port, host) = (8011,"localhost")

  val bindingFuture = Http().bindAndHandle(route,host,port)

  println(s"Server running at $host $port. Press any key to exit ...")

  scala.io.StdIn.readLine()

  bindingFuture.flatMap(_.unbind())
    .onComplete(_ => httpSys.terminate())

}

Posted by lordvader on Fri, 08 Feb 2019 02:33:17 -0800