Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Framework REST with basic authentication and SSL

I am new to this authentication area. I searched a lot but was not able to find a way to authenticate the REST calls made to the Play server. What are the various ways and best practice?

like image 380
Prakash Avatar asked Apr 07 '15 12:04

Prakash


People also ask

Is basic authentication secure FOR REST API?

Basic authentication is an HTTP-based authentication approach and is the simplest way to secure REST APIs. It uses a Base64 format to encode usernames and passwords, both of which are stored in the HTTP header.

How do you handle basic authentication in Rest assured?

Basic authentication helps you access the secured APIs and perform actions on the resources. Rest assured has four types of authentication schemes. They are basic, digest, form, and OAuth authentication. By default, rest assured uses a challenge-response mechanism.


1 Answers

A very easy way is to use Action Composition. For a sample, take a look at this Gist provided by Guillaume Bort: https://gist.github.com/guillaumebort/2328236. If you want to use it in an async action, you can write something like:

def BasicSecured[A](username: String, password: String)(action: Action[A]): Action[A] = Action.async(action.parser) { request =>
  request.headers.get("Authorization").flatMap { authorization =>
    authorization.split(" ").drop(1).headOption.filter { encoded =>
      new String(org.apache.commons.codec.binary.Base64.decodeBase64(encoded.getBytes)).split(":").toList match {
        case u :: p :: Nil if u == username && password == p => true
        case _ => false
      }
    }
  }.map(_ => action(request)).getOrElse {
    Future.successful(Unauthorized.withHeaders("WWW-Authenticate" -> """Basic realm="Secured Area""""))
  }
}

SSL does not have anything to do with basic authentication. You can use HTTPS for API either directly or through a front-end HTTP server like ngnix. There are pretty good details in Play documentation on this subject.

like image 149
centr Avatar answered Sep 27 '22 17:09

centr