将ActionBuilder添加到项目中,识别后检查权限

Adding ActionBuilders to a project to check permissions after identification

首先,我是 Play Framework 的新手,所以这可能是非常基础的,但我找不到足够的文档来阐明。

目前我有一个项目使用Oauth2来识别和授权用户。这是通过 ActionBuilder 完成的并且运行良好。

我现在想要的是一个附加的"layer",也就是说,授权后,检查用户是否有足够的权限(权限table存储在DB中)。

我读过有关 Action Composition 的内容,但由于我正在使用 ActionBuilder,我认为我应该能够使用它们来完成。我有 seen composeAction 函数,但我不太确定如何实现它。

我的代码,目前看起来像:

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

  def authenticate[A](block: AuthenticatedRequest[A] => Future[Result])(implicit request: Request[A]) = {
    authorize(new OauthDataHandler()) { authInfo =>
      block(AuthenticatedRequest(authInfo.user, request))
    }
  }

  object Authenticated extends api.mvc.ActionBuilder[AuthenticatedRequest]  {

    def invokeBlock[A](request: Request[A], block: AuthenticatedRequest[A] => Future[Result]) = {
      authenticate(block)(request)
    }
  }
}

我现在的尝试是这样的:

case class PermissionAuthenticatedRequest[A](user: User, zone: String, request: Request[A]) extends WrappedRequest(request)

  object PermissionAuthenticated extends api.mvc.ActionBuilder[PermissionAuthenticatedRequest] {
    def invokeBlock[A](request: Request[A], block: PermissionAuthenticatedRequest[A] => Future[Result]) = {

      checkPermissions(???/*user*/, ???/*zone*/,block)(request)
    }

    def checkPermissions[A](user: User, permission: String, block: PermissionAuthenticatedRequest[A] => Future[Result])(implicit request: Request[A]) = {
        if(user._id == 1) //silly check
          block(PermissionAuthenticatedRequest(user, permission, request)) 
        else 
          Future.successful(Forbidden)
    }
  }

但我仍然不知道如何检索用户(从其他 AuthenticatedAction)或权限(从请求)。

提前致谢。

w, scala-oauth2-provider 0.13.1 有 AuthorizedAction。 这样您就可以按如下方式进行身份验证

import scalaoauth2.provider.OAuth2ProviderActionBuilders._

object YourController extends Controller {
  def index = AuthorizedAction(new OauthDataHandler()) { req =>
    req.authInfo // you can take AuthInfo
    ...
  }
}

你只需要创建一个权限检查ActionFilter

import scalaoauth2.provider._

object PermissionActionFilter extends ActionFilter[({type L[A] = AuthInfoRequest[User, A]})#L] {

  protected def filter[A](request: AuthInfoRequest[User, A]): Future[Option[Result]] = Future.successful {
     request.authInfo.user // you can take AuthInfo
     if (user._id == 1) //silly check {
       None
     } else {
       Some(Forbidden)
     }
  }
}

你可以使用PermissionActionFilter如下

object YourController extends Controller {

  val MyAction = AuthorizedAction(new OauthDataHandler()) andThen PermissionActionFilter

  def index = MyAction { req =>
    req.authInfo // you can take AuthInfo
    ...
  }
}