This repository has been archived by the owner on Apr 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
#3, feature: Basic security extractor
- Loading branch information
1 parent
4cdd346
commit 0dcf518
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
35 changes: 35 additions & 0 deletions
35
api/src/main/scala/de/zalando/play/controllers/SecurityExtractors.scala
This file contains 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
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) | ||
} | ||
|
||
} |