scala - 如何通过嵌套现有指令为 Akka-Http 2 创建自定义指令?

标签 scala akka akka-http

我正在尝试创建一个自定义指令,稍后我可以使用它来验证用户角色,如下所示:

val route = put & authorize(ADMIN) { 
              // do sth
            }

val route = put {
              authorize(ADMIN) {
                //do sth
              }
            }

。这是我到目前为止所得到的:

  def authorize(role: String): Directive0 = {
    extractToken { t: String =>
      validateToken(t) {
        extractRoles(t) { roles: Seq[String] =>
          validate(roles.contains(role), s"User does not have the required role")
        }
      }
    }
  }

  def extractRoles(token: String): Directive1[Seq[String]] = {
    token match {
      case JsonWebToken(header, claimsSet, signature) => {
        val decoded = decodeJWT(token)
        decoded match {
          case Some(_) => provide(extractRoleCodesFromJWT(decoded.get))
          case None => provide(Seq())
        }
      }
      case x =>
        provide(Seq())
    }
  }

  def validateToken(token: String): Directive0 = validate(validateJWT(token), INVALID_TOKEN_MESSAGE)

  def extractToken: Directive1[Option[String]] = extractToken | extractHeader

  def extractCookie: Directive1[Option[String]] = optionalCookie(JWT_COOKIE_NAME).map(_.map(_.value))

  def extractHeader: Directive1[Option[String]] = optionalHeaderValueByName(JWT_HEADER_NAME)

除了我想稍后使用(授权)的实际 Directive0 之外,所有编译都很好。最里面的行 validate(...) 显示编译错误,指出“Server.Directive0 类型的表达式不符合预期类型 server.Route”

如何正确嵌套其他指令以形成我的授权指令? 或者我可以以其他方式连接它们,而不是嵌套? 不幸的是,有关自定义指令的文档非常少。

[更新]

感谢 Java Anto 的指点,这就是我的想法。

 def authorize(role: String): Directive0 = {
    extractToken.flatMap(validateToken)
                .flatMap(extractRoles)
                .flatMap(roles => validate(roles.contains(role), MISSING_ROLE_MESSAGE))
  }

这个可以编译,并且希望能够实现我正确测试它的技巧。

最佳答案

感谢 @Java Anto 的指点,对我有用的解决方案如下。

trait AuthorizationDirectives extends JWTService {

      val JWT_COOKIE_NAME = "jwt_cookie_name"
      val JWT_HEADER_NAME = "jwt_cookie_header"
      val INVALID_TOKEN_MESSAGE = "The provided token is not valid."
      val MISSING_ROLE_MESSAGE = "User does not have the required role."

  def authorizeRole(role: String): Directive0 = {
    extractToken.flatMap(validateToken)
      .flatMap(extractRoles)
      .flatMap(validateRole(role)(_))
  }

  def extractRoles(token: String): Directive1[String] = {
    // decode the token
    val decoded = decodeJWT(token)
    // check if decode was successful
    decoded match {
      case Some(_) => {
        // get the role string
        val rolesString = extractRoleCodesFromJWT(decoded.get)
        rolesString match {
          // return rolestring if present
          case Some(_) => provide(rolesString.get)
          case None => reject(AuthorizationFailedRejection)
        }
      }
      case None => reject(AuthorizationFailedRejection)
    }
  }

  def validateRole(role: String)(roles: String): Directive0 = {
    if (roles.contains(role))
      pass
    else
      reject(AuthorizationFailedRejection)
  }

  def validateToken(token: Option[String]): Directive1[String] = {
    token match {
      case Some(_) => validate(validateJWT(token.get), INVALID_TOKEN_MESSAGE) & provide(token.get)
      case None => reject(AuthorizationFailedRejection)
    }
  }

  def extractToken: Directive1[Option[String]] = {
    extractCookie.flatMap {
      case None => extractHeader
      case t@Some(_) => provide(t)
    }
  }

  def extractCookie: Directive1[Option[String]] = optionalCookie(JWT_COOKIE_NAME).map(_.map(_.value))

  def extractHeader: Directive1[Option[String]] = optionalHeaderValueByName(JWT_HEADER_NAME)

}

该指令可以像这样使用:

trait CRUDServiceRoute[ENTITY, UPDATE] extends BaseServiceRoute with Protocols with AuthorizationDirectives with CorsSupport {

import StatusCodes._

val requiredRoleForEdit = USER
val crudRoute: Route =
    pathEndOrSingleSlash {
      corsHandler {
        get {
          complete(getAll().map(entityToJson))
        } ~
          put {
            authorizeRole(requiredRoleForEdit) {
              entity(entityUnmarshaller) { t =>
                complete(Created -> create(t).map(idToJson))
              }
            }
          }
      }
    } ~
      pathPrefix(IntNumber) { id =>
        pathEndOrSingleSlash {
          corsHandler {
            get {
              complete(getById(id).map(entityToJson))
            }
          } ~
            corsHandler {
              put {
                authorizeRole(requiredRoleForEdit) {
                  entity(updateUnmarshaller) { tupd =>
                    complete(update(id, tupd).map(entityToJson))
                  }
                }
              }
            } ~
            delete {
              corsHandler {
                authorizeRole(requiredRoleForEdit) {
                  onSuccess(remove(id)) { ignored =>
                    complete(NoContent)
                  }
                }
              }
            }
        }
      }

  def entityToJson(value: Seq[ENTITY]): JsValue

  def entityToJson(value: Option[ENTITY]): JsValue

  def idToJson(value: Option[Long]): JsValue

  def entityUnmarshaller: FromRequestUnmarshaller[ENTITY]

  def updateUnmarshaller: FromRequestUnmarshaller[UPDATE]

  // CRUD service methods. These are implemented by the services used in the concrete routes
  def getAll(): Future[Seq[ENTITY]]

  def getById(id: Long): Future[Option[ENTITY]]

  def create(entity: ENTITY): Future[Option[Long]]

  def update(id: Long, noteUpdate: UPDATE): Future[Option[ENTITY]]

  def remove(id: Long): Future[Int]
}

关于scala - 如何通过嵌套现有指令为 Akka-Http 2 创建自定义指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34409458/

相关文章:

scala - Spark Scala了解reduceByKey(_ + _)

scala - 了解 Play 使用的是哪个 Akka 版本

scala - 您将如何 "connect"许多独立图保持它们之间的背压?

scala - 使用 akka-http 从 src/main/resources 返回一个文件

java - 使用scala问题分割以点分隔的字符串数字以分隔值

scala - 为什么我们需要 flatMap(通常)?

scala - Akka 流到 actor 问题

scala - 当子actor在未来的onFailure内抛出异常时,Akka主管actor不会处理异常

scala - 我想缩短 Akka Http 中的路由

scala - 如何从 akka Source[ByteString, _] 中提取 Future[String]?