经过身份验证的播放请求的parse.json

nik*_*ers 6 authentication json scala playframework playframework-2.0

我在我的应用程序中设置了这样的身份验证,当提供用户名并且API密钥为123时总是允许:

object Auth  {
    def IsAuthenticated(block: => String => Request[AnyContent] => Result) = {
      Security.Authenticated(RetrieveUser, HandleUnauthorized) { user =>
        Action { request =>
          block(user)(request)
        }
      }
    }

    def RetrieveUser(request: RequestHeader) = {

      val auth = new String(base64Decode(request.headers.get("AUTHORIZATION").get.replaceFirst("Basic", "")))
      val split  = auth.split(":")
      val user = split(0)
      val pass = split(1)
      Option(user)
    }

    def HandleUnauthorized(request: RequestHeader) = {
      Results.Forbidden
    }

    def APIKey(apiKey: String)(f: => String => Request[AnyContent] => Result) = IsAuthenticated { user => request =>

      if(apiKey == "123")
        f(user)(request)
      else
        Results.Forbidden
    }

}
Run Code Online (Sandbox Code Playgroud)

我想在我的控制器中定义一个方法(本例中为testOut),该方法仅将请求用作application/json.现在,在我添加身份验证之前,我会说"def testOut = Action(parse.json){...}",但现在我正在使用身份验证,如何将parse.json添加到混合和make中这项工作?

  def testOut = Auth.APIKey("123") { username => implicit request =>

    var props:Map[String, JsValue] = Map[String, JsValue]()
    request.body  match {
      case JsObject(fields) => { props = fields.toMap }
      case _ => {} // Ok("received something else: " + request.body + '\n')
    }

    if(!props.contains("UUID"))
      props.+("UUID" -> UniqueIdGenerator.uuid)

    if (!props.contains("entity"))
      props.+("entity" -> "unset")

    props.+("username" -> username)

    Ok(props.toString)
  }
Run Code Online (Sandbox Code Playgroud)

作为一个额外的问题,为什么只有UUID添加到道具地图,而不是实体和用户名?

对于noob因素感到抱歉,我正在尝试同时学习Scala和Play.:-)

干杯

nik*_*ers 1

事实证明,我根本不需要使用 bodyparser,request.body 有一个我可以使用的 asJson 函数。所以我利用这个来做以下事情。这项工作,我可以继续我的工作,但我仍然不太明白如何在这里获取 JSON 正文解析器。学习中\xe2\x80\xa6 ;-)

\n\n
def testOut = Auth.APIKey("123") { username => request =>\n\n  var props:Map[String, JsValue] = Map[String, JsValue]()\n  request.body.asJson  match {\n    case None => {}\n    case Some(x) => {\n      x match {\n        case JsObject(fields) => { props = fields.toMap }\n        case _ => {} // Ok("received something else: " + request.body + \'\\n\')\n      }\n    }\n  }\n\n  if(!props.contains("UUID"))\n    props += "UUID" -> toJson(UniqueIdGenerator.uuid)\n\n  if(!props.contains("entity"))\n    props += "entity" -> toJson("unset")\n\n  props += "should" -> toJson("appear")\n  props += "username" -> toJson(username)\n\n  Ok(props.toString)\n}\n
Run Code Online (Sandbox Code Playgroud)\n