使用基本身份验证和SSL Play Framework REST

Pra*_*ash 9 scala playframework scala-collections playframework-2.0 typesafe-activator

我是这个认证领域的新手.我搜索了很多,但无法找到一种方法来验证对Play服务器的REST调用.各种方式和最佳实践有哪些?

cen*_*ntr 11

一种非常简单的方法是使用Action Composition.有关示例,请查看Guillaume Bort提供的这个Gist:https://gist.github.com/guillaumebort/2328236.如果要在异步操作中使用它,可以编写如下内容:

def BasicSecured[A](username: String, password: String)(action: Action[A]): Action[A] = Action.async(action.parser) { request =>
  request.headers.get("Authorization").flatMap { authorization =>
    authorization.split(" ").drop(1).headOption.filter { encoded =>
      new String(org.apache.commons.codec.binary.Base64.decodeBase64(encoded.getBytes)).split(":").toList match {
        case u :: p :: Nil if u == username && password == p => true
        case _ => false
      }
    }
  }.map(_ => action(request)).getOrElse {
    Future.successful(Unauthorized.withHeaders("WWW-Authenticate" -> """Basic realm="Secured Area""""))
  }
}
Run Code Online (Sandbox Code Playgroud)

SSL与基本身份验证无关.您可以直接或通过前端HTTP服务器(如ngnix)将HTTPS用于API.有关此主题的Play文档中有非常好的细节.


Did*_*ero 5

如果我们只是在谈论基本 auth,那么您不需要任何外部模块。基本上,您可以使用action composition来实现它。

是一个完整的例子。

如果您还需要授权,您可以简单地将前面的示例与Deadbolt结合起来。它将允许您提供对某些客户端组的访问权限并拒绝对其他客户端的访问权限。

SSL 支持与身份验证无关。但是,在播放文档中进行了解释


Pet*_*háč 5

基本上,我从@centr那里得到了答案并试图让它更具可读性.看看您是否更喜欢此版本的相同代码.彻底测试,按预期工作.

def BasicSecured[A](username: String, password: String)(action: Action[A]): Action[A] = Action.async(action.parser) { request =>
    val submittedCredentials: Option[List[String]] = for {
      authHeader <- request.headers.get("Authorization")
      parts <- authHeader.split(' ').drop(1).headOption
    } yield new String(decodeBase64(parts.getBytes)).split(':').toList

    submittedCredentials.collect {
      case u :: p :: Nil if u == username && p == password => action(request)
    }.getOrElse {
      Future.successful(Unauthorized.withHeaders("WWW-Authenticate" -> """Basic realm="Secured Area""""))
    }
  }
Run Code Online (Sandbox Code Playgroud)