Last active
September 19, 2018 09:16
-
-
Save owainlewis/d59444a1d1a4865b770b to your computer and use it in GitHub Desktop.
Play framework HTTP token based authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | |
| }} | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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