Skip to content
This repository has been archived by the owner on Apr 10, 2019. It is now read-only.

Commit

Permalink
#3, feature: Basic security extractor
Browse files Browse the repository at this point in the history
  • Loading branch information
slavaschmidt committed Mar 7, 2016
1 parent 4cdd346 commit 0dcf518
Showing 1 changed file with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package de.zalando.play.controllers

import play.api.mvc.RequestHeader
import sun.misc.BASE64Decoder

/**
* @author slasch
* @since 07.03.2016.
*/
object SwaggerSecurityExtractors extends BasicAuthSecurityExtractor {

def basicAuth[User >: Any](header: RequestHeader)(convertToUser: (String, String) => User): Option[User] =
header.headers.get("authorization").map { basicAuth =>
decodeBasicAuth(basicAuth).map(p => convertToUser(p._1, p._2))
}

}

trait BasicAuthSecurityExtractor {
private val basicSt = "basic "

protected def decodeBasicAuth(auth: String): Option[(String, String)] = {
lazy val basicReqSt = auth.substring(0, basicSt.length())
lazy val basicAuthSt = auth.replaceFirst(basicReqSt, "")
lazy val decoder = new BASE64Decoder() //BESE64Decoder is not thread safe
lazy val decodedAuthSt = new String(decoder.decodeBuffer(basicAuthSt), "UTF-8")
lazy val usernamePassword = decodedAuthSt.split(":")

if (auth.length() < basicSt.length()) None
else if (basicReqSt.toLowerCase() != basicSt) None
else if (usernamePassword.length != 2) None
else Some(usernamePassword.head, usernamePassword.last)
}

}

0 comments on commit 0dcf518

Please sign in to comment.