我正在尝试为安全性创建自定义操作。我正在使用Scala Oauth 用于处理我的应用程序中的安全性并尝试创建自定义操作并将Scala Oauth安全性包装在我的自定义操作中。根据Play Framework文档,我使用两种方式来包装请求对象,但遗憾的是,我没有在自定义Action处理程序中获取自定义Request对象。以下是方法:
case class AuthRequest[A](user: User, request: Request[A]) extends WrappedRequest[A](request)
第一种方式
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)
}
第二种方式
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"))
}
}
根据两种方式,当我尝试在我的自定义处理程序中使用user
对象时,我得到以下编译时错误:
value user is not a member of play.api.mvc.Request[play.api.mvc.AnyContent]
val user = request.user
以下是我的处理程序代码:
def testCustomAction = SecurityAction { request =>
val user = request.user
Future.successful(Ok("Apna To Chal Gya"))
}
答案 0 :(得分:0)
在上面的代码中有一个简单的问题。我在play.api.mvc.Request
方法中使用invokeBlock
而不是AuthRequest
。请找到以下代码进行更正。
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)
}