1

首先,我是 Play Framework 的新手,所以也许这是非常基本的,但我找不到足够的文档来澄清。

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

我现在想要的是一个附加的“层”,这意味着在授权后,检查用户是否有足够的权限(权限表存储在数据库中)。

我读过关于动作组合的文章,但由于我使用的是 ActionBuilder,我认为我应该能够使用它们来完成。我见过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)或权限(来自请求)。

先感谢您。

4

1 回答 1

1

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
    ...
  }
}
于 2015-03-13T20:38:27.847 回答