在Play 2.5.x中使用play2-auth进行基本身份验证

时间:2016-06-07 02:21:14

标签: scala playframework playframework-2.0

在下面的示例中,目的是构建一个简单的play2-auth程序,该程序对用户进行身份验证,直到他们注销为止。

问题是我在ManageSession.scala中收到以下编译错误:

  

对象创建不可能,因为:它有6个未实现的成员

这是源代码,我从play2-auth网站上取样并进行了简化,但功能签名是相同的:

AuthConfigImpl.scala:

import play.api.mvc._
import scala.reflect._
import play.api.mvc.RequestHeader
import play.api.http.Status
import play.api.mvc.Results._
import jp.t2v.lab.play2.auth._

trait AuthConfigImpl extends AuthConfig {

  type Id = String
  type User = Account
  val idTag: ClassTag[Id] = classTag[Id]
  val sessionTimeoutInSeconds: Int = 3600

  def loginSucceeded(request: RequestHeader): Result = Redirect("/main",Status.OK)
  def logoutSucceeded(request: RequestHeader): Result = Redirect("/main",Status.OK)
  def authenticationFailed(request: RequestHeader): Result = Redirect("/main",Status.OK)
  def authorizationFailed(request: RequestHeader): Result = Forbidden("no permission")
  def authorize(user: User, authority: Authority): Boolean = true

//override lazy val cookieSecureOption: Boolean = 
//  play.api.Play.current.configuration.getBoolean("auth.cookie.secure").getOrElse(true)

}

ManageSession.scala:

import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import scala.concurrent.ExecutionContext.Implicits.global
import jp.t2v.lab.play2.auth._

object ManageSession extends Controller with LoginLogout with AuthConfigImpl {

  val loginForm = Form {
    mapping("email" -> email, "password" -> text)(Account.authenticate)
    (_.map(u => (u.email, "")))
      .verifying("Invalid email or password", result => result.isDefined)
  }

  def login = Action { implicit request =>
    Ok(views.html.showlogin())
  }

  def logout = Action { implicit request =>
    //gotoLogoutSucceeded
    Ok("logged out")
  }

  def authenticate = Action { implicit request =>
    loginForm.bindFromRequest.fold(
      formWithErrors => BadRequest(views.html.showlogin()),
      user => Ok("logged in") // gotoLoginSucceeded(user.get.email)
    )
  }
}

Account.scala:

case class Account(id: Int, email: String, password: String, name: String)

object Account  {

  def authenticate(email: String, password: String): Option[Account] = {
      if (email == "test")
          Some(Account (1, "test", "abc", "Paul"))
      else
          None
  }

1 个答案:

答案 0 :(得分:1)

play2-auth中的

-CgotoLoginSucceeded返回gotoLogoutSucceeded,但Future[Result]需要Action。您可以使用Result

解决此问题
Action.async

您的def logout = Action.async { implicit request => // do something... gotoLogoutSucceeded } import scala.concurrent.Future def authenticate = Action.async { implicit request => loginForm.bindFromRequest.fold( formWithErrors => Future.successful(BadRequest(views.html.showlogin())), user => gotoLoginSucceeded(user.get.id) ) } 也必须这样做。所有这些方法都应该返回AuthConfig。例如

Future[Result]

等等。