【问题标题】:Global scope for actions for scala-oauth2-provider with play2 scala具有 play2 scala 的 scala-oauth2-provider 的全局操作范围
【发布时间】:2023-04-02 07:51:01
【问题描述】:

我无法处理范围(访问级别,OAuth2)和 Scala。 我想要这些用例:

  • 为控制器定义一个全局范围。能够为某些操作覆盖此全局参数。
  • 不要定义全局参数,而是为每个操作指定范围

此代码是我想要的示例:

package controllers

import scalaoauth2.provider.OAuth2Provider

import scala.concurrent.ExecutionContext.Implicits.global

class MyController extends GlobalAuthController

  // define global scope
  implicit val scope = Scope.User

  // By default, if no parameter, the scope is the implicit value previously defined
  def user = ActionWithAuth { request =>
    Ok("hello user or admin")
  }

  def admin = ActionWithAuth(Scope.Admin) {
    Ok("hello admin")
  }
}

我使用nulab/scala-oauth2-provider 库。根据文档,我创建了这个:

trait OAuth2ActionComposition {
  implicit val executionContext: ExecutionContext

  def ActionWithAuth[U](implicit scope: Scope): ActionBuilder[({type λ[A] = AuthInfoRequest[A, User]})#λ] = {
    Logger.info("Scope : " + scope.toString)
    AuthorizedActionFunction(new Users(scope)) compose Action
  }
}

object OAuth2ActionComposition extends OAuth2ActionComposition {
  implicit val executionContext: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext
}

但是使用该代码我得到一个编译错误:在行 def user = ActionWithAuth { request => see this image 缺少参数类型

当我显式传递隐式参数(例如def user = ActionWithAuth(scope) { request =>)时,它可以工作。哇!但这并不方便。

我无法弄清楚为什么会出现此错误。我尝试了其他一些方法,但没有成功。

【问题讨论】:

    标签: scala playframework scope oauth-2.0


    【解决方案1】:

    感谢Silhouette 内置com.mohiva.play.silhouette.api.Authorization,我“修复”了它。 见http://silhouette.mohiva.com/docs/authorization

    确实,多亏了 Silhouette,可以定义授权。例如。 :

    case class WithProvider(provider: String) extends Authorization[User, CookieAuthenticator] {
      def isAuthorized[B](user: User, authenticator: CookieAuthenticator)(
        implicit request: Request[B], messages: Messages) = {
    
        Future.successful(user.loginInfo.providerID == provider)
      }
    }
    

    然后,使用这个“过滤器:

    def myAction = SecuredAction(WithProvider("twitter")) { implicit request =>
      // do something here
    }
    

    这些过滤器可以轻松组合。

    【讨论】:

    • 欢迎来到 Stack Overflow!虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。看看这篇文章:How do I write a good answer.
    • 好的,我明白了。我会尝试更新我的答案以匹配所需的内容。事实上,我的回答并不是对我提出的问题的直接回答。这更像是一种解决方法。这就是我这样回答的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 2010-12-12
    • 2023-03-15
    相关资源
    最近更新 更多