繁体   English   中英

基于Play(Scala)中的JSON令牌授权的自定义操作组合

[英]Custom Action composition to authorize based on JSON token in Play (Scala)

与大多数有关Action组成的讨论(例如讨论)不同,我需要在Action中解析传入的JSON请求。 这是因为我们的应用程序提供了嵌入在JSON中的安全令牌(通常不包含在标头中)。

我想要实现的是:

object AuthenticatedAction extends ActionBuilder[UserRequest] with ActionTransformer[Request, UserRequest] {
    // Do something magical here that will:
    // 1. parse the inbound request.body.validate[GPToken]
    // 2. (do stuff with the token to check authorization)
    // 3. if NOT authorized return an HTTP NOTAUTHORIZED or FORBIDDEN
    // 4. otherwise, forward the request to the desired endpoint
}

object SomeController extends Controller
    val action = AuthenticatedAction(parse.json) { implicit request =>
        request.body.validate[SomeRequest] match {
            // Do whatever... totally transparent and already authorized
        }
    }
    ...

入站JSON将始终具有令牌,例如:

{
    "token":"af75e4ad7564cfde",
    // other parameters we don't care about
}

因此,我正在考虑仅希望我们解析(而不是解析复杂的,深层嵌套的JSON结构),我可能只有一个GPToken对象:

class GPToken(token: String)
object GPToken { implicit val readsToken = Json.reads[GPToken] }

然后,在AuthenticationAction的“魔术”中,我可以反序列化令牌,对数据库执行检查授权的工作,然后将请求传递或发回NOTAUTHORIZED。 但这就是我迷路的地方...我该如何获取json正文,对其进行解析并通过我的安全层过滤所有传入的请求?

我认为将令牌移至您的请求标头会更好。 这样做将允许您使用Play的AuthententicatedBuilder,它是一个ActionBuilder来帮助进行身份验证。

如果可以这样做,那么您可能会具有如下特征:

trait Authentication {
  object Authenticated extends play.api.mvc.Security.AuthenticatedBuilder(checkGPToken(_), onUnauthorized(_))

  def checkGPToken(request: RequestHeader): Option[User] = {
    request.headers.get("GPToken") flatMap { token =>
      // Do the check with the token
      // Return something about the user that will be available inside your actions
    }
  }

  def onUnauthorized(request: RequestHeader) = {
    // Do something when it doesn't pass authorization
    Results.Unauthorized
  }
}

现在,使用控制器,您可以轻松地创建需要身份验证的操作。

object SomeController extends Controller with Authentication {
    def someAction = Authenticated { req =>
      // Your user your header check is available
      val user = req.user
      // Do something in the context of being authenticated
      Ok
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM