Skip to content

Instantly share code, notes, and snippets.

@owainlewis
Last active September 19, 2018 09:16
Show Gist options
  • Select an option

  • Save owainlewis/d59444a1d1a4865b770b to your computer and use it in GitHub Desktop.

Select an option

Save owainlewis/d59444a1d1a4865b770b to your computer and use it in GitHub Desktop.
Play framework HTTP token based authentication
package controllers.api
import play.api.mvc.{ Controller, Action }
import models._
import dao._
object Discussion extends Controller with TokenAuthentication {
def index = withAPIToken { user => { request =>
Ok(Json.toJson(DiscussionDAO.all))
}}
}
package controllers.api
import dao.UserDAO
import play.api.mvc._
import models.User
trait TokenAuthentication { self: Controller =>
/**
* Extract an optional token from a request header if it is in the correct format
*
* Example:
*
* extractToken("Token token=123") => Some("123")
*
* @param authHeader An authentication header i.e "Token token=123"
*/
def extractToken(authHeader: String): Option[String] = {
authHeader.split("Token token=") match {
case Array(_, token) => Some(token)
case _ => None
}
}
/**
* Fetch an API token from the request headers
*
* If one exists then allow the request else deny it
*
* curl -i https://discusslr.com/api/discussions -H "Authorization: Token token=TOKEN"
*/
def withAPIToken(f: => User => Request[AnyContent] => Result) = Action { implicit request =>
request.headers.get("Authorization") flatMap { authHeaderToken =>
extractToken(authHeaderToken) flatMap { token =>
UserDAO.findOneByToken(token) map { user =>
f(user)(request)
}
}
} getOrElse Unauthorized("Invalid API token")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment