Play Basic Authentication

Table of contents
Reading Time: < 1 minute

This blog is about Basic Authentication for securing your Play Action or can say rest end point from external inference, It simply uses HTTP header and doesn’t require cookies session and login page for authentication.

The credential of the user has to be sent in the header of each HTTP request. HTTP Basic authentication does not provide high-level protection as it just encoded user’s credential with Base64 i.e binary to text encoding scheme that is not encrypted or hashed, but you can be restricted to access your rest end point by implementing Basic Authentication.

Let’s start with Play Basic Authentication:

1. First of all, we need to create Basic Authentication implementation in “BasciAuthentication.scala”:

object BasicAuthentication extends Controller {
  def apply[A](userExists: (String, String) => Boolean)(action: Action[A]): Action[A] =
    Action.async(action.parser) { request =>
      request.headers.get("Authorization").flatMap { authorization =>
        authorization.split(" ").drop(1).headOption.filter { encoded =>
          val authInfo = new String(decodeBase64(encoded.getBytes)).split(":").toList

          allCatch.opt {
            val (username, password) = (authInfo.head, authInfo(1))

            userExists(username, password)
          } getOrElse false
      }.map(_ => action(request)).getOrElse {
        Future.successful(Unauthorized("Authentication Failed"))

You can use BasicAuthentication on any Action that you want to protect.

2. Next, we need to create action(indexWithAuthentication) on which we are going to apply basic authentication:

def indexWithAuthentication =
  BasicAuthentication(userRepository.findUser) {
    Action { implicit request =>
      Ok("Authentication Successful")

Here, we used BasicAuthentication for protecting the Action and findUser is a method in UserRepository where you can add your authentication.

3. Added route(/withAuthentication) in routes file:

GET        /withAuthentication        controllers.HomeController.indexWithAuthentication

4. You can test rest end point(/withAuthentication) using Postman(on which you can send a request and view response), you just need to select the type of Authentication i.e Basic Auth and pass your username and password.

I hope this blog is helpful to you!

Get source code from here


Written by 

Teena is a Senior Software Consultant at Knoldus Software LLP having more than 3 year experience working in Scala, Akka, Play Framework. She is very enthusiastic towards her work and good at working in team. She is very much keen to learn new technologies. She is familiar with programming languages such as Scala, Play Framework, Akka, Javascript, HTML, Java.