Skip to content

Instantly share code, notes, and snippets.

View bandrzejczak's full-sized avatar

Bartek Andrzejczak bandrzejczak

View GitHub Profile
def authorized: Directive1[OAuth2Token] = {
bearerToken.flatMap {
case Some(token) =>
onComplete(tokenVerifier.verifyToken(token)).flatMap {
_.map(username => provide(OAuth2Token(token, username)))
.recover {
case ex =>
logger.error(ex, "Couldn't log in using provided authorization token")
reject(AuthorizationFailedRejection).toDirective[Tuple1[OAuth2Token]]
}
private def bearerToken: Directive1[Option[String]] =
for {
authBearerHeader <- optionalHeaderValueByType(classOf[Authorization]).map(extractBearerToken)
xAuthCookie <- optionalCookie("X-Authorization-Token").map(_.map(_.value))
} yield authBearerHeader.orElse(xAuthCookie)
private def extractBearerToken(authHeader: Option[Authorization]): Option[String] =
authHeader.collect {
case Authorization(OAuth2BearerToken(token)) => token
}
class KeycloakTokenVerifier(keycloakDeployment: KeycloakDeployment) extends TokenVerifier {
implicit val executionContext = ExecutionContext.fromExecutor(new ForkJoinPool(2))
def verifyToken(token: String): Future[String] = {
Future {
RSATokenVerifier.verifyToken(
token,
keycloakDeployment.getRealmKey,
keycloakDeployment.getRealmInfoUrl
).getPreferredUsername
trait TokenVerifier {
def verifyToken(token: String): Future[String]
}
name := "keycloak-akka-http"
version := "1.0"
scalaVersion := "2.11.7"
val akkaV = "2.4.1"
val akkaStreamV = "2.0-M2"
val akka = Seq (
<!doctype html>
<html ng-cloak>
<head>
<meta charset="utf-8">
<title>Keycloak Test</title>
</head>
<body ng-cloak>
<h1>
Hello, {{ currentUser.username }}
</h1>
function bootstrapAngular(keycloak, userInfo) {
angular.module('KeycloakApp')
.run(function ($rootScope) {
// store the token in header's defaults or a cookie - we'll cover that with the backend in part 2
$rootScope.currentUser = {
username: userInfo.name || userInfo.preferred_username,
roles: keycloak.realmAccess.roles
};
keycloak.loadUserInfo().success(function (userInfo) {
// Bootstrap Angular
});
var keycloakConfig = {
"url": "http://localhost:8080/auth",
"realm": "master",
"clientId": "frontend",
"credentials": {
"secret": "1a1b98b6-66c5-4384-a4b4-7361717e773e"
}
};
var keycloak = Keycloak(keycloakConfig);
keycloak.init({
Metrics Java C++
Iterations 100 100
Min. iteration time [ms] 277.933 15.293
Max. iteration time [ms] 566.202 15.636
Avg. iteration time [ms] 375.815 15.463