Paul Lam
Paul Lam

Reputation: 1819

Decorating a Scala Play Controller with Java class Secured extends Security.Authenticator

I'm refactoring a Play 2.3 app in Java to Scala. Existing Java controllers are decorated like so for authentication.

@Security.Authenticated(Secured.class) public class Application extends Controller { ... }

The signature of Secured.java is:

public class Secured extends Security.Authenticator { ... }

How might I decorate my Scala controller with the same Secured.java?

I've tried not doing that by writing a second Secured2.scala as a trait and doing authentication the Scala way in Play but many of the existing templates rely on Secured.java to get the current user so that's why I'm trying to make my Scala controller compatible with the Java Secured class.

Upvotes: 1

Views: 629

Answers (1)

Alex Garibay
Alex Garibay

Reputation: 391

I don't think you'd be able to use the same Java class for authentication using the scala API of play. But here's how you'd do it using the scala API and you can fill in the gaps with your Secured class code:

trait Authentication {
  // Define what you want your auth header to be
  val AUTH_TOKEN_HEADER = "X-AUTH-TOKEN"

  object Authenticated extends Security.AuthenticatedBuilder(checkHeader(_), onUnauthorized(_))

  def checkHeader(request: RequestHeader): Option[String] = {
    request.headers.get(AUTH_TOKEN_HEADER) flatMap { token =>
      // do a check to see if there is a user and get their name
    }
  }

  def onUnauthorized(request: RequestHeader) = {
    // Do something when the user isn't authorized to access a route
    Results.Unauthorized
  }
}

trait SecuredController extends Controller with Authentication

And here is how it would look in an actual controller:

object SomeController extends SecuredController {
  def someApi = Authenticated { req =>
    // do something
    // The username is available in the request
    val username: String = req.user
    Ok
  }
}

Upvotes: 2

Related Questions