我有一个项目,其中的控制器需要身份验证,而控制器不需要身份验证。
我已经实现了有关动作组成here的文档,所以我将UserAction
注入到每个需要身份验证的控制器中
class UserRequest[A](val user: Option[String], request: Request[A]) extends WrappedRequest[A](request)
class UserAction @Inject()(val parser: BodyParsers.Default)(implicit val executionContext: ExecutionContext)
extends ActionBuilder[UserRequest, AnyContent] with ActionTransformer[Request, UserRequest] {
def transform[A](request: Request[A]) = Future.successful {
if(request.queryString.contains("token")){
val token = request.queryString("token").head
new UserRequest(Some(token), request)
} else {
new UserRequest(None, request)
}
}
def PermissionCheckAction(implicit ec: ExecutionContext) = new ActionFilter[UserRequest] {
def executionContext = ec
def filter[A](input: UserRequest[A]) = Future.successful {
if (input.user.isEmpty)
Some(Results.Unauthorized)
else
None
}
}
}
还有控制器:
class ResultsController @Inject()(
adRepo: AdRepository,
userAction : UserAction
) extends InjectedController {
如何在父控制器中重构注入,并将useraction应用于控制器中的所有操作?
答案 0 :(得分:0)
您必须将自定义操作应用于每个控制器端点。在您的情况下,请将自定义操作应用于控制器中需要身份验证的每个功能。
在文档中往下看,您会发现:
def tagItem(itemId: String, tag: String)(implicit ec: ExecutionContext) =
(userAction andThen ItemAction(itemId) andThen PermissionCheckAction) { request =>
request.item.addTag(tag)
Ok("User " + request.username + " tagged " + request.item.id)
}
request
现在是UserRequest
,并且已经检查了权限。
修改
由于您没有ItemAction
,只需将行重写为:
(userAction andThen PermissionCheckAction)
答案 1 :(得分:0)
另一种可行的方法是将权限检查操作提取到特征:
trait AuthFilter {
implicit val ec: ExecutionContext
val userAction: UserAction
def UserActionWithPermissionCheck: ActionBuilder[UserRequest, AnyContent] = userAction andThen userAction.PermissionCheckAction
}
然后在需要时使用此过滤器:
class ResultsController @Inject()(val userAction : UserAction)(implicit val ec: ExecutionContext)
extends InjectedController with AuthFilter {
def tagItemProtected(itemId: String, tag: String) =
UserActionWithPermissionCheck { request =>
Ok("UserReq: " + request)
}
def tagItem(itemId: String, tag: String) =
userAction { request =>
Ok("UserReq: " + request)
}
}