我已经在我的应用程序中设置了这样的身份验证,当提供用户名并且 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 添加到混合中并制作这个工作?
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 添加到道具映射中,而不是实体和用户名?
对不起菜鸟因素,我正在尝试同时学习 Scala 和 Play。:-)
干杯
尼克