Play Basic Authentication

DZone 's Guide to

Play Basic Authentication

In this post, we'll show you how to quickly add some basic authentication protocols to your Play Framework-based web application.

· Security Zone ·
Free Resource

This post is about how to use Basic Authentication to secure your Play Action or rest end point from external inference. It simply uses HTTP header and doesn't require a cookies session or a 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 encodes user's credentials with Base64, i.e a binary-to-text encoding scheme that is not encrypted or hashed, but your access to your rest end point can be restricted by implementing Basic Authentication.

Let's start with Play Basic Authentication:

1. First of all, we need to create a 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 an action (indexWithAuthentication) to 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, which is a method in the UserRepository where you can add your authentication.

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

GET        /withAuthentication        controllers.HomeController.indexWithAuthentication

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

I hope this post is helpful to you!

You can get the source code from here.


authentication ,scala ,basic authenication example ,security ,web security

Published at DZone with permission of Teena Vashist . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}