package io.vertx.ext.auth.oauth2.authorization.impl;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.auth.authorization.RoleBasedAuthorization;
import io.vertx.ext.auth.oauth2.authorization.KeycloakAuthorization;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class KeycloakAuthorizationImpl implements KeycloakAuthorization {
private static final JsonObject EMPTY_JSON = new JsonObject(Collections.emptyMap());
@Override
public String getId() {
return "keycloak";
}
@Override
public void getAuthorizations(User user, Handler<AsyncResult<Void>> handler) {
final JsonObject accessToken = user.attributes().getJsonObject("accessToken");
if (accessToken == null) {
handler.handle(Future.failedFuture("User doesn't contain a decoded Token"));
return;
}
final Set<Authorization> authorizations = new HashSet<>();
try {
extractApplicationRoles(accessToken, authorizations);
} catch (RuntimeException e) {
handler.handle(Future.failedFuture(e));
return;
}
try {
extractRealmRoles(accessToken, authorizations);
} catch (RuntimeException e) {
handler.handle(Future.failedFuture(e));
return;
}
user.authorizations().add(getId(), authorizations);
handler.handle(Future.succeededFuture());
}
private static void (JsonObject accessToken, Set<Authorization> authorizations) {
JsonObject resourceAccess = accessToken
.getJsonObject("resource_access", EMPTY_JSON);
for (String resource : resourceAccess.fieldNames()) {
JsonArray appRoles = resourceAccess
.getJsonObject(resource, EMPTY_JSON)
.getJsonArray("roles");
if (appRoles != null && appRoles.size() >= 0) {
for (Object el : appRoles) {
authorizations.add(
RoleBasedAuthorization
.create((String) el)
.setResource(resource));
}
}
}
}
private static void (JsonObject accessToken, Set<Authorization> authorizations) {
JsonArray appRoles = accessToken
.getJsonObject("realm_access", EMPTY_JSON)
.getJsonArray("roles");
if (appRoles != null && appRoles.size() >= 0) {
for (Object el : appRoles) {
authorizations.add(RoleBasedAuthorization.create((String) el));
}
}
}
}