我在我的应用程序中设置了这样的身份验证,当提供用户名并且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
}
}
我希望在我的控制器中定义一个方法(本例中为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)
}
作为奖励问题,为什么只有UUID被添加到道具地图中,而不是实体和用户名?
对于noob因素感到抱歉,我正在尝试同时学习Scala和Play。 : - )
干杯
的Nik
答案 0 :(得分:1)
事实证明,我根本不需要使用bodysarser,request.body有一个我可以使用的asJson函数。所以我利用它来做以下事情。这项工作,我可以继续我的工作,但我仍然不太了解如何在这里获得JSON身体解析器。正在学习......; - )
def testOut = Auth.APIKey("123") { username => request =>
var props:Map[String, JsValue] = Map[String, JsValue]()
request.body.asJson match {
case None => {}
case Some(x) => {
x match {
case JsObject(fields) => { props = fields.toMap }
case _ => {} // Ok("received something else: " + request.body + '\n')
}
}
}
if(!props.contains("UUID"))
props += "UUID" -> toJson(UniqueIdGenerator.uuid)
if(!props.contains("entity"))
props += "entity" -> toJson("unset")
props += "should" -> toJson("appear")
props += "username" -> toJson(username)
Ok(props.toString)
}
答案 1 :(得分:1)
请在此处查看我对此问题的回答:Play 2.0 Framework, using a BodyParser with an authenticated request
要点是我重载了IsAuthenticated方法,将BodyParser
作为参数并使用它调用Action
。