Parse.json authenticated request to the game

I set authentication in my application, like this, always allow when the username is provided, and the API key is 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 } } 

Then I want to define a method in my controller (testOut in this case) that uses the request only as application / json. Now, before adding authentication, I would say: "def testOut = Action (parse.json) {...}", but now when I use authentication, how can I add parse.json to mix and make this work?

  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) } 

As a bonus question, why only the UUID is added to the props, and not the entity and username?

Sorry for the noob factor, I'm trying to learn Scala and play at the same time. :-)

Greetings

Nick

+6
source share
2 answers

Turns out I don't need to use bodyparser at all, request.body has an asson function that I can use. So I used this to do the following. This work, and I can continue my work, but I still do not quite understand how to get the JSON parser. Studying in progress ...; -)

 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
source

See my answer to this question here: Play 2.0 Framework using BodyParser with authenticated request

The bottom line is that I overloaded the IsAuthenticated method to take BodyParser as a parameter and call Action with it.

+1
source

Source: https://habr.com/ru/post/912651/


All Articles