Authentication using Actions in Play Framework

Actions in Play Framework
Table of contents
Reading Time: < 1 minute

Actions in Play Framework plays an important, 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 Authentication using Actions in Play Framework: Play Authentication

Happy Learning !! 🙂

 

Written by 

Geetika Gupta is a software consultant having more than 2.5 years of experience. She enjoys coding in languages such as C, C++, Java, Scala and also has a good knowledge of big data technologies like Spark, Hadoop, Hive and Presto and is currently working on Akka-HTTP and dynamoDB. Her hobbies include watching television, listening to music and travelling.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading