Play Framework 2.3.x: Wrap Request object using Scala Oauth in Play Framework

I am trying to create a custom security action. I am using Scala Oauth to handle security in my application and trying to create a custom action and wrap Scala Oauth in my custom action. According to the documentation for the Play Framework, I use two methods for a wrapped request object, but, unfortunately, I do not get my custom request object in a user action handler. The following are the ways:

case class AuthRequest[A](user: User, request: Request[A]) extends WrappedRequest[A](request) 

First way

 case class CustomSecurityAction[A](action: Action[A]) extends Action[A] with OAuth2Provider{ def apply(request: Request[A]): Future[Result] = { implicit val executionContext: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext request.headers.get("Host").map { host => authorize(new SecurityDataHandler(host)) { authInfo => action(AuthRequest(authInfo.user, request)) }(request, executionContext) } getOrElse { Future.successful(Unauthorized("401 No user\n")) }} lazy val parser = action.parser } object SecurityAction extends ActionBuilder[Request] with OAuth2Provider { def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = { block(request) } override def composeAction[A](action: Action[A]) = new CustomSecurityAction(action) } 

Second way

 object SecurityAction extends ActionBuilder[Request] with OAuth2Provider { def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = { implicit val executionContext: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext request.headers.get("Host").map { host => authorize(new SecurityDataHandler(host)) { authInfo => block(AuthRequest(authInfo.user, request)) }(request, executionContext) } getOrElse { Future.successful(Unauthorized("401 No user\n")) } } 

In both cases, when I try to use the user object in my user exit, I get the following compile time error:

 value user is not a member of play.api.mvc.Request[play.api.mvc.AnyContent] val user = request.user 

The following is the code for my handler:

 def testCustomAction = SecurityAction { request => val user = request.user Future.successful(Ok("Apna To Chal Gya")) } 
0
source share
1 answer

There is a simple problem in the code above. I use play.api.mvc.Request in invokeBlock instead of AuthRequest . Below is the code to fix it.

 object SecurityAction extends ActionBuilder[AuthRequest] { override def invokeBlock[A](request: Request[A], block: (AuthRequest[A]) => Future[Result]) = { request match { case re: AuthRequest[A] => block(re) case _ => Future.successful(Results.Unauthorized("401 No user\n")) } } override def composeAction[A](action: Action[A]) = CustomSecurityAction(action) } 
0
source

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


All Articles