Authentication using Actions in Play Framework


Actions plays an important role in Play Framework, the requests received by a Play application are handled by an Action. Action composition is an incredibly powerful way to enhance or restrict controller behaviour. In Play Framework controllers consist of methods that create Action objects to handle the incoming requests.

play.api.mvc.Action is basically a (play.api.mvc.Request => play.api.mvc.Result) function that handles a request and generates a result to be sent to the client.

We can provide authentication to our application by using the ActionBuilder trait. To implement ActionBuilder we need to implement the invokeBlock method, it takes the current request and a block of code as arguments.

def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result])

Customizing Your ActionBuilder

Suppose in your application you want some operations to be performed on every request, for that you can create your own ActionBuilder and perform the operations in it.

Firstly you need to extend the ActionBuilder and provide implementation for the invokeBlock method.

In our use case suppose we want every request with a parameter username in the request header set to any one of ‘Jake’, ‘Alex’, ‘Ryan’, ‘Nicholas’ will  be able to access our application, then we can write our code as:

case class UserRequest[A](val userName: String, val request: Request[A])
  extends WrappedRequest[A](request)
object SecuredAction extends ActionBuilder[UserRequest] {

  override def invokeBlock[A](request: Request[A],
      block: (UserRequest[A]) => Future[Result]): Future[Result] = {
    val userName = request.headers.get("username").fold("")(identity)
    if (UserService.getAllUsers().contains(User(userName))) {
      block(UserRequest(userName, request))
    } else {
      Future.successful(Results.Unauthorized("Unauthorized access !!"))
    }
  }
}

All the other requests with different username in header are given ‘Unauthorized access’. Using this only some of the authorized user will be able to access our application, response to other requests will be sent back from the invokeBlock itself and your controller code will not be executed.

Here is a simple application demonstrating the same: Play Authentication

Happy Learning !! 🙂

 

Advertisements
This entry was posted in knoldus, Play Framework, sbt, Scala, Security, Web, web application. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s