简体   繁体   English

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

[英]How to implement Secure.Authenticator in scala Controller?

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

I have implemented the authenticator as below in Scala: 我已经在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())
  }

}

I applied it as an annotation to the hello action in the below controller. 我将其作为注释应用于以下控制器中的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")
  }

}

I am using Play 2.4 and play.api.mvc.Controller instead of play.mvc.Controller as in the guide. 我正在使用Play 2.4和play.api.mvc.Controller而不是指南中的play.mvc.Controller。 Is this the reason this is not working? 这是不起作用的原因吗? How do I get it to work with play.api.mvc.Controller? 如何使其与play.api.mvc.Controller一起使用?

I figured an example would probably help explain things. 我想出一个例子可能会帮助解释事情。 If you want similar functionality in Play Scala you would do something like the following: 如果要在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())
  }
}

You would then use this in your controller: 然后,您将在控制器中使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM