简体   繁体   中英

How to implement Secure.Authenticator in scala Controller?

I am following this guide - https://www.playframework.com/documentation/2.1.1/JavaGuide4#Implementing-authenticators

I have implemented the authenticator as below in 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.

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. Is this the reason this is not working? How do I get it to work with 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:

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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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