-
Notifications
You must be signed in to change notification settings - Fork 12
/
OIDCKeycloak.scala
267 lines (229 loc) · 10.5 KB
/
OIDCKeycloak.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package akkahttp.oidc
import dasniko.testcontainers.keycloak.KeycloakContainer
import io.circe.parser.decode
import io.circe.syntax.*
import org.apache.pekko.actor.ActorSystem
import org.apache.pekko.http.scaladsl.Http
import org.apache.pekko.http.scaladsl.model.*
import org.apache.pekko.http.scaladsl.model.headers.{HttpChallenge, OAuth2BearerToken}
import org.apache.pekko.http.scaladsl.server.Directives.*
import org.apache.pekko.http.scaladsl.server.{AuthenticationFailedRejection, Directive1, Route}
import org.apache.pekko.http.scaladsl.unmarshalling.Unmarshal
import org.keycloak.TokenVerifier
import org.keycloak.adapters.KeycloakDeploymentBuilder
import org.keycloak.admin.client.{CreatedResponseUtil, Keycloak}
import org.keycloak.jose.jws.AlgorithmType
import org.keycloak.representations.AccessToken
import org.keycloak.representations.adapters.config.AdapterConfig
import org.keycloak.representations.idm.{ClientRepresentation, CredentialRepresentation, UserRepresentation}
import org.slf4j.{Logger, LoggerFactory}
import java.math.BigInteger
import java.nio.file.{Files, Paths}
import java.security.spec.RSAPublicKeySpec
import java.security.{KeyFactory, PublicKey}
import java.time.Duration
import java.util
import java.util.{Base64, Collections}
import scala.concurrent.{ExecutionContextExecutor, Future}
import scala.jdk.CollectionConverters.CollectionHasAsScala
import scala.sys.process.{Process, stringSeqToProcess}
import scala.util.{Failure, Success}
/**
* A "one-click" Keycloak OIDC server with pekko-http frontend.
* The pekko-http endpoint /users loads all users from the Keycloak server.
*
* Inspired by:
* https://scalac.io/blog/user-authentication-keycloak-1
*
* Uses a HTML5 client: src/main/resources/KeycloakClient.html
* instead of the separate React client
*
* Runs with:
* https://github.com/dasniko/testcontainers-keycloak
* automatically configured for convenience
*
* Doc:
* https://www.keycloak.org/docs/latest/securing_apps/#_javascript_adapter
* https://pekko.apache.org/docs/pekko-http/1.0/routing-dsl/directives/security-directives/index.html
*/
object OIDCKeycloak extends App with CORSHandler with JsonSupport {
val logger: Logger = LoggerFactory.getLogger(this.getClass)
implicit val system: ActorSystem = ActorSystem()
implicit val executionContext: ExecutionContextExecutor = system.dispatcher
def runKeycloak() = {
// Pin to same version as "keycloakVersion" in build.sbt
val keycloak = new KeycloakContainer("quay.io/keycloak/keycloak:26.0.1")
// Keycloak config taken from:
// https://github.com/keycloak/keycloak/blob/main/examples/js-console/example-realm.json
.withRealmImportFile("keycloak_realm_config.json")
.withStartupTimeout(Duration.ofSeconds(180))
keycloak.start()
logger.info("Running Keycloak on URL: {}", keycloak.getAuthServerUrl)
keycloak
}
def configureKeycloak(keycloak: KeycloakContainer) = {
val adminClientId = "admin-cli"
def initAdminClient() = {
val keycloakAdminClient = keycloak.getKeycloakAdminClient()
logger.info("Connected to Keycloak server version: {}", keycloakAdminClient.serverInfo().getInfo.getSystemInfo.getVersion)
keycloakAdminClient
}
def createTestUser(keycloakAdminClient: Keycloak): Unit = {
val username = "test"
val password = "test"
val usersResource = keycloakAdminClient.realm("test").users()
val user = new UserRepresentation()
user.setEnabled(true)
user.setUsername(username)
user.setFirstName("First")
user.setLastName("Last")
user.setEmail(s"$username@test.local")
user.setAttributes(Collections.singletonMap("origin", util.Arrays.asList(adminClientId)))
// Create user
val response = usersResource.create(user)
val userId = CreatedResponseUtil.getCreatedId(response)
// Define password credential
val passwordCred = new CredentialRepresentation()
passwordCred.setTemporary(false)
passwordCred.setType(CredentialRepresentation.PASSWORD)
passwordCred.setValue(password)
// Set password credential
val userResource = usersResource.get(userId)
userResource.resetPassword(passwordCred)
logger.info(s"User $username created with userId: $userId")
logger.info(s"User $username/$password may sign in via: http://localhost:${keycloak.getHttpPort}/realms/test/account")
}
def createClientConfig(keycloakAdminClient: Keycloak): Unit = {
val clientId = "my-test-client"
val clientRepresentation = new ClientRepresentation()
clientRepresentation.setClientId(clientId)
clientRepresentation.setProtocol("openid-connect")
val redirectUriTestingOnly = new util.ArrayList[String]()
redirectUriTestingOnly.add("http://127.0.0.1:6002/*")
clientRepresentation.setRedirectUris(redirectUriTestingOnly)
val webOriginsTestingOnly = new util.ArrayList[String]()
webOriginsTestingOnly.add("*")
clientRepresentation.setWebOrigins(webOriginsTestingOnly)
val resp = keycloakAdminClient.realm("test").clients().create(clientRepresentation)
logger.info(s"Successfully created client config for clientId: $clientId, response status: " + resp.getStatus)
val clients: util.List[ClientRepresentation] = keycloakAdminClient.realm("test").clients().findByClientId(clientId)
logger.info(s"Successfully read ClientRepresentation for clientId: ${clients.get(0).getClientId}")
}
val keycloakAdminClient = initAdminClient()
createTestUser(keycloakAdminClient)
createClientConfig(keycloakAdminClient)
keycloakAdminClient
}
def runBackendServer(keycloak: KeycloakContainer): Unit = {
val config = new AdapterConfig()
config.setAuthServerUrl(keycloak.getAuthServerUrl)
config.setRealm("test")
config.setResource("my-test-client")
val keycloakDeployment = KeycloakDeploymentBuilder.build(config)
logger.info("Dynamic authServerBaseUrl: " + keycloakDeployment.getAuthServerBaseUrl)
def generateKey(keyData: KeyData): PublicKey = {
val keyFactory = KeyFactory.getInstance(AlgorithmType.RSA.toString)
val urlDecoder = Base64.getUrlDecoder
val modulus = new BigInteger(1, urlDecoder.decode(keyData.n))
val publicExponent = new BigInteger(1, urlDecoder.decode(keyData.e))
keyFactory.generatePublic(new RSAPublicKeySpec(modulus, publicExponent))
}
val publicKeys: Future[Map[String, PublicKey]] =
Http().singleRequest(HttpRequest(uri = keycloakDeployment.getJwksUrl)).flatMap(response => {
val json = Unmarshal(response).to[String]
val keys = json.map { jsonString =>
decode[Keys](jsonString) match {
case Right(keys) => keys
case Left(error) => throw new RuntimeException(error.getMessage)
}
}
keys.map(_.keys.map(k => (k.kid, generateKey(k))).toMap)
})
// Alternative:
// https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/security-directives/authenticateOAuth2.html
def authenticate: Directive1[AccessToken] =
extractCredentials.flatMap {
case Some(OAuth2BearerToken(token)) =>
onComplete(verifyToken(token)).flatMap {
case Success(Some(t)) =>
logger.info(s"Token: '${token.take(10)}...' is valid")
provide(t)
case _ =>
logger.warn(s"Token: '${token.take(10)}...' is not valid")
reject(AuthenticationFailedRejection(AuthenticationFailedRejection.CredentialsRejected, HttpChallenge("JWT", None)))
}
case _ =>
logger.warn("No token present in request")
reject(AuthenticationFailedRejection(AuthenticationFailedRejection.CredentialsMissing, HttpChallenge("JWT", None)))
}
def verifyToken(token: String): Future[Option[AccessToken]] = {
logger.info(s"About to verify token...")
val tokenVerifier = TokenVerifier.create(token, classOf[AccessToken])
for {
publicKey <- publicKeys.map(_.get(tokenVerifier.getHeader.getKeyId))
} yield publicKey match {
case Some(pk) =>
val token = tokenVerifier.publicKey(pk).verify().getToken
Some(token)
case None =>
logger.warn(s"No public key found for id: ${tokenVerifier.getHeader.getKeyId}")
None
}
}
val userRoutes: Route =
logRequest("log request") {
path("users") {
get {
authenticate { token =>
// To have "real data": Read 'UserRepresentation' from Keycloak via the admin client and then strip down
val usersOrig = adminClient.realm("test").users().list().asScala
val usersBasic = UsersKeycloak(usersOrig.collect(each => UserKeycloak(Option(each.getFirstName), Option(each.getLastName), Option(each.getEmail))).toSeq)
complete(HttpResponse(StatusCodes.OK, entity = usersBasic.asJson.noSpaces))
}
}
}
}
val getFromDocRoot: Route =
get {
concat(
pathSingleSlash {
val content = new String(Files.readAllBytes(Paths.get("src/main/resources/KeycloakClient.html")))
val renderedPage = content.replaceAll("%%PORT%%", keycloak.getFirstMappedPort.toString)
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, renderedPage))
}
)
}
val getResource: Route =
pathPrefix("js") {
path(Remaining) { file =>
getFromFile(s"src/main/resources/js/$file")
}
}
val routes: Route = corsHandler(userRoutes) ~ getFromDocRoot ~ getResource
val bindingFuture = Http().newServerAt("127.0.0.1", 6002).bind(routes)
bindingFuture.onComplete {
case Success(b) =>
logger.info(s"Http server started, listening on: http:/${b.localAddress}")
case Failure(e) =>
logger.info(s"Server could not bind to... Exception message: ${e.getMessage}")
system.terminate()
}
}
// Login with admin/admin
def adminConsole(keycloakURL: String) = {
val os = System.getProperty("os.name").toLowerCase
if (os == "mac os x") Process(s"open $keycloakURL").!
}
// Login with test/test
def browserClient() = {
val os = System.getProperty("os.name").toLowerCase
if (os == "mac os x") Process(s"open http://127.0.0.1:6002").!
else if (os == "windows 10") Seq("cmd", "/c", s"start http://127.0.0.1:6002").!
}
val keycloak = runKeycloak()
val adminClient = configureKeycloak(keycloak)
adminConsole(keycloak.getAuthServerUrl)
runBackendServer(keycloak)
browserClient()
Thread.sleep(100000)
}