如何在 Scala Controller 中实现 Secure.Authenticator?

How to implement Secure.Authenticator in scala Controller?

我正在遵循本指南 - https://www.playframework.com/documentation/2.1.1/JavaGuide4#Implementing-authenticators

我已经在 Scala 中实现了如下验证器:

package controllers

import play.mvc.Security
import play.mvc.Http.Context
import play.mvc.Result
import play.mvc.Results

class Secured extends Security.Authenticator {

  override def getUsername(ctx: Context) : String = {
    return ctx.session().get("username");
  }  

  override def onUnauthorized(ctx: Context) : Result = {
    Results.redirect(routes.Application.login())
  }

}

我将它作为注释应用到下面控制器中的 hello 操作。

package controllers

import services.UserServiceImpl
import models.User._
import play.api.mvc._
import play.mvc.Security.Authenticated

object Application extends Controller {

  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }

  @Authenticated(classOf[Secured])
  def hello = Action {
    Ok("Hello")
  }

  def login = Action {
    Ok("Login")
  }

}

我正在使用 Play 2.4 和 play.api.mvc.Controller 而不是指南中的 play.mvc.Controller。这是这不起作用的原因吗?如何让它与 play.api.mvc.Controller 一起使用?

我想一个例子可能有助于解释事情。如果您想在 Play Scala 中使用类似的功能,您可以执行以下操作:

object AuthenticatedAction extends ActionBuilder[Request] {
  def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
    request.session.get("username") match {
      case Some(user) => block(request)
      case None => Redirect(routes.Application.login())
  }
}

然后您将在您的控制器中使用它:

def hello = AuthenticatedAction { implicit request =>
  Ok("Hello")
}